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 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2548 if (Ops.size() > AddOpsInlineThreshold || 2549 Add->getNumOperands() > AddOpsInlineThreshold) 2550 break; 2551 // If we have an add, expand the add operands onto the end of the operands 2552 // list. 2553 Ops.erase(Ops.begin()+Idx); 2554 Ops.append(Add->op_begin(), Add->op_end()); 2555 DeletedAdd = true; 2556 } 2557 2558 // If we deleted at least one add, we added operands to the end of the list, 2559 // and they are not necessarily sorted. Recurse to resort and resimplify 2560 // any operands we just acquired. 2561 if (DeletedAdd) 2562 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2563 } 2564 2565 // Skip over the add expression until we get to a multiply. 2566 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2567 ++Idx; 2568 2569 // Check to see if there are any folding opportunities present with 2570 // operands multiplied by constant values. 2571 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2572 uint64_t BitWidth = getTypeSizeInBits(Ty); 2573 DenseMap<const SCEV *, APInt> M; 2574 SmallVector<const SCEV *, 8> NewOps; 2575 APInt AccumulatedConstant(BitWidth, 0); 2576 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2577 Ops.data(), Ops.size(), 2578 APInt(BitWidth, 1), *this)) { 2579 struct APIntCompare { 2580 bool operator()(const APInt &LHS, const APInt &RHS) const { 2581 return LHS.ult(RHS); 2582 } 2583 }; 2584 2585 // Some interesting folding opportunity is present, so its worthwhile to 2586 // re-generate the operands list. Group the operands by constant scale, 2587 // to avoid multiplying by the same constant scale multiple times. 2588 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2589 for (const SCEV *NewOp : NewOps) 2590 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2591 // Re-generate the operands list. 2592 Ops.clear(); 2593 if (AccumulatedConstant != 0) 2594 Ops.push_back(getConstant(AccumulatedConstant)); 2595 for (auto &MulOp : MulOpLists) 2596 if (MulOp.first != 0) 2597 Ops.push_back(getMulExpr( 2598 getConstant(MulOp.first), 2599 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2600 SCEV::FlagAnyWrap, Depth + 1)); 2601 if (Ops.empty()) 2602 return getZero(Ty); 2603 if (Ops.size() == 1) 2604 return Ops[0]; 2605 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2606 } 2607 } 2608 2609 // If we are adding something to a multiply expression, make sure the 2610 // something is not already an operand of the multiply. If so, merge it into 2611 // the multiply. 2612 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2613 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2614 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2615 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2616 if (isa<SCEVConstant>(MulOpSCEV)) 2617 continue; 2618 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2619 if (MulOpSCEV == Ops[AddOp]) { 2620 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2621 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2622 if (Mul->getNumOperands() != 2) { 2623 // If the multiply has more than two operands, we must get the 2624 // Y*Z term. 2625 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2626 Mul->op_begin()+MulOp); 2627 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2628 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2629 } 2630 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2631 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2632 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2633 SCEV::FlagAnyWrap, Depth + 1); 2634 if (Ops.size() == 2) return OuterMul; 2635 if (AddOp < Idx) { 2636 Ops.erase(Ops.begin()+AddOp); 2637 Ops.erase(Ops.begin()+Idx-1); 2638 } else { 2639 Ops.erase(Ops.begin()+Idx); 2640 Ops.erase(Ops.begin()+AddOp-1); 2641 } 2642 Ops.push_back(OuterMul); 2643 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2644 } 2645 2646 // Check this multiply against other multiplies being added together. 2647 for (unsigned OtherMulIdx = Idx+1; 2648 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2649 ++OtherMulIdx) { 2650 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2651 // If MulOp occurs in OtherMul, we can fold the two multiplies 2652 // together. 2653 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2654 OMulOp != e; ++OMulOp) 2655 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2656 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2657 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2658 if (Mul->getNumOperands() != 2) { 2659 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2660 Mul->op_begin()+MulOp); 2661 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2662 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2663 } 2664 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2665 if (OtherMul->getNumOperands() != 2) { 2666 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2667 OtherMul->op_begin()+OMulOp); 2668 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2669 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2670 } 2671 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2672 const SCEV *InnerMulSum = 2673 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2674 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2675 SCEV::FlagAnyWrap, Depth + 1); 2676 if (Ops.size() == 2) return OuterMul; 2677 Ops.erase(Ops.begin()+Idx); 2678 Ops.erase(Ops.begin()+OtherMulIdx-1); 2679 Ops.push_back(OuterMul); 2680 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2681 } 2682 } 2683 } 2684 } 2685 2686 // If there are any add recurrences in the operands list, see if any other 2687 // added values are loop invariant. If so, we can fold them into the 2688 // recurrence. 2689 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2690 ++Idx; 2691 2692 // Scan over all recurrences, trying to fold loop invariants into them. 2693 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2694 // Scan all of the other operands to this add and add them to the vector if 2695 // they are loop invariant w.r.t. the recurrence. 2696 SmallVector<const SCEV *, 8> LIOps; 2697 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2698 const Loop *AddRecLoop = AddRec->getLoop(); 2699 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2700 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2701 LIOps.push_back(Ops[i]); 2702 Ops.erase(Ops.begin()+i); 2703 --i; --e; 2704 } 2705 2706 // If we found some loop invariants, fold them into the recurrence. 2707 if (!LIOps.empty()) { 2708 // Compute nowrap flags for the addition of the loop-invariant ops and 2709 // the addrec. Temporarily push it as an operand for that purpose. 2710 LIOps.push_back(AddRec); 2711 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2712 LIOps.pop_back(); 2713 2714 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2715 LIOps.push_back(AddRec->getStart()); 2716 2717 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2718 // This follows from the fact that the no-wrap flags on the outer add 2719 // expression are applicable on the 0th iteration, when the add recurrence 2720 // will be equal to its start value. 2721 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2722 2723 // Build the new addrec. Propagate the NUW and NSW flags if both the 2724 // outer add and the inner addrec are guaranteed to have no overflow. 2725 // Always propagate NW. 2726 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2727 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2728 2729 // If all of the other operands were loop invariant, we are done. 2730 if (Ops.size() == 1) return NewRec; 2731 2732 // Otherwise, add the folded AddRec by the non-invariant parts. 2733 for (unsigned i = 0;; ++i) 2734 if (Ops[i] == AddRec) { 2735 Ops[i] = NewRec; 2736 break; 2737 } 2738 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2739 } 2740 2741 // Okay, if there weren't any loop invariants to be folded, check to see if 2742 // there are multiple AddRec's with the same loop induction variable being 2743 // added together. If so, we can fold them. 2744 for (unsigned OtherIdx = Idx+1; 2745 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2746 ++OtherIdx) { 2747 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2748 // so that the 1st found AddRecExpr is dominated by all others. 2749 assert(DT.dominates( 2750 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2751 AddRec->getLoop()->getHeader()) && 2752 "AddRecExprs are not sorted in reverse dominance order?"); 2753 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2754 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2755 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2756 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2757 ++OtherIdx) { 2758 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2759 if (OtherAddRec->getLoop() == AddRecLoop) { 2760 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2761 i != e; ++i) { 2762 if (i >= AddRecOps.size()) { 2763 AddRecOps.append(OtherAddRec->op_begin()+i, 2764 OtherAddRec->op_end()); 2765 break; 2766 } 2767 SmallVector<const SCEV *, 2> TwoOps = { 2768 AddRecOps[i], OtherAddRec->getOperand(i)}; 2769 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2770 } 2771 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2772 } 2773 } 2774 // Step size has changed, so we cannot guarantee no self-wraparound. 2775 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2776 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2777 } 2778 } 2779 2780 // Otherwise couldn't fold anything into this recurrence. Move onto the 2781 // next one. 2782 } 2783 2784 // Okay, it looks like we really DO need an add expr. Check to see if we 2785 // already have one, otherwise create a new one. 2786 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2787 } 2788 2789 const SCEV * 2790 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2791 SCEV::NoWrapFlags Flags) { 2792 FoldingSetNodeID ID; 2793 ID.AddInteger(scAddExpr); 2794 for (const SCEV *Op : Ops) 2795 ID.AddPointer(Op); 2796 void *IP = nullptr; 2797 SCEVAddExpr *S = 2798 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2799 if (!S) { 2800 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2801 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2802 S = new (SCEVAllocator) 2803 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2804 UniqueSCEVs.InsertNode(S, IP); 2805 addToLoopUseLists(S); 2806 } 2807 S->setNoWrapFlags(Flags); 2808 return S; 2809 } 2810 2811 const SCEV * 2812 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2813 const Loop *L, SCEV::NoWrapFlags Flags) { 2814 FoldingSetNodeID ID; 2815 ID.AddInteger(scAddRecExpr); 2816 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2817 ID.AddPointer(Ops[i]); 2818 ID.AddPointer(L); 2819 void *IP = nullptr; 2820 SCEVAddRecExpr *S = 2821 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2822 if (!S) { 2823 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2824 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2825 S = new (SCEVAllocator) 2826 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2827 UniqueSCEVs.InsertNode(S, IP); 2828 addToLoopUseLists(S); 2829 } 2830 setNoWrapFlags(S, Flags); 2831 return S; 2832 } 2833 2834 const SCEV * 2835 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2836 SCEV::NoWrapFlags Flags) { 2837 FoldingSetNodeID ID; 2838 ID.AddInteger(scMulExpr); 2839 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2840 ID.AddPointer(Ops[i]); 2841 void *IP = nullptr; 2842 SCEVMulExpr *S = 2843 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2844 if (!S) { 2845 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2846 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2847 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2848 O, Ops.size()); 2849 UniqueSCEVs.InsertNode(S, IP); 2850 addToLoopUseLists(S); 2851 } 2852 S->setNoWrapFlags(Flags); 2853 return S; 2854 } 2855 2856 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2857 uint64_t k = i*j; 2858 if (j > 1 && k / j != i) Overflow = true; 2859 return k; 2860 } 2861 2862 /// Compute the result of "n choose k", the binomial coefficient. If an 2863 /// intermediate computation overflows, Overflow will be set and the return will 2864 /// be garbage. Overflow is not cleared on absence of overflow. 2865 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2866 // We use the multiplicative formula: 2867 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2868 // At each iteration, we take the n-th term of the numeral and divide by the 2869 // (k-n)th term of the denominator. This division will always produce an 2870 // integral result, and helps reduce the chance of overflow in the 2871 // intermediate computations. However, we can still overflow even when the 2872 // final result would fit. 2873 2874 if (n == 0 || n == k) return 1; 2875 if (k > n) return 0; 2876 2877 if (k > n/2) 2878 k = n-k; 2879 2880 uint64_t r = 1; 2881 for (uint64_t i = 1; i <= k; ++i) { 2882 r = umul_ov(r, n-(i-1), Overflow); 2883 r /= i; 2884 } 2885 return r; 2886 } 2887 2888 /// Determine if any of the operands in this SCEV are a constant or if 2889 /// any of the add or multiply expressions in this SCEV contain a constant. 2890 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2891 struct FindConstantInAddMulChain { 2892 bool FoundConstant = false; 2893 2894 bool follow(const SCEV *S) { 2895 FoundConstant |= isa<SCEVConstant>(S); 2896 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2897 } 2898 2899 bool isDone() const { 2900 return FoundConstant; 2901 } 2902 }; 2903 2904 FindConstantInAddMulChain F; 2905 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2906 ST.visitAll(StartExpr); 2907 return F.FoundConstant; 2908 } 2909 2910 /// Get a canonical multiply expression, or something simpler if possible. 2911 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2912 SCEV::NoWrapFlags OrigFlags, 2913 unsigned Depth) { 2914 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 2915 "only nuw or nsw allowed"); 2916 assert(!Ops.empty() && "Cannot get empty mul!"); 2917 if (Ops.size() == 1) return Ops[0]; 2918 #ifndef NDEBUG 2919 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2920 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2921 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2922 "SCEVMulExpr operand types don't match!"); 2923 #endif 2924 2925 // Sort by complexity, this groups all similar expression types together. 2926 GroupByComplexity(Ops, &LI, DT); 2927 2928 // If there are any constants, fold them together. 2929 unsigned Idx = 0; 2930 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2931 ++Idx; 2932 assert(Idx < Ops.size()); 2933 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2934 // We found two constants, fold them together! 2935 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 2936 if (Ops.size() == 2) return Ops[0]; 2937 Ops.erase(Ops.begin()+1); // Erase the folded element 2938 LHSC = cast<SCEVConstant>(Ops[0]); 2939 } 2940 2941 // If we have a multiply of zero, it will always be zero. 2942 if (LHSC->getValue()->isZero()) 2943 return LHSC; 2944 2945 // If we are left with a constant one being multiplied, strip it off. 2946 if (LHSC->getValue()->isOne()) { 2947 Ops.erase(Ops.begin()); 2948 --Idx; 2949 } 2950 2951 if (Ops.size() == 1) 2952 return Ops[0]; 2953 } 2954 2955 // Delay expensive flag strengthening until necessary. 2956 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2957 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 2958 }; 2959 2960 // Limit recursion calls depth. 2961 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2962 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 2963 2964 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2965 // Don't strengthen flags if we have no new information. 2966 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 2967 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 2968 Mul->setNoWrapFlags(ComputeFlags(Ops)); 2969 return S; 2970 } 2971 2972 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2973 if (Ops.size() == 2) { 2974 // C1*(C2+V) -> C1*C2 + C1*V 2975 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2976 // If any of Add's ops are Adds or Muls with a constant, apply this 2977 // transformation as well. 2978 // 2979 // TODO: There are some cases where this transformation is not 2980 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2981 // this transformation should be narrowed down. 2982 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2983 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2984 SCEV::FlagAnyWrap, Depth + 1), 2985 getMulExpr(LHSC, Add->getOperand(1), 2986 SCEV::FlagAnyWrap, Depth + 1), 2987 SCEV::FlagAnyWrap, Depth + 1); 2988 2989 if (Ops[0]->isAllOnesValue()) { 2990 // If we have a mul by -1 of an add, try distributing the -1 among the 2991 // add operands. 2992 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2993 SmallVector<const SCEV *, 4> NewOps; 2994 bool AnyFolded = false; 2995 for (const SCEV *AddOp : Add->operands()) { 2996 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2997 Depth + 1); 2998 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2999 NewOps.push_back(Mul); 3000 } 3001 if (AnyFolded) 3002 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3003 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3004 // Negation preserves a recurrence's no self-wrap property. 3005 SmallVector<const SCEV *, 4> Operands; 3006 for (const SCEV *AddRecOp : AddRec->operands()) 3007 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3008 Depth + 1)); 3009 3010 return getAddRecExpr(Operands, AddRec->getLoop(), 3011 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3012 } 3013 } 3014 } 3015 } 3016 3017 // Skip over the add expression until we get to a multiply. 3018 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3019 ++Idx; 3020 3021 // If there are mul operands inline them all into this expression. 3022 if (Idx < Ops.size()) { 3023 bool DeletedMul = false; 3024 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3025 if (Ops.size() > MulOpsInlineThreshold) 3026 break; 3027 // If we have an mul, expand the mul operands onto the end of the 3028 // operands list. 3029 Ops.erase(Ops.begin()+Idx); 3030 Ops.append(Mul->op_begin(), Mul->op_end()); 3031 DeletedMul = true; 3032 } 3033 3034 // If we deleted at least one mul, we added operands to the end of the 3035 // list, and they are not necessarily sorted. Recurse to resort and 3036 // resimplify any operands we just acquired. 3037 if (DeletedMul) 3038 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3039 } 3040 3041 // If there are any add recurrences in the operands list, see if any other 3042 // added values are loop invariant. If so, we can fold them into the 3043 // recurrence. 3044 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3045 ++Idx; 3046 3047 // Scan over all recurrences, trying to fold loop invariants into them. 3048 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3049 // Scan all of the other operands to this mul and add them to the vector 3050 // if they are loop invariant w.r.t. the recurrence. 3051 SmallVector<const SCEV *, 8> LIOps; 3052 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3053 const Loop *AddRecLoop = AddRec->getLoop(); 3054 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3055 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3056 LIOps.push_back(Ops[i]); 3057 Ops.erase(Ops.begin()+i); 3058 --i; --e; 3059 } 3060 3061 // If we found some loop invariants, fold them into the recurrence. 3062 if (!LIOps.empty()) { 3063 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3064 SmallVector<const SCEV *, 4> NewOps; 3065 NewOps.reserve(AddRec->getNumOperands()); 3066 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3067 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3068 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3069 SCEV::FlagAnyWrap, Depth + 1)); 3070 3071 // Build the new addrec. Propagate the NUW and NSW flags if both the 3072 // outer mul and the inner addrec are guaranteed to have no overflow. 3073 // 3074 // No self-wrap cannot be guaranteed after changing the step size, but 3075 // will be inferred if either NUW or NSW is true. 3076 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3077 const SCEV *NewRec = getAddRecExpr( 3078 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3079 3080 // If all of the other operands were loop invariant, we are done. 3081 if (Ops.size() == 1) return NewRec; 3082 3083 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3084 for (unsigned i = 0;; ++i) 3085 if (Ops[i] == AddRec) { 3086 Ops[i] = NewRec; 3087 break; 3088 } 3089 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3090 } 3091 3092 // Okay, if there weren't any loop invariants to be folded, check to see 3093 // if there are multiple AddRec's with the same loop induction variable 3094 // being multiplied together. If so, we can fold them. 3095 3096 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3097 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3098 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3099 // ]]],+,...up to x=2n}. 3100 // Note that the arguments to choose() are always integers with values 3101 // known at compile time, never SCEV objects. 3102 // 3103 // The implementation avoids pointless extra computations when the two 3104 // addrec's are of different length (mathematically, it's equivalent to 3105 // an infinite stream of zeros on the right). 3106 bool OpsModified = false; 3107 for (unsigned OtherIdx = Idx+1; 3108 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3109 ++OtherIdx) { 3110 const SCEVAddRecExpr *OtherAddRec = 3111 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3112 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3113 continue; 3114 3115 // Limit max number of arguments to avoid creation of unreasonably big 3116 // SCEVAddRecs with very complex operands. 3117 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3118 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3119 continue; 3120 3121 bool Overflow = false; 3122 Type *Ty = AddRec->getType(); 3123 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3124 SmallVector<const SCEV*, 7> AddRecOps; 3125 for (int x = 0, xe = AddRec->getNumOperands() + 3126 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3127 SmallVector <const SCEV *, 7> SumOps; 3128 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3129 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3130 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3131 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3132 z < ze && !Overflow; ++z) { 3133 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3134 uint64_t Coeff; 3135 if (LargerThan64Bits) 3136 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3137 else 3138 Coeff = Coeff1*Coeff2; 3139 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3140 const SCEV *Term1 = AddRec->getOperand(y-z); 3141 const SCEV *Term2 = OtherAddRec->getOperand(z); 3142 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3143 SCEV::FlagAnyWrap, Depth + 1)); 3144 } 3145 } 3146 if (SumOps.empty()) 3147 SumOps.push_back(getZero(Ty)); 3148 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3149 } 3150 if (!Overflow) { 3151 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3152 SCEV::FlagAnyWrap); 3153 if (Ops.size() == 2) return NewAddRec; 3154 Ops[Idx] = NewAddRec; 3155 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3156 OpsModified = true; 3157 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3158 if (!AddRec) 3159 break; 3160 } 3161 } 3162 if (OpsModified) 3163 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3164 3165 // Otherwise couldn't fold anything into this recurrence. Move onto the 3166 // next one. 3167 } 3168 3169 // Okay, it looks like we really DO need an mul expr. Check to see if we 3170 // already have one, otherwise create a new one. 3171 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3172 } 3173 3174 /// Represents an unsigned remainder expression based on unsigned division. 3175 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3176 const SCEV *RHS) { 3177 assert(getEffectiveSCEVType(LHS->getType()) == 3178 getEffectiveSCEVType(RHS->getType()) && 3179 "SCEVURemExpr operand types don't match!"); 3180 3181 // Short-circuit easy cases 3182 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3183 // If constant is one, the result is trivial 3184 if (RHSC->getValue()->isOne()) 3185 return getZero(LHS->getType()); // X urem 1 --> 0 3186 3187 // If constant is a power of two, fold into a zext(trunc(LHS)). 3188 if (RHSC->getAPInt().isPowerOf2()) { 3189 Type *FullTy = LHS->getType(); 3190 Type *TruncTy = 3191 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3192 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3193 } 3194 } 3195 3196 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3197 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3198 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3199 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3200 } 3201 3202 /// Get a canonical unsigned division expression, or something simpler if 3203 /// possible. 3204 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3205 const SCEV *RHS) { 3206 assert(getEffectiveSCEVType(LHS->getType()) == 3207 getEffectiveSCEVType(RHS->getType()) && 3208 "SCEVUDivExpr operand types don't match!"); 3209 3210 FoldingSetNodeID ID; 3211 ID.AddInteger(scUDivExpr); 3212 ID.AddPointer(LHS); 3213 ID.AddPointer(RHS); 3214 void *IP = nullptr; 3215 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3216 return S; 3217 3218 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3219 if (RHSC->getValue()->isOne()) 3220 return LHS; // X udiv 1 --> x 3221 // If the denominator is zero, the result of the udiv is undefined. Don't 3222 // try to analyze it, because the resolution chosen here may differ from 3223 // the resolution chosen in other parts of the compiler. 3224 if (!RHSC->getValue()->isZero()) { 3225 // Determine if the division can be folded into the operands of 3226 // its operands. 3227 // TODO: Generalize this to non-constants by using known-bits information. 3228 Type *Ty = LHS->getType(); 3229 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3230 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3231 // For non-power-of-two values, effectively round the value up to the 3232 // nearest power of two. 3233 if (!RHSC->getAPInt().isPowerOf2()) 3234 ++MaxShiftAmt; 3235 IntegerType *ExtTy = 3236 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3237 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3238 if (const SCEVConstant *Step = 3239 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3240 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3241 const APInt &StepInt = Step->getAPInt(); 3242 const APInt &DivInt = RHSC->getAPInt(); 3243 if (!StepInt.urem(DivInt) && 3244 getZeroExtendExpr(AR, ExtTy) == 3245 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3246 getZeroExtendExpr(Step, ExtTy), 3247 AR->getLoop(), SCEV::FlagAnyWrap)) { 3248 SmallVector<const SCEV *, 4> Operands; 3249 for (const SCEV *Op : AR->operands()) 3250 Operands.push_back(getUDivExpr(Op, RHS)); 3251 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3252 } 3253 /// Get a canonical UDivExpr for a recurrence. 3254 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3255 // We can currently only fold X%N if X is constant. 3256 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3257 if (StartC && !DivInt.urem(StepInt) && 3258 getZeroExtendExpr(AR, ExtTy) == 3259 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3260 getZeroExtendExpr(Step, ExtTy), 3261 AR->getLoop(), SCEV::FlagAnyWrap)) { 3262 const APInt &StartInt = StartC->getAPInt(); 3263 const APInt &StartRem = StartInt.urem(StepInt); 3264 if (StartRem != 0) { 3265 const SCEV *NewLHS = 3266 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3267 AR->getLoop(), SCEV::FlagNW); 3268 if (LHS != NewLHS) { 3269 LHS = NewLHS; 3270 3271 // Reset the ID to include the new LHS, and check if it is 3272 // already cached. 3273 ID.clear(); 3274 ID.AddInteger(scUDivExpr); 3275 ID.AddPointer(LHS); 3276 ID.AddPointer(RHS); 3277 IP = nullptr; 3278 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3279 return S; 3280 } 3281 } 3282 } 3283 } 3284 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3285 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3286 SmallVector<const SCEV *, 4> Operands; 3287 for (const SCEV *Op : M->operands()) 3288 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3289 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3290 // Find an operand that's safely divisible. 3291 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3292 const SCEV *Op = M->getOperand(i); 3293 const SCEV *Div = getUDivExpr(Op, RHSC); 3294 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3295 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3296 Operands[i] = Div; 3297 return getMulExpr(Operands); 3298 } 3299 } 3300 } 3301 3302 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3303 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3304 if (auto *DivisorConstant = 3305 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3306 bool Overflow = false; 3307 APInt NewRHS = 3308 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3309 if (Overflow) { 3310 return getConstant(RHSC->getType(), 0, false); 3311 } 3312 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3313 } 3314 } 3315 3316 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3317 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3318 SmallVector<const SCEV *, 4> Operands; 3319 for (const SCEV *Op : A->operands()) 3320 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3321 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3322 Operands.clear(); 3323 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3324 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3325 if (isa<SCEVUDivExpr>(Op) || 3326 getMulExpr(Op, RHS) != A->getOperand(i)) 3327 break; 3328 Operands.push_back(Op); 3329 } 3330 if (Operands.size() == A->getNumOperands()) 3331 return getAddExpr(Operands); 3332 } 3333 } 3334 3335 // Fold if both operands are constant. 3336 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3337 Constant *LHSCV = LHSC->getValue(); 3338 Constant *RHSCV = RHSC->getValue(); 3339 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3340 RHSCV))); 3341 } 3342 } 3343 } 3344 3345 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3346 // changes). Make sure we get a new one. 3347 IP = nullptr; 3348 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3349 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3350 LHS, RHS); 3351 UniqueSCEVs.InsertNode(S, IP); 3352 addToLoopUseLists(S); 3353 return S; 3354 } 3355 3356 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3357 APInt A = C1->getAPInt().abs(); 3358 APInt B = C2->getAPInt().abs(); 3359 uint32_t ABW = A.getBitWidth(); 3360 uint32_t BBW = B.getBitWidth(); 3361 3362 if (ABW > BBW) 3363 B = B.zext(ABW); 3364 else if (ABW < BBW) 3365 A = A.zext(BBW); 3366 3367 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3368 } 3369 3370 /// Get a canonical unsigned division expression, or something simpler if 3371 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3372 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3373 /// it's not exact because the udiv may be clearing bits. 3374 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3375 const SCEV *RHS) { 3376 // TODO: we could try to find factors in all sorts of things, but for now we 3377 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3378 // end of this file for inspiration. 3379 3380 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3381 if (!Mul || !Mul->hasNoUnsignedWrap()) 3382 return getUDivExpr(LHS, RHS); 3383 3384 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3385 // If the mulexpr multiplies by a constant, then that constant must be the 3386 // first element of the mulexpr. 3387 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3388 if (LHSCst == RHSCst) { 3389 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3390 return getMulExpr(Operands); 3391 } 3392 3393 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3394 // that there's a factor provided by one of the other terms. We need to 3395 // check. 3396 APInt Factor = gcd(LHSCst, RHSCst); 3397 if (!Factor.isIntN(1)) { 3398 LHSCst = 3399 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3400 RHSCst = 3401 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3402 SmallVector<const SCEV *, 2> Operands; 3403 Operands.push_back(LHSCst); 3404 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3405 LHS = getMulExpr(Operands); 3406 RHS = RHSCst; 3407 Mul = dyn_cast<SCEVMulExpr>(LHS); 3408 if (!Mul) 3409 return getUDivExactExpr(LHS, RHS); 3410 } 3411 } 3412 } 3413 3414 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3415 if (Mul->getOperand(i) == RHS) { 3416 SmallVector<const SCEV *, 2> Operands; 3417 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3418 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3419 return getMulExpr(Operands); 3420 } 3421 } 3422 3423 return getUDivExpr(LHS, RHS); 3424 } 3425 3426 /// Get an add recurrence expression for the specified loop. Simplify the 3427 /// expression as much as possible. 3428 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3429 const Loop *L, 3430 SCEV::NoWrapFlags Flags) { 3431 SmallVector<const SCEV *, 4> Operands; 3432 Operands.push_back(Start); 3433 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3434 if (StepChrec->getLoop() == L) { 3435 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3436 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3437 } 3438 3439 Operands.push_back(Step); 3440 return getAddRecExpr(Operands, L, Flags); 3441 } 3442 3443 /// Get an add recurrence expression for the specified loop. Simplify the 3444 /// expression as much as possible. 3445 const SCEV * 3446 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3447 const Loop *L, SCEV::NoWrapFlags Flags) { 3448 if (Operands.size() == 1) return Operands[0]; 3449 #ifndef NDEBUG 3450 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3451 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3452 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3453 "SCEVAddRecExpr operand types don't match!"); 3454 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3455 assert(isLoopInvariant(Operands[i], L) && 3456 "SCEVAddRecExpr operand is not loop-invariant!"); 3457 #endif 3458 3459 if (Operands.back()->isZero()) { 3460 Operands.pop_back(); 3461 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3462 } 3463 3464 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3465 // use that information to infer NUW and NSW flags. However, computing a 3466 // BE count requires calling getAddRecExpr, so we may not yet have a 3467 // meaningful BE count at this point (and if we don't, we'd be stuck 3468 // with a SCEVCouldNotCompute as the cached BE count). 3469 3470 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3471 3472 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3473 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3474 const Loop *NestedLoop = NestedAR->getLoop(); 3475 if (L->contains(NestedLoop) 3476 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3477 : (!NestedLoop->contains(L) && 3478 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3479 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3480 Operands[0] = NestedAR->getStart(); 3481 // AddRecs require their operands be loop-invariant with respect to their 3482 // loops. Don't perform this transformation if it would break this 3483 // requirement. 3484 bool AllInvariant = all_of( 3485 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3486 3487 if (AllInvariant) { 3488 // Create a recurrence for the outer loop with the same step size. 3489 // 3490 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3491 // inner recurrence has the same property. 3492 SCEV::NoWrapFlags OuterFlags = 3493 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3494 3495 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3496 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3497 return isLoopInvariant(Op, NestedLoop); 3498 }); 3499 3500 if (AllInvariant) { 3501 // Ok, both add recurrences are valid after the transformation. 3502 // 3503 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3504 // the outer recurrence has the same property. 3505 SCEV::NoWrapFlags InnerFlags = 3506 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3507 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3508 } 3509 } 3510 // Reset Operands to its original state. 3511 Operands[0] = NestedAR; 3512 } 3513 } 3514 3515 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3516 // already have one, otherwise create a new one. 3517 return getOrCreateAddRecExpr(Operands, L, Flags); 3518 } 3519 3520 const SCEV * 3521 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3522 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3523 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3524 // getSCEV(Base)->getType() has the same address space as Base->getType() 3525 // because SCEV::getType() preserves the address space. 3526 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3527 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3528 // instruction to its SCEV, because the Instruction may be guarded by control 3529 // flow and the no-overflow bits may not be valid for the expression in any 3530 // context. This can be fixed similarly to how these flags are handled for 3531 // adds. 3532 SCEV::NoWrapFlags OffsetWrap = 3533 GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3534 3535 Type *CurTy = GEP->getType(); 3536 bool FirstIter = true; 3537 SmallVector<const SCEV *, 4> Offsets; 3538 for (const SCEV *IndexExpr : IndexExprs) { 3539 // Compute the (potentially symbolic) offset in bytes for this index. 3540 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3541 // For a struct, add the member offset. 3542 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3543 unsigned FieldNo = Index->getZExtValue(); 3544 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3545 Offsets.push_back(FieldOffset); 3546 3547 // Update CurTy to the type of the field at Index. 3548 CurTy = STy->getTypeAtIndex(Index); 3549 } else { 3550 // Update CurTy to its element type. 3551 if (FirstIter) { 3552 assert(isa<PointerType>(CurTy) && 3553 "The first index of a GEP indexes a pointer"); 3554 CurTy = GEP->getSourceElementType(); 3555 FirstIter = false; 3556 } else { 3557 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3558 } 3559 // For an array, add the element offset, explicitly scaled. 3560 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3561 // Getelementptr indices are signed. 3562 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3563 3564 // Multiply the index by the element size to compute the element offset. 3565 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3566 Offsets.push_back(LocalOffset); 3567 } 3568 } 3569 3570 // Handle degenerate case of GEP without offsets. 3571 if (Offsets.empty()) 3572 return BaseExpr; 3573 3574 // Add the offsets together, assuming nsw if inbounds. 3575 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3576 // Add the base address and the offset. We cannot use the nsw flag, as the 3577 // base address is unsigned. However, if we know that the offset is 3578 // non-negative, we can use nuw. 3579 SCEV::NoWrapFlags BaseWrap = GEP->isInBounds() && isKnownNonNegative(Offset) 3580 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3581 return getAddExpr(BaseExpr, Offset, BaseWrap); 3582 } 3583 3584 std::tuple<SCEV *, FoldingSetNodeID, void *> 3585 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3586 ArrayRef<const SCEV *> Ops) { 3587 FoldingSetNodeID ID; 3588 void *IP = nullptr; 3589 ID.AddInteger(SCEVType); 3590 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3591 ID.AddPointer(Ops[i]); 3592 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3593 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3594 } 3595 3596 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3597 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3598 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3599 } 3600 3601 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3602 SmallVectorImpl<const SCEV *> &Ops) { 3603 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3604 if (Ops.size() == 1) return Ops[0]; 3605 #ifndef NDEBUG 3606 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3607 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3608 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3609 "Operand types don't match!"); 3610 #endif 3611 3612 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3613 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3614 3615 // Sort by complexity, this groups all similar expression types together. 3616 GroupByComplexity(Ops, &LI, DT); 3617 3618 // Check if we have created the same expression before. 3619 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3620 return S; 3621 } 3622 3623 // If there are any constants, fold them together. 3624 unsigned Idx = 0; 3625 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3626 ++Idx; 3627 assert(Idx < Ops.size()); 3628 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3629 if (Kind == scSMaxExpr) 3630 return APIntOps::smax(LHS, RHS); 3631 else if (Kind == scSMinExpr) 3632 return APIntOps::smin(LHS, RHS); 3633 else if (Kind == scUMaxExpr) 3634 return APIntOps::umax(LHS, RHS); 3635 else if (Kind == scUMinExpr) 3636 return APIntOps::umin(LHS, RHS); 3637 llvm_unreachable("Unknown SCEV min/max opcode"); 3638 }; 3639 3640 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3641 // We found two constants, fold them together! 3642 ConstantInt *Fold = ConstantInt::get( 3643 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3644 Ops[0] = getConstant(Fold); 3645 Ops.erase(Ops.begin()+1); // Erase the folded element 3646 if (Ops.size() == 1) return Ops[0]; 3647 LHSC = cast<SCEVConstant>(Ops[0]); 3648 } 3649 3650 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3651 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3652 3653 if (IsMax ? IsMinV : IsMaxV) { 3654 // If we are left with a constant minimum(/maximum)-int, strip it off. 3655 Ops.erase(Ops.begin()); 3656 --Idx; 3657 } else if (IsMax ? IsMaxV : IsMinV) { 3658 // If we have a max(/min) with a constant maximum(/minimum)-int, 3659 // it will always be the extremum. 3660 return LHSC; 3661 } 3662 3663 if (Ops.size() == 1) return Ops[0]; 3664 } 3665 3666 // Find the first operation of the same kind 3667 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3668 ++Idx; 3669 3670 // Check to see if one of the operands is of the same kind. If so, expand its 3671 // operands onto our operand list, and recurse to simplify. 3672 if (Idx < Ops.size()) { 3673 bool DeletedAny = false; 3674 while (Ops[Idx]->getSCEVType() == Kind) { 3675 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3676 Ops.erase(Ops.begin()+Idx); 3677 Ops.append(SMME->op_begin(), SMME->op_end()); 3678 DeletedAny = true; 3679 } 3680 3681 if (DeletedAny) 3682 return getMinMaxExpr(Kind, Ops); 3683 } 3684 3685 // Okay, check to see if the same value occurs in the operand list twice. If 3686 // so, delete one. Since we sorted the list, these values are required to 3687 // be adjacent. 3688 llvm::CmpInst::Predicate GEPred = 3689 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3690 llvm::CmpInst::Predicate LEPred = 3691 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3692 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3693 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3694 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3695 if (Ops[i] == Ops[i + 1] || 3696 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3697 // X op Y op Y --> X op Y 3698 // X op Y --> X, if we know X, Y are ordered appropriately 3699 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3700 --i; 3701 --e; 3702 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3703 Ops[i + 1])) { 3704 // X op Y --> Y, if we know X, Y are ordered appropriately 3705 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3706 --i; 3707 --e; 3708 } 3709 } 3710 3711 if (Ops.size() == 1) return Ops[0]; 3712 3713 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3714 3715 // Okay, it looks like we really DO need an expr. Check to see if we 3716 // already have one, otherwise create a new one. 3717 const SCEV *ExistingSCEV; 3718 FoldingSetNodeID ID; 3719 void *IP; 3720 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3721 if (ExistingSCEV) 3722 return ExistingSCEV; 3723 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3724 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3725 SCEV *S = new (SCEVAllocator) 3726 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3727 3728 UniqueSCEVs.InsertNode(S, IP); 3729 addToLoopUseLists(S); 3730 return S; 3731 } 3732 3733 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3734 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3735 return getSMaxExpr(Ops); 3736 } 3737 3738 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3739 return getMinMaxExpr(scSMaxExpr, Ops); 3740 } 3741 3742 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3743 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3744 return getUMaxExpr(Ops); 3745 } 3746 3747 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3748 return getMinMaxExpr(scUMaxExpr, Ops); 3749 } 3750 3751 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3752 const SCEV *RHS) { 3753 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3754 return getSMinExpr(Ops); 3755 } 3756 3757 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3758 return getMinMaxExpr(scSMinExpr, Ops); 3759 } 3760 3761 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3762 const SCEV *RHS) { 3763 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3764 return getUMinExpr(Ops); 3765 } 3766 3767 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3768 return getMinMaxExpr(scUMinExpr, Ops); 3769 } 3770 3771 const SCEV * 3772 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 3773 ScalableVectorType *ScalableTy) { 3774 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 3775 Constant *One = ConstantInt::get(IntTy, 1); 3776 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 3777 // Note that the expression we created is the final expression, we don't 3778 // want to simplify it any further Also, if we call a normal getSCEV(), 3779 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3780 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3781 } 3782 3783 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3784 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 3785 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 3786 // We can bypass creating a target-independent constant expression and then 3787 // folding it back into a ConstantInt. This is just a compile-time 3788 // optimization. 3789 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3790 } 3791 3792 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 3793 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 3794 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 3795 // We can bypass creating a target-independent constant expression and then 3796 // folding it back into a ConstantInt. This is just a compile-time 3797 // optimization. 3798 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 3799 } 3800 3801 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3802 StructType *STy, 3803 unsigned FieldNo) { 3804 // We can bypass creating a target-independent constant expression and then 3805 // folding it back into a ConstantInt. This is just a compile-time 3806 // optimization. 3807 return getConstant( 3808 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3809 } 3810 3811 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3812 // Don't attempt to do anything other than create a SCEVUnknown object 3813 // here. createSCEV only calls getUnknown after checking for all other 3814 // interesting possibilities, and any other code that calls getUnknown 3815 // is doing so in order to hide a value from SCEV canonicalization. 3816 3817 FoldingSetNodeID ID; 3818 ID.AddInteger(scUnknown); 3819 ID.AddPointer(V); 3820 void *IP = nullptr; 3821 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3822 assert(cast<SCEVUnknown>(S)->getValue() == V && 3823 "Stale SCEVUnknown in uniquing map!"); 3824 return S; 3825 } 3826 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3827 FirstUnknown); 3828 FirstUnknown = cast<SCEVUnknown>(S); 3829 UniqueSCEVs.InsertNode(S, IP); 3830 return S; 3831 } 3832 3833 //===----------------------------------------------------------------------===// 3834 // Basic SCEV Analysis and PHI Idiom Recognition Code 3835 // 3836 3837 /// Test if values of the given type are analyzable within the SCEV 3838 /// framework. This primarily includes integer types, and it can optionally 3839 /// include pointer types if the ScalarEvolution class has access to 3840 /// target-specific information. 3841 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3842 // Integers and pointers are always SCEVable. 3843 return Ty->isIntOrPtrTy(); 3844 } 3845 3846 /// Return the size in bits of the specified type, for which isSCEVable must 3847 /// return true. 3848 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3849 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3850 if (Ty->isPointerTy()) 3851 return getDataLayout().getIndexTypeSizeInBits(Ty); 3852 return getDataLayout().getTypeSizeInBits(Ty); 3853 } 3854 3855 /// Return a type with the same bitwidth as the given type and which represents 3856 /// how SCEV will treat the given type, for which isSCEVable must return 3857 /// true. For pointer types, this is the pointer index sized integer type. 3858 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3859 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3860 3861 if (Ty->isIntegerTy()) 3862 return Ty; 3863 3864 // The only other support type is pointer. 3865 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3866 return getDataLayout().getIndexType(Ty); 3867 } 3868 3869 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3870 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3871 } 3872 3873 const SCEV *ScalarEvolution::getCouldNotCompute() { 3874 return CouldNotCompute.get(); 3875 } 3876 3877 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3878 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3879 auto *SU = dyn_cast<SCEVUnknown>(S); 3880 return SU && SU->getValue() == nullptr; 3881 }); 3882 3883 return !ContainsNulls; 3884 } 3885 3886 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3887 HasRecMapType::iterator I = HasRecMap.find(S); 3888 if (I != HasRecMap.end()) 3889 return I->second; 3890 3891 bool FoundAddRec = 3892 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3893 HasRecMap.insert({S, FoundAddRec}); 3894 return FoundAddRec; 3895 } 3896 3897 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3898 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3899 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3900 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3901 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3902 if (!Add) 3903 return {S, nullptr}; 3904 3905 if (Add->getNumOperands() != 2) 3906 return {S, nullptr}; 3907 3908 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3909 if (!ConstOp) 3910 return {S, nullptr}; 3911 3912 return {Add->getOperand(1), ConstOp->getValue()}; 3913 } 3914 3915 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3916 /// by the value and offset from any ValueOffsetPair in the set. 3917 ScalarEvolution::ValueOffsetPairSetVector * 3918 ScalarEvolution::getSCEVValues(const SCEV *S) { 3919 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3920 if (SI == ExprValueMap.end()) 3921 return nullptr; 3922 #ifndef NDEBUG 3923 if (VerifySCEVMap) { 3924 // Check there is no dangling Value in the set returned. 3925 for (const auto &VE : SI->second) 3926 assert(ValueExprMap.count(VE.first)); 3927 } 3928 #endif 3929 return &SI->second; 3930 } 3931 3932 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3933 /// cannot be used separately. eraseValueFromMap should be used to remove 3934 /// V from ValueExprMap and ExprValueMap at the same time. 3935 void ScalarEvolution::eraseValueFromMap(Value *V) { 3936 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3937 if (I != ValueExprMap.end()) { 3938 const SCEV *S = I->second; 3939 // Remove {V, 0} from the set of ExprValueMap[S] 3940 if (auto *SV = getSCEVValues(S)) 3941 SV->remove({V, nullptr}); 3942 3943 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3944 const SCEV *Stripped; 3945 ConstantInt *Offset; 3946 std::tie(Stripped, Offset) = splitAddExpr(S); 3947 if (Offset != nullptr) { 3948 if (auto *SV = getSCEVValues(Stripped)) 3949 SV->remove({V, Offset}); 3950 } 3951 ValueExprMap.erase(V); 3952 } 3953 } 3954 3955 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3956 /// TODO: In reality it is better to check the poison recursively 3957 /// but this is better than nothing. 3958 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3959 if (auto *I = dyn_cast<Instruction>(V)) { 3960 if (isa<OverflowingBinaryOperator>(I)) { 3961 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3962 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3963 return true; 3964 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3965 return true; 3966 } 3967 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3968 return true; 3969 } 3970 return false; 3971 } 3972 3973 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3974 /// create a new one. 3975 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3976 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3977 3978 const SCEV *S = getExistingSCEV(V); 3979 if (S == nullptr) { 3980 S = createSCEV(V); 3981 // During PHI resolution, it is possible to create two SCEVs for the same 3982 // V, so it is needed to double check whether V->S is inserted into 3983 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3984 std::pair<ValueExprMapType::iterator, bool> Pair = 3985 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3986 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3987 ExprValueMap[S].insert({V, nullptr}); 3988 3989 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3990 // ExprValueMap. 3991 const SCEV *Stripped = S; 3992 ConstantInt *Offset = nullptr; 3993 std::tie(Stripped, Offset) = splitAddExpr(S); 3994 // If stripped is SCEVUnknown, don't bother to save 3995 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3996 // increase the complexity of the expansion code. 3997 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3998 // because it may generate add/sub instead of GEP in SCEV expansion. 3999 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4000 !isa<GetElementPtrInst>(V)) 4001 ExprValueMap[Stripped].insert({V, Offset}); 4002 } 4003 } 4004 return S; 4005 } 4006 4007 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4008 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4009 4010 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4011 if (I != ValueExprMap.end()) { 4012 const SCEV *S = I->second; 4013 if (checkValidity(S)) 4014 return S; 4015 eraseValueFromMap(V); 4016 forgetMemoizedResults(S); 4017 } 4018 return nullptr; 4019 } 4020 4021 /// Return a SCEV corresponding to -V = -1*V 4022 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4023 SCEV::NoWrapFlags Flags) { 4024 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4025 return getConstant( 4026 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4027 4028 Type *Ty = V->getType(); 4029 Ty = getEffectiveSCEVType(Ty); 4030 return getMulExpr(V, getMinusOne(Ty), Flags); 4031 } 4032 4033 /// If Expr computes ~A, return A else return nullptr 4034 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4035 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4036 if (!Add || Add->getNumOperands() != 2 || 4037 !Add->getOperand(0)->isAllOnesValue()) 4038 return nullptr; 4039 4040 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4041 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4042 !AddRHS->getOperand(0)->isAllOnesValue()) 4043 return nullptr; 4044 4045 return AddRHS->getOperand(1); 4046 } 4047 4048 /// Return a SCEV corresponding to ~V = -1-V 4049 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4050 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4051 return getConstant( 4052 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4053 4054 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4055 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4056 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4057 SmallVector<const SCEV *, 2> MatchedOperands; 4058 for (const SCEV *Operand : MME->operands()) { 4059 const SCEV *Matched = MatchNotExpr(Operand); 4060 if (!Matched) 4061 return (const SCEV *)nullptr; 4062 MatchedOperands.push_back(Matched); 4063 } 4064 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4065 MatchedOperands); 4066 }; 4067 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4068 return Replaced; 4069 } 4070 4071 Type *Ty = V->getType(); 4072 Ty = getEffectiveSCEVType(Ty); 4073 return getMinusSCEV(getMinusOne(Ty), V); 4074 } 4075 4076 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4077 SCEV::NoWrapFlags Flags, 4078 unsigned Depth) { 4079 // Fast path: X - X --> 0. 4080 if (LHS == RHS) 4081 return getZero(LHS->getType()); 4082 4083 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4084 // makes it so that we cannot make much use of NUW. 4085 auto AddFlags = SCEV::FlagAnyWrap; 4086 const bool RHSIsNotMinSigned = 4087 !getSignedRangeMin(RHS).isMinSignedValue(); 4088 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4089 // Let M be the minimum representable signed value. Then (-1)*RHS 4090 // signed-wraps if and only if RHS is M. That can happen even for 4091 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4092 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4093 // (-1)*RHS, we need to prove that RHS != M. 4094 // 4095 // If LHS is non-negative and we know that LHS - RHS does not 4096 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4097 // either by proving that RHS > M or that LHS >= 0. 4098 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4099 AddFlags = SCEV::FlagNSW; 4100 } 4101 } 4102 4103 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4104 // RHS is NSW and LHS >= 0. 4105 // 4106 // The difficulty here is that the NSW flag may have been proven 4107 // relative to a loop that is to be found in a recurrence in LHS and 4108 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4109 // larger scope than intended. 4110 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4111 4112 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4113 } 4114 4115 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4116 unsigned Depth) { 4117 Type *SrcTy = V->getType(); 4118 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4119 "Cannot truncate or zero extend with non-integer arguments!"); 4120 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4121 return V; // No conversion 4122 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4123 return getTruncateExpr(V, Ty, Depth); 4124 return getZeroExtendExpr(V, Ty, Depth); 4125 } 4126 4127 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4128 unsigned Depth) { 4129 Type *SrcTy = V->getType(); 4130 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4131 "Cannot truncate or zero extend with non-integer arguments!"); 4132 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4133 return V; // No conversion 4134 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4135 return getTruncateExpr(V, Ty, Depth); 4136 return getSignExtendExpr(V, Ty, Depth); 4137 } 4138 4139 const SCEV * 4140 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4141 Type *SrcTy = V->getType(); 4142 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4143 "Cannot noop or zero extend with non-integer arguments!"); 4144 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4145 "getNoopOrZeroExtend cannot truncate!"); 4146 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4147 return V; // No conversion 4148 return getZeroExtendExpr(V, Ty); 4149 } 4150 4151 const SCEV * 4152 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4153 Type *SrcTy = V->getType(); 4154 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4155 "Cannot noop or sign extend with non-integer arguments!"); 4156 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4157 "getNoopOrSignExtend cannot truncate!"); 4158 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4159 return V; // No conversion 4160 return getSignExtendExpr(V, Ty); 4161 } 4162 4163 const SCEV * 4164 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4165 Type *SrcTy = V->getType(); 4166 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4167 "Cannot noop or any extend with non-integer arguments!"); 4168 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4169 "getNoopOrAnyExtend cannot truncate!"); 4170 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4171 return V; // No conversion 4172 return getAnyExtendExpr(V, Ty); 4173 } 4174 4175 const SCEV * 4176 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4177 Type *SrcTy = V->getType(); 4178 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4179 "Cannot truncate or noop with non-integer arguments!"); 4180 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4181 "getTruncateOrNoop cannot extend!"); 4182 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4183 return V; // No conversion 4184 return getTruncateExpr(V, Ty); 4185 } 4186 4187 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4188 const SCEV *RHS) { 4189 const SCEV *PromotedLHS = LHS; 4190 const SCEV *PromotedRHS = RHS; 4191 4192 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4193 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4194 else 4195 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4196 4197 return getUMaxExpr(PromotedLHS, PromotedRHS); 4198 } 4199 4200 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4201 const SCEV *RHS) { 4202 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4203 return getUMinFromMismatchedTypes(Ops); 4204 } 4205 4206 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4207 SmallVectorImpl<const SCEV *> &Ops) { 4208 assert(!Ops.empty() && "At least one operand must be!"); 4209 // Trivial case. 4210 if (Ops.size() == 1) 4211 return Ops[0]; 4212 4213 // Find the max type first. 4214 Type *MaxType = nullptr; 4215 for (auto *S : Ops) 4216 if (MaxType) 4217 MaxType = getWiderType(MaxType, S->getType()); 4218 else 4219 MaxType = S->getType(); 4220 assert(MaxType && "Failed to find maximum type!"); 4221 4222 // Extend all ops to max type. 4223 SmallVector<const SCEV *, 2> PromotedOps; 4224 for (auto *S : Ops) 4225 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4226 4227 // Generate umin. 4228 return getUMinExpr(PromotedOps); 4229 } 4230 4231 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4232 // A pointer operand may evaluate to a nonpointer expression, such as null. 4233 if (!V->getType()->isPointerTy()) 4234 return V; 4235 4236 while (true) { 4237 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 4238 V = Cast->getOperand(); 4239 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4240 const SCEV *PtrOp = nullptr; 4241 for (const SCEV *NAryOp : NAry->operands()) { 4242 if (NAryOp->getType()->isPointerTy()) { 4243 // Cannot find the base of an expression with multiple pointer ops. 4244 if (PtrOp) 4245 return V; 4246 PtrOp = NAryOp; 4247 } 4248 } 4249 if (!PtrOp) // All operands were non-pointer. 4250 return V; 4251 V = PtrOp; 4252 } else // Not something we can look further into. 4253 return V; 4254 } 4255 } 4256 4257 /// Push users of the given Instruction onto the given Worklist. 4258 static void 4259 PushDefUseChildren(Instruction *I, 4260 SmallVectorImpl<Instruction *> &Worklist) { 4261 // Push the def-use children onto the Worklist stack. 4262 for (User *U : I->users()) 4263 Worklist.push_back(cast<Instruction>(U)); 4264 } 4265 4266 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4267 SmallVector<Instruction *, 16> Worklist; 4268 PushDefUseChildren(PN, Worklist); 4269 4270 SmallPtrSet<Instruction *, 8> Visited; 4271 Visited.insert(PN); 4272 while (!Worklist.empty()) { 4273 Instruction *I = Worklist.pop_back_val(); 4274 if (!Visited.insert(I).second) 4275 continue; 4276 4277 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4278 if (It != ValueExprMap.end()) { 4279 const SCEV *Old = It->second; 4280 4281 // Short-circuit the def-use traversal if the symbolic name 4282 // ceases to appear in expressions. 4283 if (Old != SymName && !hasOperand(Old, SymName)) 4284 continue; 4285 4286 // SCEVUnknown for a PHI either means that it has an unrecognized 4287 // structure, it's a PHI that's in the progress of being computed 4288 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4289 // additional loop trip count information isn't going to change anything. 4290 // In the second case, createNodeForPHI will perform the necessary 4291 // updates on its own when it gets to that point. In the third, we do 4292 // want to forget the SCEVUnknown. 4293 if (!isa<PHINode>(I) || 4294 !isa<SCEVUnknown>(Old) || 4295 (I != PN && Old == SymName)) { 4296 eraseValueFromMap(It->first); 4297 forgetMemoizedResults(Old); 4298 } 4299 } 4300 4301 PushDefUseChildren(I, Worklist); 4302 } 4303 } 4304 4305 namespace { 4306 4307 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4308 /// expression in case its Loop is L. If it is not L then 4309 /// if IgnoreOtherLoops is true then use AddRec itself 4310 /// otherwise rewrite cannot be done. 4311 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4312 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4313 public: 4314 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4315 bool IgnoreOtherLoops = true) { 4316 SCEVInitRewriter Rewriter(L, SE); 4317 const SCEV *Result = Rewriter.visit(S); 4318 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4319 return SE.getCouldNotCompute(); 4320 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4321 ? SE.getCouldNotCompute() 4322 : Result; 4323 } 4324 4325 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4326 if (!SE.isLoopInvariant(Expr, L)) 4327 SeenLoopVariantSCEVUnknown = true; 4328 return Expr; 4329 } 4330 4331 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4332 // Only re-write AddRecExprs for this loop. 4333 if (Expr->getLoop() == L) 4334 return Expr->getStart(); 4335 SeenOtherLoops = true; 4336 return Expr; 4337 } 4338 4339 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4340 4341 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4342 4343 private: 4344 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4345 : SCEVRewriteVisitor(SE), L(L) {} 4346 4347 const Loop *L; 4348 bool SeenLoopVariantSCEVUnknown = false; 4349 bool SeenOtherLoops = false; 4350 }; 4351 4352 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4353 /// increment expression in case its Loop is L. If it is not L then 4354 /// use AddRec itself. 4355 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4356 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4357 public: 4358 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4359 SCEVPostIncRewriter Rewriter(L, SE); 4360 const SCEV *Result = Rewriter.visit(S); 4361 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4362 ? SE.getCouldNotCompute() 4363 : Result; 4364 } 4365 4366 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4367 if (!SE.isLoopInvariant(Expr, L)) 4368 SeenLoopVariantSCEVUnknown = true; 4369 return Expr; 4370 } 4371 4372 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4373 // Only re-write AddRecExprs for this loop. 4374 if (Expr->getLoop() == L) 4375 return Expr->getPostIncExpr(SE); 4376 SeenOtherLoops = true; 4377 return Expr; 4378 } 4379 4380 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4381 4382 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4383 4384 private: 4385 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4386 : SCEVRewriteVisitor(SE), L(L) {} 4387 4388 const Loop *L; 4389 bool SeenLoopVariantSCEVUnknown = false; 4390 bool SeenOtherLoops = false; 4391 }; 4392 4393 /// This class evaluates the compare condition by matching it against the 4394 /// condition of loop latch. If there is a match we assume a true value 4395 /// for the condition while building SCEV nodes. 4396 class SCEVBackedgeConditionFolder 4397 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4398 public: 4399 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4400 ScalarEvolution &SE) { 4401 bool IsPosBECond = false; 4402 Value *BECond = nullptr; 4403 if (BasicBlock *Latch = L->getLoopLatch()) { 4404 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4405 if (BI && BI->isConditional()) { 4406 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4407 "Both outgoing branches should not target same header!"); 4408 BECond = BI->getCondition(); 4409 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4410 } else { 4411 return S; 4412 } 4413 } 4414 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4415 return Rewriter.visit(S); 4416 } 4417 4418 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4419 const SCEV *Result = Expr; 4420 bool InvariantF = SE.isLoopInvariant(Expr, L); 4421 4422 if (!InvariantF) { 4423 Instruction *I = cast<Instruction>(Expr->getValue()); 4424 switch (I->getOpcode()) { 4425 case Instruction::Select: { 4426 SelectInst *SI = cast<SelectInst>(I); 4427 Optional<const SCEV *> Res = 4428 compareWithBackedgeCondition(SI->getCondition()); 4429 if (Res.hasValue()) { 4430 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4431 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4432 } 4433 break; 4434 } 4435 default: { 4436 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4437 if (Res.hasValue()) 4438 Result = Res.getValue(); 4439 break; 4440 } 4441 } 4442 } 4443 return Result; 4444 } 4445 4446 private: 4447 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4448 bool IsPosBECond, ScalarEvolution &SE) 4449 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4450 IsPositiveBECond(IsPosBECond) {} 4451 4452 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4453 4454 const Loop *L; 4455 /// Loop back condition. 4456 Value *BackedgeCond = nullptr; 4457 /// Set to true if loop back is on positive branch condition. 4458 bool IsPositiveBECond; 4459 }; 4460 4461 Optional<const SCEV *> 4462 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4463 4464 // If value matches the backedge condition for loop latch, 4465 // then return a constant evolution node based on loopback 4466 // branch taken. 4467 if (BackedgeCond == IC) 4468 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4469 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4470 return None; 4471 } 4472 4473 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4474 public: 4475 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4476 ScalarEvolution &SE) { 4477 SCEVShiftRewriter Rewriter(L, SE); 4478 const SCEV *Result = Rewriter.visit(S); 4479 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4480 } 4481 4482 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4483 // Only allow AddRecExprs for this loop. 4484 if (!SE.isLoopInvariant(Expr, L)) 4485 Valid = false; 4486 return Expr; 4487 } 4488 4489 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4490 if (Expr->getLoop() == L && Expr->isAffine()) 4491 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4492 Valid = false; 4493 return Expr; 4494 } 4495 4496 bool isValid() { return Valid; } 4497 4498 private: 4499 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4500 : SCEVRewriteVisitor(SE), L(L) {} 4501 4502 const Loop *L; 4503 bool Valid = true; 4504 }; 4505 4506 } // end anonymous namespace 4507 4508 SCEV::NoWrapFlags 4509 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4510 if (!AR->isAffine()) 4511 return SCEV::FlagAnyWrap; 4512 4513 using OBO = OverflowingBinaryOperator; 4514 4515 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4516 4517 if (!AR->hasNoSignedWrap()) { 4518 ConstantRange AddRecRange = getSignedRange(AR); 4519 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4520 4521 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4522 Instruction::Add, IncRange, OBO::NoSignedWrap); 4523 if (NSWRegion.contains(AddRecRange)) 4524 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4525 } 4526 4527 if (!AR->hasNoUnsignedWrap()) { 4528 ConstantRange AddRecRange = getUnsignedRange(AR); 4529 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4530 4531 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4532 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4533 if (NUWRegion.contains(AddRecRange)) 4534 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4535 } 4536 4537 return Result; 4538 } 4539 4540 SCEV::NoWrapFlags 4541 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4542 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4543 4544 if (AR->hasNoSignedWrap()) 4545 return Result; 4546 4547 if (!AR->isAffine()) 4548 return Result; 4549 4550 const SCEV *Step = AR->getStepRecurrence(*this); 4551 const Loop *L = AR->getLoop(); 4552 4553 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4554 // Note that this serves two purposes: It filters out loops that are 4555 // simply not analyzable, and it covers the case where this code is 4556 // being called from within backedge-taken count analysis, such that 4557 // attempting to ask for the backedge-taken count would likely result 4558 // in infinite recursion. In the later case, the analysis code will 4559 // cope with a conservative value, and it will take care to purge 4560 // that value once it has finished. 4561 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4562 4563 // Normally, in the cases we can prove no-overflow via a 4564 // backedge guarding condition, we can also compute a backedge 4565 // taken count for the loop. The exceptions are assumptions and 4566 // guards present in the loop -- SCEV is not great at exploiting 4567 // these to compute max backedge taken counts, but can still use 4568 // these to prove lack of overflow. Use this fact to avoid 4569 // doing extra work that may not pay off. 4570 4571 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4572 AC.assumptions().empty()) 4573 return Result; 4574 4575 // If the backedge is guarded by a comparison with the pre-inc value the 4576 // addrec is safe. Also, if the entry is guarded by a comparison with the 4577 // start value and the backedge is guarded by a comparison with the post-inc 4578 // value, the addrec is safe. 4579 ICmpInst::Predicate Pred; 4580 const SCEV *OverflowLimit = 4581 getSignedOverflowLimitForStep(Step, &Pred, this); 4582 if (OverflowLimit && 4583 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4584 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4585 Result = setFlags(Result, SCEV::FlagNSW); 4586 } 4587 return Result; 4588 } 4589 SCEV::NoWrapFlags 4590 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4591 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4592 4593 if (AR->hasNoUnsignedWrap()) 4594 return Result; 4595 4596 if (!AR->isAffine()) 4597 return Result; 4598 4599 const SCEV *Step = AR->getStepRecurrence(*this); 4600 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4601 const Loop *L = AR->getLoop(); 4602 4603 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4604 // Note that this serves two purposes: It filters out loops that are 4605 // simply not analyzable, and it covers the case where this code is 4606 // being called from within backedge-taken count analysis, such that 4607 // attempting to ask for the backedge-taken count would likely result 4608 // in infinite recursion. In the later case, the analysis code will 4609 // cope with a conservative value, and it will take care to purge 4610 // that value once it has finished. 4611 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4612 4613 // Normally, in the cases we can prove no-overflow via a 4614 // backedge guarding condition, we can also compute a backedge 4615 // taken count for the loop. The exceptions are assumptions and 4616 // guards present in the loop -- SCEV is not great at exploiting 4617 // these to compute max backedge taken counts, but can still use 4618 // these to prove lack of overflow. Use this fact to avoid 4619 // doing extra work that may not pay off. 4620 4621 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4622 AC.assumptions().empty()) 4623 return Result; 4624 4625 // If the backedge is guarded by a comparison with the pre-inc value the 4626 // addrec is safe. Also, if the entry is guarded by a comparison with the 4627 // start value and the backedge is guarded by a comparison with the post-inc 4628 // value, the addrec is safe. 4629 if (isKnownPositive(Step)) { 4630 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 4631 getUnsignedRangeMax(Step)); 4632 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 4633 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 4634 Result = setFlags(Result, SCEV::FlagNUW); 4635 } 4636 } 4637 4638 return Result; 4639 } 4640 4641 namespace { 4642 4643 /// Represents an abstract binary operation. This may exist as a 4644 /// normal instruction or constant expression, or may have been 4645 /// derived from an expression tree. 4646 struct BinaryOp { 4647 unsigned Opcode; 4648 Value *LHS; 4649 Value *RHS; 4650 bool IsNSW = false; 4651 bool IsNUW = false; 4652 4653 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4654 /// constant expression. 4655 Operator *Op = nullptr; 4656 4657 explicit BinaryOp(Operator *Op) 4658 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4659 Op(Op) { 4660 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4661 IsNSW = OBO->hasNoSignedWrap(); 4662 IsNUW = OBO->hasNoUnsignedWrap(); 4663 } 4664 } 4665 4666 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4667 bool IsNUW = false) 4668 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4669 }; 4670 4671 } // end anonymous namespace 4672 4673 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4674 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4675 auto *Op = dyn_cast<Operator>(V); 4676 if (!Op) 4677 return None; 4678 4679 // Implementation detail: all the cleverness here should happen without 4680 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4681 // SCEV expressions when possible, and we should not break that. 4682 4683 switch (Op->getOpcode()) { 4684 case Instruction::Add: 4685 case Instruction::Sub: 4686 case Instruction::Mul: 4687 case Instruction::UDiv: 4688 case Instruction::URem: 4689 case Instruction::And: 4690 case Instruction::Or: 4691 case Instruction::AShr: 4692 case Instruction::Shl: 4693 return BinaryOp(Op); 4694 4695 case Instruction::Xor: 4696 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4697 // If the RHS of the xor is a signmask, then this is just an add. 4698 // Instcombine turns add of signmask into xor as a strength reduction step. 4699 if (RHSC->getValue().isSignMask()) 4700 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4701 return BinaryOp(Op); 4702 4703 case Instruction::LShr: 4704 // Turn logical shift right of a constant into a unsigned divide. 4705 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4706 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4707 4708 // If the shift count is not less than the bitwidth, the result of 4709 // the shift is undefined. Don't try to analyze it, because the 4710 // resolution chosen here may differ from the resolution chosen in 4711 // other parts of the compiler. 4712 if (SA->getValue().ult(BitWidth)) { 4713 Constant *X = 4714 ConstantInt::get(SA->getContext(), 4715 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4716 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4717 } 4718 } 4719 return BinaryOp(Op); 4720 4721 case Instruction::ExtractValue: { 4722 auto *EVI = cast<ExtractValueInst>(Op); 4723 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4724 break; 4725 4726 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4727 if (!WO) 4728 break; 4729 4730 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4731 bool Signed = WO->isSigned(); 4732 // TODO: Should add nuw/nsw flags for mul as well. 4733 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4734 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4735 4736 // Now that we know that all uses of the arithmetic-result component of 4737 // CI are guarded by the overflow check, we can go ahead and pretend 4738 // that the arithmetic is non-overflowing. 4739 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4740 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4741 } 4742 4743 default: 4744 break; 4745 } 4746 4747 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4748 // semantics as a Sub, return a binary sub expression. 4749 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4750 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4751 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4752 4753 return None; 4754 } 4755 4756 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4757 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4758 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4759 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4760 /// follows one of the following patterns: 4761 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4762 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4763 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4764 /// we return the type of the truncation operation, and indicate whether the 4765 /// truncated type should be treated as signed/unsigned by setting 4766 /// \p Signed to true/false, respectively. 4767 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4768 bool &Signed, ScalarEvolution &SE) { 4769 // The case where Op == SymbolicPHI (that is, with no type conversions on 4770 // the way) is handled by the regular add recurrence creating logic and 4771 // would have already been triggered in createAddRecForPHI. Reaching it here 4772 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4773 // because one of the other operands of the SCEVAddExpr updating this PHI is 4774 // not invariant). 4775 // 4776 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4777 // this case predicates that allow us to prove that Op == SymbolicPHI will 4778 // be added. 4779 if (Op == SymbolicPHI) 4780 return nullptr; 4781 4782 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4783 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4784 if (SourceBits != NewBits) 4785 return nullptr; 4786 4787 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4788 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4789 if (!SExt && !ZExt) 4790 return nullptr; 4791 const SCEVTruncateExpr *Trunc = 4792 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4793 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4794 if (!Trunc) 4795 return nullptr; 4796 const SCEV *X = Trunc->getOperand(); 4797 if (X != SymbolicPHI) 4798 return nullptr; 4799 Signed = SExt != nullptr; 4800 return Trunc->getType(); 4801 } 4802 4803 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4804 if (!PN->getType()->isIntegerTy()) 4805 return nullptr; 4806 const Loop *L = LI.getLoopFor(PN->getParent()); 4807 if (!L || L->getHeader() != PN->getParent()) 4808 return nullptr; 4809 return L; 4810 } 4811 4812 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4813 // computation that updates the phi follows the following pattern: 4814 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4815 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4816 // If so, try to see if it can be rewritten as an AddRecExpr under some 4817 // Predicates. If successful, return them as a pair. Also cache the results 4818 // of the analysis. 4819 // 4820 // Example usage scenario: 4821 // Say the Rewriter is called for the following SCEV: 4822 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4823 // where: 4824 // %X = phi i64 (%Start, %BEValue) 4825 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4826 // and call this function with %SymbolicPHI = %X. 4827 // 4828 // The analysis will find that the value coming around the backedge has 4829 // the following SCEV: 4830 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4831 // Upon concluding that this matches the desired pattern, the function 4832 // will return the pair {NewAddRec, SmallPredsVec} where: 4833 // NewAddRec = {%Start,+,%Step} 4834 // SmallPredsVec = {P1, P2, P3} as follows: 4835 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4836 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4837 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4838 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4839 // under the predicates {P1,P2,P3}. 4840 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4841 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4842 // 4843 // TODO's: 4844 // 4845 // 1) Extend the Induction descriptor to also support inductions that involve 4846 // casts: When needed (namely, when we are called in the context of the 4847 // vectorizer induction analysis), a Set of cast instructions will be 4848 // populated by this method, and provided back to isInductionPHI. This is 4849 // needed to allow the vectorizer to properly record them to be ignored by 4850 // the cost model and to avoid vectorizing them (otherwise these casts, 4851 // which are redundant under the runtime overflow checks, will be 4852 // vectorized, which can be costly). 4853 // 4854 // 2) Support additional induction/PHISCEV patterns: We also want to support 4855 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4856 // after the induction update operation (the induction increment): 4857 // 4858 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4859 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4860 // 4861 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4862 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4863 // 4864 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4865 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4866 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4867 SmallVector<const SCEVPredicate *, 3> Predicates; 4868 4869 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4870 // return an AddRec expression under some predicate. 4871 4872 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4873 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4874 assert(L && "Expecting an integer loop header phi"); 4875 4876 // The loop may have multiple entrances or multiple exits; we can analyze 4877 // this phi as an addrec if it has a unique entry value and a unique 4878 // backedge value. 4879 Value *BEValueV = nullptr, *StartValueV = nullptr; 4880 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4881 Value *V = PN->getIncomingValue(i); 4882 if (L->contains(PN->getIncomingBlock(i))) { 4883 if (!BEValueV) { 4884 BEValueV = V; 4885 } else if (BEValueV != V) { 4886 BEValueV = nullptr; 4887 break; 4888 } 4889 } else if (!StartValueV) { 4890 StartValueV = V; 4891 } else if (StartValueV != V) { 4892 StartValueV = nullptr; 4893 break; 4894 } 4895 } 4896 if (!BEValueV || !StartValueV) 4897 return None; 4898 4899 const SCEV *BEValue = getSCEV(BEValueV); 4900 4901 // If the value coming around the backedge is an add with the symbolic 4902 // value we just inserted, possibly with casts that we can ignore under 4903 // an appropriate runtime guard, then we found a simple induction variable! 4904 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4905 if (!Add) 4906 return None; 4907 4908 // If there is a single occurrence of the symbolic value, possibly 4909 // casted, replace it with a recurrence. 4910 unsigned FoundIndex = Add->getNumOperands(); 4911 Type *TruncTy = nullptr; 4912 bool Signed; 4913 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4914 if ((TruncTy = 4915 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4916 if (FoundIndex == e) { 4917 FoundIndex = i; 4918 break; 4919 } 4920 4921 if (FoundIndex == Add->getNumOperands()) 4922 return None; 4923 4924 // Create an add with everything but the specified operand. 4925 SmallVector<const SCEV *, 8> Ops; 4926 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4927 if (i != FoundIndex) 4928 Ops.push_back(Add->getOperand(i)); 4929 const SCEV *Accum = getAddExpr(Ops); 4930 4931 // The runtime checks will not be valid if the step amount is 4932 // varying inside the loop. 4933 if (!isLoopInvariant(Accum, L)) 4934 return None; 4935 4936 // *** Part2: Create the predicates 4937 4938 // Analysis was successful: we have a phi-with-cast pattern for which we 4939 // can return an AddRec expression under the following predicates: 4940 // 4941 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4942 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4943 // P2: An Equal predicate that guarantees that 4944 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4945 // P3: An Equal predicate that guarantees that 4946 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4947 // 4948 // As we next prove, the above predicates guarantee that: 4949 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4950 // 4951 // 4952 // More formally, we want to prove that: 4953 // Expr(i+1) = Start + (i+1) * Accum 4954 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4955 // 4956 // Given that: 4957 // 1) Expr(0) = Start 4958 // 2) Expr(1) = Start + Accum 4959 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4960 // 3) Induction hypothesis (step i): 4961 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4962 // 4963 // Proof: 4964 // Expr(i+1) = 4965 // = Start + (i+1)*Accum 4966 // = (Start + i*Accum) + Accum 4967 // = Expr(i) + Accum 4968 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4969 // :: from step i 4970 // 4971 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4972 // 4973 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4974 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4975 // + Accum :: from P3 4976 // 4977 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4978 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4979 // 4980 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4981 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4982 // 4983 // By induction, the same applies to all iterations 1<=i<n: 4984 // 4985 4986 // Create a truncated addrec for which we will add a no overflow check (P1). 4987 const SCEV *StartVal = getSCEV(StartValueV); 4988 const SCEV *PHISCEV = 4989 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4990 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4991 4992 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4993 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4994 // will be constant. 4995 // 4996 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4997 // add P1. 4998 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4999 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5000 Signed ? SCEVWrapPredicate::IncrementNSSW 5001 : SCEVWrapPredicate::IncrementNUSW; 5002 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5003 Predicates.push_back(AddRecPred); 5004 } 5005 5006 // Create the Equal Predicates P2,P3: 5007 5008 // It is possible that the predicates P2 and/or P3 are computable at 5009 // compile time due to StartVal and/or Accum being constants. 5010 // If either one is, then we can check that now and escape if either P2 5011 // or P3 is false. 5012 5013 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5014 // for each of StartVal and Accum 5015 auto getExtendedExpr = [&](const SCEV *Expr, 5016 bool CreateSignExtend) -> const SCEV * { 5017 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5018 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5019 const SCEV *ExtendedExpr = 5020 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5021 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5022 return ExtendedExpr; 5023 }; 5024 5025 // Given: 5026 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5027 // = getExtendedExpr(Expr) 5028 // Determine whether the predicate P: Expr == ExtendedExpr 5029 // is known to be false at compile time 5030 auto PredIsKnownFalse = [&](const SCEV *Expr, 5031 const SCEV *ExtendedExpr) -> bool { 5032 return Expr != ExtendedExpr && 5033 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5034 }; 5035 5036 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5037 if (PredIsKnownFalse(StartVal, StartExtended)) { 5038 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5039 return None; 5040 } 5041 5042 // The Step is always Signed (because the overflow checks are either 5043 // NSSW or NUSW) 5044 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5045 if (PredIsKnownFalse(Accum, AccumExtended)) { 5046 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5047 return None; 5048 } 5049 5050 auto AppendPredicate = [&](const SCEV *Expr, 5051 const SCEV *ExtendedExpr) -> void { 5052 if (Expr != ExtendedExpr && 5053 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5054 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5055 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5056 Predicates.push_back(Pred); 5057 } 5058 }; 5059 5060 AppendPredicate(StartVal, StartExtended); 5061 AppendPredicate(Accum, AccumExtended); 5062 5063 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5064 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5065 // into NewAR if it will also add the runtime overflow checks specified in 5066 // Predicates. 5067 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5068 5069 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5070 std::make_pair(NewAR, Predicates); 5071 // Remember the result of the analysis for this SCEV at this locayyytion. 5072 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5073 return PredRewrite; 5074 } 5075 5076 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5077 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5078 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5079 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5080 if (!L) 5081 return None; 5082 5083 // Check to see if we already analyzed this PHI. 5084 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5085 if (I != PredicatedSCEVRewrites.end()) { 5086 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5087 I->second; 5088 // Analysis was done before and failed to create an AddRec: 5089 if (Rewrite.first == SymbolicPHI) 5090 return None; 5091 // Analysis was done before and succeeded to create an AddRec under 5092 // a predicate: 5093 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5094 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5095 return Rewrite; 5096 } 5097 5098 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5099 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5100 5101 // Record in the cache that the analysis failed 5102 if (!Rewrite) { 5103 SmallVector<const SCEVPredicate *, 3> Predicates; 5104 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5105 return None; 5106 } 5107 5108 return Rewrite; 5109 } 5110 5111 // FIXME: This utility is currently required because the Rewriter currently 5112 // does not rewrite this expression: 5113 // {0, +, (sext ix (trunc iy to ix) to iy)} 5114 // into {0, +, %step}, 5115 // even when the following Equal predicate exists: 5116 // "%step == (sext ix (trunc iy to ix) to iy)". 5117 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5118 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5119 if (AR1 == AR2) 5120 return true; 5121 5122 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5123 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 5124 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 5125 return false; 5126 return true; 5127 }; 5128 5129 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5130 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5131 return false; 5132 return true; 5133 } 5134 5135 /// A helper function for createAddRecFromPHI to handle simple cases. 5136 /// 5137 /// This function tries to find an AddRec expression for the simplest (yet most 5138 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5139 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5140 /// technique for finding the AddRec expression. 5141 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5142 Value *BEValueV, 5143 Value *StartValueV) { 5144 const Loop *L = LI.getLoopFor(PN->getParent()); 5145 assert(L && L->getHeader() == PN->getParent()); 5146 assert(BEValueV && StartValueV); 5147 5148 auto BO = MatchBinaryOp(BEValueV, DT); 5149 if (!BO) 5150 return nullptr; 5151 5152 if (BO->Opcode != Instruction::Add) 5153 return nullptr; 5154 5155 const SCEV *Accum = nullptr; 5156 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5157 Accum = getSCEV(BO->RHS); 5158 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5159 Accum = getSCEV(BO->LHS); 5160 5161 if (!Accum) 5162 return nullptr; 5163 5164 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5165 if (BO->IsNUW) 5166 Flags = setFlags(Flags, SCEV::FlagNUW); 5167 if (BO->IsNSW) 5168 Flags = setFlags(Flags, SCEV::FlagNSW); 5169 5170 const SCEV *StartVal = getSCEV(StartValueV); 5171 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5172 5173 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5174 5175 // We can add Flags to the post-inc expression only if we 5176 // know that it is *undefined behavior* for BEValueV to 5177 // overflow. 5178 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5179 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5180 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5181 5182 return PHISCEV; 5183 } 5184 5185 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5186 const Loop *L = LI.getLoopFor(PN->getParent()); 5187 if (!L || L->getHeader() != PN->getParent()) 5188 return nullptr; 5189 5190 // The loop may have multiple entrances or multiple exits; we can analyze 5191 // this phi as an addrec if it has a unique entry value and a unique 5192 // backedge value. 5193 Value *BEValueV = nullptr, *StartValueV = nullptr; 5194 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5195 Value *V = PN->getIncomingValue(i); 5196 if (L->contains(PN->getIncomingBlock(i))) { 5197 if (!BEValueV) { 5198 BEValueV = V; 5199 } else if (BEValueV != V) { 5200 BEValueV = nullptr; 5201 break; 5202 } 5203 } else if (!StartValueV) { 5204 StartValueV = V; 5205 } else if (StartValueV != V) { 5206 StartValueV = nullptr; 5207 break; 5208 } 5209 } 5210 if (!BEValueV || !StartValueV) 5211 return nullptr; 5212 5213 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5214 "PHI node already processed?"); 5215 5216 // First, try to find AddRec expression without creating a fictituos symbolic 5217 // value for PN. 5218 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5219 return S; 5220 5221 // Handle PHI node value symbolically. 5222 const SCEV *SymbolicName = getUnknown(PN); 5223 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5224 5225 // Using this symbolic name for the PHI, analyze the value coming around 5226 // the back-edge. 5227 const SCEV *BEValue = getSCEV(BEValueV); 5228 5229 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5230 // has a special value for the first iteration of the loop. 5231 5232 // If the value coming around the backedge is an add with the symbolic 5233 // value we just inserted, then we found a simple induction variable! 5234 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5235 // If there is a single occurrence of the symbolic value, replace it 5236 // with a recurrence. 5237 unsigned FoundIndex = Add->getNumOperands(); 5238 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5239 if (Add->getOperand(i) == SymbolicName) 5240 if (FoundIndex == e) { 5241 FoundIndex = i; 5242 break; 5243 } 5244 5245 if (FoundIndex != Add->getNumOperands()) { 5246 // Create an add with everything but the specified operand. 5247 SmallVector<const SCEV *, 8> Ops; 5248 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5249 if (i != FoundIndex) 5250 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5251 L, *this)); 5252 const SCEV *Accum = getAddExpr(Ops); 5253 5254 // This is not a valid addrec if the step amount is varying each 5255 // loop iteration, but is not itself an addrec in this loop. 5256 if (isLoopInvariant(Accum, L) || 5257 (isa<SCEVAddRecExpr>(Accum) && 5258 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5259 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5260 5261 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5262 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5263 if (BO->IsNUW) 5264 Flags = setFlags(Flags, SCEV::FlagNUW); 5265 if (BO->IsNSW) 5266 Flags = setFlags(Flags, SCEV::FlagNSW); 5267 } 5268 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5269 // If the increment is an inbounds GEP, then we know the address 5270 // space cannot be wrapped around. We cannot make any guarantee 5271 // about signed or unsigned overflow because pointers are 5272 // unsigned but we may have a negative index from the base 5273 // pointer. We can guarantee that no unsigned wrap occurs if the 5274 // indices form a positive value. 5275 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5276 Flags = setFlags(Flags, SCEV::FlagNW); 5277 5278 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5279 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5280 Flags = setFlags(Flags, SCEV::FlagNUW); 5281 } 5282 5283 // We cannot transfer nuw and nsw flags from subtraction 5284 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5285 // for instance. 5286 } 5287 5288 const SCEV *StartVal = getSCEV(StartValueV); 5289 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5290 5291 // Okay, for the entire analysis of this edge we assumed the PHI 5292 // to be symbolic. We now need to go back and purge all of the 5293 // entries for the scalars that use the symbolic expression. 5294 forgetSymbolicName(PN, SymbolicName); 5295 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5296 5297 // We can add Flags to the post-inc expression only if we 5298 // know that it is *undefined behavior* for BEValueV to 5299 // overflow. 5300 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5301 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5302 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5303 5304 return PHISCEV; 5305 } 5306 } 5307 } else { 5308 // Otherwise, this could be a loop like this: 5309 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5310 // In this case, j = {1,+,1} and BEValue is j. 5311 // Because the other in-value of i (0) fits the evolution of BEValue 5312 // i really is an addrec evolution. 5313 // 5314 // We can generalize this saying that i is the shifted value of BEValue 5315 // by one iteration: 5316 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5317 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5318 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5319 if (Shifted != getCouldNotCompute() && 5320 Start != getCouldNotCompute()) { 5321 const SCEV *StartVal = getSCEV(StartValueV); 5322 if (Start == StartVal) { 5323 // Okay, for the entire analysis of this edge we assumed the PHI 5324 // to be symbolic. We now need to go back and purge all of the 5325 // entries for the scalars that use the symbolic expression. 5326 forgetSymbolicName(PN, SymbolicName); 5327 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5328 return Shifted; 5329 } 5330 } 5331 } 5332 5333 // Remove the temporary PHI node SCEV that has been inserted while intending 5334 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5335 // as it will prevent later (possibly simpler) SCEV expressions to be added 5336 // to the ValueExprMap. 5337 eraseValueFromMap(PN); 5338 5339 return nullptr; 5340 } 5341 5342 // Checks if the SCEV S is available at BB. S is considered available at BB 5343 // if S can be materialized at BB without introducing a fault. 5344 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5345 BasicBlock *BB) { 5346 struct CheckAvailable { 5347 bool TraversalDone = false; 5348 bool Available = true; 5349 5350 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5351 BasicBlock *BB = nullptr; 5352 DominatorTree &DT; 5353 5354 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5355 : L(L), BB(BB), DT(DT) {} 5356 5357 bool setUnavailable() { 5358 TraversalDone = true; 5359 Available = false; 5360 return false; 5361 } 5362 5363 bool follow(const SCEV *S) { 5364 switch (S->getSCEVType()) { 5365 case scConstant: 5366 case scPtrToInt: 5367 case scTruncate: 5368 case scZeroExtend: 5369 case scSignExtend: 5370 case scAddExpr: 5371 case scMulExpr: 5372 case scUMaxExpr: 5373 case scSMaxExpr: 5374 case scUMinExpr: 5375 case scSMinExpr: 5376 // These expressions are available if their operand(s) is/are. 5377 return true; 5378 5379 case scAddRecExpr: { 5380 // We allow add recurrences that are on the loop BB is in, or some 5381 // outer loop. This guarantees availability because the value of the 5382 // add recurrence at BB is simply the "current" value of the induction 5383 // variable. We can relax this in the future; for instance an add 5384 // recurrence on a sibling dominating loop is also available at BB. 5385 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5386 if (L && (ARLoop == L || ARLoop->contains(L))) 5387 return true; 5388 5389 return setUnavailable(); 5390 } 5391 5392 case scUnknown: { 5393 // For SCEVUnknown, we check for simple dominance. 5394 const auto *SU = cast<SCEVUnknown>(S); 5395 Value *V = SU->getValue(); 5396 5397 if (isa<Argument>(V)) 5398 return false; 5399 5400 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5401 return false; 5402 5403 return setUnavailable(); 5404 } 5405 5406 case scUDivExpr: 5407 case scCouldNotCompute: 5408 // We do not try to smart about these at all. 5409 return setUnavailable(); 5410 } 5411 llvm_unreachable("Unknown SCEV kind!"); 5412 } 5413 5414 bool isDone() { return TraversalDone; } 5415 }; 5416 5417 CheckAvailable CA(L, BB, DT); 5418 SCEVTraversal<CheckAvailable> ST(CA); 5419 5420 ST.visitAll(S); 5421 return CA.Available; 5422 } 5423 5424 // Try to match a control flow sequence that branches out at BI and merges back 5425 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5426 // match. 5427 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5428 Value *&C, Value *&LHS, Value *&RHS) { 5429 C = BI->getCondition(); 5430 5431 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5432 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5433 5434 if (!LeftEdge.isSingleEdge()) 5435 return false; 5436 5437 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5438 5439 Use &LeftUse = Merge->getOperandUse(0); 5440 Use &RightUse = Merge->getOperandUse(1); 5441 5442 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5443 LHS = LeftUse; 5444 RHS = RightUse; 5445 return true; 5446 } 5447 5448 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5449 LHS = RightUse; 5450 RHS = LeftUse; 5451 return true; 5452 } 5453 5454 return false; 5455 } 5456 5457 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5458 auto IsReachable = 5459 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5460 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5461 const Loop *L = LI.getLoopFor(PN->getParent()); 5462 5463 // We don't want to break LCSSA, even in a SCEV expression tree. 5464 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5465 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5466 return nullptr; 5467 5468 // Try to match 5469 // 5470 // br %cond, label %left, label %right 5471 // left: 5472 // br label %merge 5473 // right: 5474 // br label %merge 5475 // merge: 5476 // V = phi [ %x, %left ], [ %y, %right ] 5477 // 5478 // as "select %cond, %x, %y" 5479 5480 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5481 assert(IDom && "At least the entry block should dominate PN"); 5482 5483 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5484 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5485 5486 if (BI && BI->isConditional() && 5487 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5488 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5489 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5490 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5491 } 5492 5493 return nullptr; 5494 } 5495 5496 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5497 if (const SCEV *S = createAddRecFromPHI(PN)) 5498 return S; 5499 5500 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5501 return S; 5502 5503 // If the PHI has a single incoming value, follow that value, unless the 5504 // PHI's incoming blocks are in a different loop, in which case doing so 5505 // risks breaking LCSSA form. Instcombine would normally zap these, but 5506 // it doesn't have DominatorTree information, so it may miss cases. 5507 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5508 if (LI.replacementPreservesLCSSAForm(PN, V)) 5509 return getSCEV(V); 5510 5511 // If it's not a loop phi, we can't handle it yet. 5512 return getUnknown(PN); 5513 } 5514 5515 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5516 Value *Cond, 5517 Value *TrueVal, 5518 Value *FalseVal) { 5519 // Handle "constant" branch or select. This can occur for instance when a 5520 // loop pass transforms an inner loop and moves on to process the outer loop. 5521 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5522 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5523 5524 // Try to match some simple smax or umax patterns. 5525 auto *ICI = dyn_cast<ICmpInst>(Cond); 5526 if (!ICI) 5527 return getUnknown(I); 5528 5529 Value *LHS = ICI->getOperand(0); 5530 Value *RHS = ICI->getOperand(1); 5531 5532 switch (ICI->getPredicate()) { 5533 case ICmpInst::ICMP_SLT: 5534 case ICmpInst::ICMP_SLE: 5535 std::swap(LHS, RHS); 5536 LLVM_FALLTHROUGH; 5537 case ICmpInst::ICMP_SGT: 5538 case ICmpInst::ICMP_SGE: 5539 // a >s b ? a+x : b+x -> smax(a, b)+x 5540 // a >s b ? b+x : a+x -> smin(a, b)+x 5541 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5542 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5543 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5544 const SCEV *LA = getSCEV(TrueVal); 5545 const SCEV *RA = getSCEV(FalseVal); 5546 const SCEV *LDiff = getMinusSCEV(LA, LS); 5547 const SCEV *RDiff = getMinusSCEV(RA, RS); 5548 if (LDiff == RDiff) 5549 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5550 LDiff = getMinusSCEV(LA, RS); 5551 RDiff = getMinusSCEV(RA, LS); 5552 if (LDiff == RDiff) 5553 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5554 } 5555 break; 5556 case ICmpInst::ICMP_ULT: 5557 case ICmpInst::ICMP_ULE: 5558 std::swap(LHS, RHS); 5559 LLVM_FALLTHROUGH; 5560 case ICmpInst::ICMP_UGT: 5561 case ICmpInst::ICMP_UGE: 5562 // a >u b ? a+x : b+x -> umax(a, b)+x 5563 // a >u b ? b+x : a+x -> umin(a, b)+x 5564 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5565 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5566 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5567 const SCEV *LA = getSCEV(TrueVal); 5568 const SCEV *RA = getSCEV(FalseVal); 5569 const SCEV *LDiff = getMinusSCEV(LA, LS); 5570 const SCEV *RDiff = getMinusSCEV(RA, RS); 5571 if (LDiff == RDiff) 5572 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5573 LDiff = getMinusSCEV(LA, RS); 5574 RDiff = getMinusSCEV(RA, LS); 5575 if (LDiff == RDiff) 5576 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5577 } 5578 break; 5579 case ICmpInst::ICMP_NE: 5580 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5581 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5582 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5583 const SCEV *One = getOne(I->getType()); 5584 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5585 const SCEV *LA = getSCEV(TrueVal); 5586 const SCEV *RA = getSCEV(FalseVal); 5587 const SCEV *LDiff = getMinusSCEV(LA, LS); 5588 const SCEV *RDiff = getMinusSCEV(RA, One); 5589 if (LDiff == RDiff) 5590 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5591 } 5592 break; 5593 case ICmpInst::ICMP_EQ: 5594 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5595 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5596 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5597 const SCEV *One = getOne(I->getType()); 5598 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5599 const SCEV *LA = getSCEV(TrueVal); 5600 const SCEV *RA = getSCEV(FalseVal); 5601 const SCEV *LDiff = getMinusSCEV(LA, One); 5602 const SCEV *RDiff = getMinusSCEV(RA, LS); 5603 if (LDiff == RDiff) 5604 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5605 } 5606 break; 5607 default: 5608 break; 5609 } 5610 5611 return getUnknown(I); 5612 } 5613 5614 /// Expand GEP instructions into add and multiply operations. This allows them 5615 /// to be analyzed by regular SCEV code. 5616 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5617 // Don't attempt to analyze GEPs over unsized objects. 5618 if (!GEP->getSourceElementType()->isSized()) 5619 return getUnknown(GEP); 5620 5621 SmallVector<const SCEV *, 4> IndexExprs; 5622 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5623 IndexExprs.push_back(getSCEV(*Index)); 5624 return getGEPExpr(GEP, IndexExprs); 5625 } 5626 5627 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5628 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5629 return C->getAPInt().countTrailingZeros(); 5630 5631 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5632 return GetMinTrailingZeros(I->getOperand()); 5633 5634 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5635 return std::min(GetMinTrailingZeros(T->getOperand()), 5636 (uint32_t)getTypeSizeInBits(T->getType())); 5637 5638 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5639 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5640 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5641 ? getTypeSizeInBits(E->getType()) 5642 : OpRes; 5643 } 5644 5645 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5646 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5647 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5648 ? getTypeSizeInBits(E->getType()) 5649 : OpRes; 5650 } 5651 5652 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5653 // The result is the min of all operands results. 5654 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5655 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5656 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5657 return MinOpRes; 5658 } 5659 5660 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5661 // The result is the sum of all operands results. 5662 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5663 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5664 for (unsigned i = 1, e = M->getNumOperands(); 5665 SumOpRes != BitWidth && i != e; ++i) 5666 SumOpRes = 5667 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5668 return SumOpRes; 5669 } 5670 5671 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5672 // The result is the min of all operands results. 5673 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5674 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5675 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5676 return MinOpRes; 5677 } 5678 5679 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5680 // The result is the min of all operands results. 5681 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5682 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5683 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5684 return MinOpRes; 5685 } 5686 5687 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5688 // The result is the min of all operands results. 5689 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5690 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5691 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5692 return MinOpRes; 5693 } 5694 5695 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5696 // For a SCEVUnknown, ask ValueTracking. 5697 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5698 return Known.countMinTrailingZeros(); 5699 } 5700 5701 // SCEVUDivExpr 5702 return 0; 5703 } 5704 5705 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5706 auto I = MinTrailingZerosCache.find(S); 5707 if (I != MinTrailingZerosCache.end()) 5708 return I->second; 5709 5710 uint32_t Result = GetMinTrailingZerosImpl(S); 5711 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5712 assert(InsertPair.second && "Should insert a new key"); 5713 return InsertPair.first->second; 5714 } 5715 5716 /// Helper method to assign a range to V from metadata present in the IR. 5717 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5718 if (Instruction *I = dyn_cast<Instruction>(V)) 5719 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5720 return getConstantRangeFromMetadata(*MD); 5721 5722 return None; 5723 } 5724 5725 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 5726 SCEV::NoWrapFlags Flags) { 5727 if (AddRec->getNoWrapFlags(Flags) != Flags) { 5728 AddRec->setNoWrapFlags(Flags); 5729 UnsignedRanges.erase(AddRec); 5730 SignedRanges.erase(AddRec); 5731 } 5732 } 5733 5734 ConstantRange ScalarEvolution:: 5735 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 5736 const DataLayout &DL = getDataLayout(); 5737 5738 unsigned BitWidth = getTypeSizeInBits(U->getType()); 5739 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 5740 5741 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 5742 // use information about the trip count to improve our available range. Note 5743 // that the trip count independent cases are already handled by known bits. 5744 // WARNING: The definition of recurrence used here is subtly different than 5745 // the one used by AddRec (and thus most of this file). Step is allowed to 5746 // be arbitrarily loop varying here, where AddRec allows only loop invariant 5747 // and other addrecs in the same loop (for non-affine addrecs). The code 5748 // below intentionally handles the case where step is not loop invariant. 5749 auto *P = dyn_cast<PHINode>(U->getValue()); 5750 if (!P) 5751 return FullSet; 5752 5753 // Make sure that no Phi input comes from an unreachable block. Otherwise, 5754 // even the values that are not available in these blocks may come from them, 5755 // and this leads to false-positive recurrence test. 5756 for (auto *Pred : predecessors(P->getParent())) 5757 if (!DT.isReachableFromEntry(Pred)) 5758 return FullSet; 5759 5760 BinaryOperator *BO; 5761 Value *Start, *Step; 5762 if (!matchSimpleRecurrence(P, BO, Start, Step)) 5763 return FullSet; 5764 5765 // If we found a recurrence in reachable code, we must be in a loop. Note 5766 // that BO might be in some subloop of L, and that's completely okay. 5767 auto *L = LI.getLoopFor(P->getParent()); 5768 assert(L && L->getHeader() == P->getParent()); 5769 if (!L->contains(BO->getParent())) 5770 // NOTE: This bailout should be an assert instead. However, asserting 5771 // the condition here exposes a case where LoopFusion is querying SCEV 5772 // with malformed loop information during the midst of the transform. 5773 // There doesn't appear to be an obvious fix, so for the moment bailout 5774 // until the caller issue can be fixed. PR49566 tracks the bug. 5775 return FullSet; 5776 5777 // TODO: Extend to other opcodes such as mul, and div 5778 switch (BO->getOpcode()) { 5779 default: 5780 return FullSet; 5781 case Instruction::AShr: 5782 case Instruction::LShr: 5783 case Instruction::Shl: 5784 break; 5785 }; 5786 5787 if (BO->getOperand(0) != P) 5788 // TODO: Handle the power function forms some day. 5789 return FullSet; 5790 5791 unsigned TC = getSmallConstantMaxTripCount(L); 5792 if (!TC || TC >= BitWidth) 5793 return FullSet; 5794 5795 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 5796 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 5797 assert(KnownStart.getBitWidth() == BitWidth && 5798 KnownStep.getBitWidth() == BitWidth); 5799 5800 // Compute total shift amount, being careful of overflow and bitwidths. 5801 auto MaxShiftAmt = KnownStep.getMaxValue(); 5802 APInt TCAP(BitWidth, TC-1); 5803 bool Overflow = false; 5804 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 5805 if (Overflow) 5806 return FullSet; 5807 5808 switch (BO->getOpcode()) { 5809 default: 5810 llvm_unreachable("filtered out above"); 5811 case Instruction::AShr: { 5812 // For each ashr, three cases: 5813 // shift = 0 => unchanged value 5814 // saturation => 0 or -1 5815 // other => a value closer to zero (of the same sign) 5816 // Thus, the end value is closer to zero than the start. 5817 auto KnownEnd = KnownBits::ashr(KnownStart, 5818 KnownBits::makeConstant(TotalShift)); 5819 if (KnownStart.isNonNegative()) 5820 // Analogous to lshr (simply not yet canonicalized) 5821 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5822 KnownStart.getMaxValue() + 1); 5823 if (KnownStart.isNegative()) 5824 // End >=u Start && End <=s Start 5825 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 5826 KnownEnd.getMaxValue() + 1); 5827 break; 5828 } 5829 case Instruction::LShr: { 5830 // For each lshr, three cases: 5831 // shift = 0 => unchanged value 5832 // saturation => 0 5833 // other => a smaller positive number 5834 // Thus, the low end of the unsigned range is the last value produced. 5835 auto KnownEnd = KnownBits::lshr(KnownStart, 5836 KnownBits::makeConstant(TotalShift)); 5837 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 5838 KnownStart.getMaxValue() + 1); 5839 } 5840 case Instruction::Shl: { 5841 // Iff no bits are shifted out, value increases on every shift. 5842 auto KnownEnd = KnownBits::shl(KnownStart, 5843 KnownBits::makeConstant(TotalShift)); 5844 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 5845 return ConstantRange(KnownStart.getMinValue(), 5846 KnownEnd.getMaxValue() + 1); 5847 break; 5848 } 5849 }; 5850 return FullSet; 5851 } 5852 5853 /// Determine the range for a particular SCEV. If SignHint is 5854 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5855 /// with a "cleaner" unsigned (resp. signed) representation. 5856 const ConstantRange & 5857 ScalarEvolution::getRangeRef(const SCEV *S, 5858 ScalarEvolution::RangeSignHint SignHint) { 5859 DenseMap<const SCEV *, ConstantRange> &Cache = 5860 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5861 : SignedRanges; 5862 ConstantRange::PreferredRangeType RangeType = 5863 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5864 ? ConstantRange::Unsigned : ConstantRange::Signed; 5865 5866 // See if we've computed this range already. 5867 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5868 if (I != Cache.end()) 5869 return I->second; 5870 5871 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5872 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5873 5874 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5875 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5876 using OBO = OverflowingBinaryOperator; 5877 5878 // If the value has known zeros, the maximum value will have those known zeros 5879 // as well. 5880 uint32_t TZ = GetMinTrailingZeros(S); 5881 if (TZ != 0) { 5882 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5883 ConservativeResult = 5884 ConstantRange(APInt::getMinValue(BitWidth), 5885 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5886 else 5887 ConservativeResult = ConstantRange( 5888 APInt::getSignedMinValue(BitWidth), 5889 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5890 } 5891 5892 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5893 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5894 unsigned WrapType = OBO::AnyWrap; 5895 if (Add->hasNoSignedWrap()) 5896 WrapType |= OBO::NoSignedWrap; 5897 if (Add->hasNoUnsignedWrap()) 5898 WrapType |= OBO::NoUnsignedWrap; 5899 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5900 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5901 WrapType, RangeType); 5902 return setRange(Add, SignHint, 5903 ConservativeResult.intersectWith(X, RangeType)); 5904 } 5905 5906 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5907 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5908 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5909 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5910 return setRange(Mul, SignHint, 5911 ConservativeResult.intersectWith(X, RangeType)); 5912 } 5913 5914 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5915 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5916 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5917 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5918 return setRange(SMax, SignHint, 5919 ConservativeResult.intersectWith(X, RangeType)); 5920 } 5921 5922 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5923 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5924 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5925 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5926 return setRange(UMax, SignHint, 5927 ConservativeResult.intersectWith(X, RangeType)); 5928 } 5929 5930 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5931 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5932 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5933 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5934 return setRange(SMin, SignHint, 5935 ConservativeResult.intersectWith(X, RangeType)); 5936 } 5937 5938 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5939 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5940 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5941 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5942 return setRange(UMin, SignHint, 5943 ConservativeResult.intersectWith(X, RangeType)); 5944 } 5945 5946 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5947 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5948 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5949 return setRange(UDiv, SignHint, 5950 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5951 } 5952 5953 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5954 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5955 return setRange(ZExt, SignHint, 5956 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5957 RangeType)); 5958 } 5959 5960 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5961 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5962 return setRange(SExt, SignHint, 5963 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5964 RangeType)); 5965 } 5966 5967 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 5968 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 5969 return setRange(PtrToInt, SignHint, X); 5970 } 5971 5972 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5973 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5974 return setRange(Trunc, SignHint, 5975 ConservativeResult.intersectWith(X.truncate(BitWidth), 5976 RangeType)); 5977 } 5978 5979 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5980 // If there's no unsigned wrap, the value will never be less than its 5981 // initial value. 5982 if (AddRec->hasNoUnsignedWrap()) { 5983 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5984 if (!UnsignedMinValue.isNullValue()) 5985 ConservativeResult = ConservativeResult.intersectWith( 5986 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5987 } 5988 5989 // If there's no signed wrap, and all the operands except initial value have 5990 // the same sign or zero, the value won't ever be: 5991 // 1: smaller than initial value if operands are non negative, 5992 // 2: bigger than initial value if operands are non positive. 5993 // For both cases, value can not cross signed min/max boundary. 5994 if (AddRec->hasNoSignedWrap()) { 5995 bool AllNonNeg = true; 5996 bool AllNonPos = true; 5997 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5998 if (!isKnownNonNegative(AddRec->getOperand(i))) 5999 AllNonNeg = false; 6000 if (!isKnownNonPositive(AddRec->getOperand(i))) 6001 AllNonPos = false; 6002 } 6003 if (AllNonNeg) 6004 ConservativeResult = ConservativeResult.intersectWith( 6005 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6006 APInt::getSignedMinValue(BitWidth)), 6007 RangeType); 6008 else if (AllNonPos) 6009 ConservativeResult = ConservativeResult.intersectWith( 6010 ConstantRange::getNonEmpty( 6011 APInt::getSignedMinValue(BitWidth), 6012 getSignedRangeMax(AddRec->getStart()) + 1), 6013 RangeType); 6014 } 6015 6016 // TODO: non-affine addrec 6017 if (AddRec->isAffine()) { 6018 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6019 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6020 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6021 auto RangeFromAffine = getRangeForAffineAR( 6022 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6023 BitWidth); 6024 ConservativeResult = 6025 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6026 6027 auto RangeFromFactoring = getRangeViaFactoring( 6028 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6029 BitWidth); 6030 ConservativeResult = 6031 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6032 } 6033 6034 // Now try symbolic BE count and more powerful methods. 6035 if (UseExpensiveRangeSharpening) { 6036 const SCEV *SymbolicMaxBECount = 6037 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6038 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6039 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6040 AddRec->hasNoSelfWrap()) { 6041 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6042 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6043 ConservativeResult = 6044 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6045 } 6046 } 6047 } 6048 6049 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6050 } 6051 6052 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6053 6054 // Check if the IR explicitly contains !range metadata. 6055 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6056 if (MDRange.hasValue()) 6057 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6058 RangeType); 6059 6060 // Use facts about recurrences in the underlying IR. Note that add 6061 // recurrences are AddRecExprs and thus don't hit this path. This 6062 // primarily handles shift recurrences. 6063 auto CR = getRangeForUnknownRecurrence(U); 6064 ConservativeResult = ConservativeResult.intersectWith(CR); 6065 6066 // See if ValueTracking can give us a useful range. 6067 const DataLayout &DL = getDataLayout(); 6068 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6069 if (Known.getBitWidth() != BitWidth) 6070 Known = Known.zextOrTrunc(BitWidth); 6071 6072 // ValueTracking may be able to compute a tighter result for the number of 6073 // sign bits than for the value of those sign bits. 6074 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6075 if (U->getType()->isPointerTy()) { 6076 // If the pointer size is larger than the index size type, this can cause 6077 // NS to be larger than BitWidth. So compensate for this. 6078 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6079 int ptrIdxDiff = ptrSize - BitWidth; 6080 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6081 NS -= ptrIdxDiff; 6082 } 6083 6084 if (NS > 1) { 6085 // If we know any of the sign bits, we know all of the sign bits. 6086 if (!Known.Zero.getHiBits(NS).isNullValue()) 6087 Known.Zero.setHighBits(NS); 6088 if (!Known.One.getHiBits(NS).isNullValue()) 6089 Known.One.setHighBits(NS); 6090 } 6091 6092 if (Known.getMinValue() != Known.getMaxValue() + 1) 6093 ConservativeResult = ConservativeResult.intersectWith( 6094 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6095 RangeType); 6096 if (NS > 1) 6097 ConservativeResult = ConservativeResult.intersectWith( 6098 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6099 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6100 RangeType); 6101 6102 // A range of Phi is a subset of union of all ranges of its input. 6103 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 6104 // Make sure that we do not run over cycled Phis. 6105 if (PendingPhiRanges.insert(Phi).second) { 6106 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 6107 for (auto &Op : Phi->operands()) { 6108 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 6109 RangeFromOps = RangeFromOps.unionWith(OpRange); 6110 // No point to continue if we already have a full set. 6111 if (RangeFromOps.isFullSet()) 6112 break; 6113 } 6114 ConservativeResult = 6115 ConservativeResult.intersectWith(RangeFromOps, RangeType); 6116 bool Erased = PendingPhiRanges.erase(Phi); 6117 assert(Erased && "Failed to erase Phi properly?"); 6118 (void) Erased; 6119 } 6120 } 6121 6122 return setRange(U, SignHint, std::move(ConservativeResult)); 6123 } 6124 6125 return setRange(S, SignHint, std::move(ConservativeResult)); 6126 } 6127 6128 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6129 // values that the expression can take. Initially, the expression has a value 6130 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6131 // argument defines if we treat Step as signed or unsigned. 6132 static ConstantRange getRangeForAffineARHelper(APInt Step, 6133 const ConstantRange &StartRange, 6134 const APInt &MaxBECount, 6135 unsigned BitWidth, bool Signed) { 6136 // If either Step or MaxBECount is 0, then the expression won't change, and we 6137 // just need to return the initial range. 6138 if (Step == 0 || MaxBECount == 0) 6139 return StartRange; 6140 6141 // If we don't know anything about the initial value (i.e. StartRange is 6142 // FullRange), then we don't know anything about the final range either. 6143 // Return FullRange. 6144 if (StartRange.isFullSet()) 6145 return ConstantRange::getFull(BitWidth); 6146 6147 // If Step is signed and negative, then we use its absolute value, but we also 6148 // note that we're moving in the opposite direction. 6149 bool Descending = Signed && Step.isNegative(); 6150 6151 if (Signed) 6152 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6153 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6154 // This equations hold true due to the well-defined wrap-around behavior of 6155 // APInt. 6156 Step = Step.abs(); 6157 6158 // Check if Offset is more than full span of BitWidth. If it is, the 6159 // expression is guaranteed to overflow. 6160 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6161 return ConstantRange::getFull(BitWidth); 6162 6163 // Offset is by how much the expression can change. Checks above guarantee no 6164 // overflow here. 6165 APInt Offset = Step * MaxBECount; 6166 6167 // Minimum value of the final range will match the minimal value of StartRange 6168 // if the expression is increasing and will be decreased by Offset otherwise. 6169 // Maximum value of the final range will match the maximal value of StartRange 6170 // if the expression is decreasing and will be increased by Offset otherwise. 6171 APInt StartLower = StartRange.getLower(); 6172 APInt StartUpper = StartRange.getUpper() - 1; 6173 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6174 : (StartUpper + std::move(Offset)); 6175 6176 // It's possible that the new minimum/maximum value will fall into the initial 6177 // range (due to wrap around). This means that the expression can take any 6178 // value in this bitwidth, and we have to return full range. 6179 if (StartRange.contains(MovedBoundary)) 6180 return ConstantRange::getFull(BitWidth); 6181 6182 APInt NewLower = 6183 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6184 APInt NewUpper = 6185 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6186 NewUpper += 1; 6187 6188 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6189 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6190 } 6191 6192 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6193 const SCEV *Step, 6194 const SCEV *MaxBECount, 6195 unsigned BitWidth) { 6196 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6197 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6198 "Precondition!"); 6199 6200 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6201 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6202 6203 // First, consider step signed. 6204 ConstantRange StartSRange = getSignedRange(Start); 6205 ConstantRange StepSRange = getSignedRange(Step); 6206 6207 // If Step can be both positive and negative, we need to find ranges for the 6208 // maximum absolute step values in both directions and union them. 6209 ConstantRange SR = 6210 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6211 MaxBECountValue, BitWidth, /* Signed = */ true); 6212 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6213 StartSRange, MaxBECountValue, 6214 BitWidth, /* Signed = */ true)); 6215 6216 // Next, consider step unsigned. 6217 ConstantRange UR = getRangeForAffineARHelper( 6218 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6219 MaxBECountValue, BitWidth, /* Signed = */ false); 6220 6221 // Finally, intersect signed and unsigned ranges. 6222 return SR.intersectWith(UR, ConstantRange::Smallest); 6223 } 6224 6225 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6226 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6227 ScalarEvolution::RangeSignHint SignHint) { 6228 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6229 assert(AddRec->hasNoSelfWrap() && 6230 "This only works for non-self-wrapping AddRecs!"); 6231 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6232 const SCEV *Step = AddRec->getStepRecurrence(*this); 6233 // Only deal with constant step to save compile time. 6234 if (!isa<SCEVConstant>(Step)) 6235 return ConstantRange::getFull(BitWidth); 6236 // Let's make sure that we can prove that we do not self-wrap during 6237 // MaxBECount iterations. We need this because MaxBECount is a maximum 6238 // iteration count estimate, and we might infer nw from some exit for which we 6239 // do not know max exit count (or any other side reasoning). 6240 // TODO: Turn into assert at some point. 6241 if (getTypeSizeInBits(MaxBECount->getType()) > 6242 getTypeSizeInBits(AddRec->getType())) 6243 return ConstantRange::getFull(BitWidth); 6244 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6245 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6246 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6247 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6248 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6249 MaxItersWithoutWrap)) 6250 return ConstantRange::getFull(BitWidth); 6251 6252 ICmpInst::Predicate LEPred = 6253 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6254 ICmpInst::Predicate GEPred = 6255 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6256 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6257 6258 // We know that there is no self-wrap. Let's take Start and End values and 6259 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6260 // the iteration. They either lie inside the range [Min(Start, End), 6261 // Max(Start, End)] or outside it: 6262 // 6263 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6264 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6265 // 6266 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6267 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6268 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6269 // Start <= End and step is positive, or Start >= End and step is negative. 6270 const SCEV *Start = AddRec->getStart(); 6271 ConstantRange StartRange = getRangeRef(Start, SignHint); 6272 ConstantRange EndRange = getRangeRef(End, SignHint); 6273 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6274 // If they already cover full iteration space, we will know nothing useful 6275 // even if we prove what we want to prove. 6276 if (RangeBetween.isFullSet()) 6277 return RangeBetween; 6278 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6279 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6280 : RangeBetween.isWrappedSet(); 6281 if (IsWrappedSet) 6282 return ConstantRange::getFull(BitWidth); 6283 6284 if (isKnownPositive(Step) && 6285 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6286 return RangeBetween; 6287 else if (isKnownNegative(Step) && 6288 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6289 return RangeBetween; 6290 return ConstantRange::getFull(BitWidth); 6291 } 6292 6293 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6294 const SCEV *Step, 6295 const SCEV *MaxBECount, 6296 unsigned BitWidth) { 6297 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6298 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6299 6300 struct SelectPattern { 6301 Value *Condition = nullptr; 6302 APInt TrueValue; 6303 APInt FalseValue; 6304 6305 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6306 const SCEV *S) { 6307 Optional<unsigned> CastOp; 6308 APInt Offset(BitWidth, 0); 6309 6310 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6311 "Should be!"); 6312 6313 // Peel off a constant offset: 6314 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6315 // In the future we could consider being smarter here and handle 6316 // {Start+Step,+,Step} too. 6317 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6318 return; 6319 6320 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6321 S = SA->getOperand(1); 6322 } 6323 6324 // Peel off a cast operation 6325 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6326 CastOp = SCast->getSCEVType(); 6327 S = SCast->getOperand(); 6328 } 6329 6330 using namespace llvm::PatternMatch; 6331 6332 auto *SU = dyn_cast<SCEVUnknown>(S); 6333 const APInt *TrueVal, *FalseVal; 6334 if (!SU || 6335 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6336 m_APInt(FalseVal)))) { 6337 Condition = nullptr; 6338 return; 6339 } 6340 6341 TrueValue = *TrueVal; 6342 FalseValue = *FalseVal; 6343 6344 // Re-apply the cast we peeled off earlier 6345 if (CastOp.hasValue()) 6346 switch (*CastOp) { 6347 default: 6348 llvm_unreachable("Unknown SCEV cast type!"); 6349 6350 case scTruncate: 6351 TrueValue = TrueValue.trunc(BitWidth); 6352 FalseValue = FalseValue.trunc(BitWidth); 6353 break; 6354 case scZeroExtend: 6355 TrueValue = TrueValue.zext(BitWidth); 6356 FalseValue = FalseValue.zext(BitWidth); 6357 break; 6358 case scSignExtend: 6359 TrueValue = TrueValue.sext(BitWidth); 6360 FalseValue = FalseValue.sext(BitWidth); 6361 break; 6362 } 6363 6364 // Re-apply the constant offset we peeled off earlier 6365 TrueValue += Offset; 6366 FalseValue += Offset; 6367 } 6368 6369 bool isRecognized() { return Condition != nullptr; } 6370 }; 6371 6372 SelectPattern StartPattern(*this, BitWidth, Start); 6373 if (!StartPattern.isRecognized()) 6374 return ConstantRange::getFull(BitWidth); 6375 6376 SelectPattern StepPattern(*this, BitWidth, Step); 6377 if (!StepPattern.isRecognized()) 6378 return ConstantRange::getFull(BitWidth); 6379 6380 if (StartPattern.Condition != StepPattern.Condition) { 6381 // We don't handle this case today; but we could, by considering four 6382 // possibilities below instead of two. I'm not sure if there are cases where 6383 // that will help over what getRange already does, though. 6384 return ConstantRange::getFull(BitWidth); 6385 } 6386 6387 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6388 // construct arbitrary general SCEV expressions here. This function is called 6389 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6390 // say) can end up caching a suboptimal value. 6391 6392 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6393 // C2352 and C2512 (otherwise it isn't needed). 6394 6395 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6396 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6397 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6398 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6399 6400 ConstantRange TrueRange = 6401 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6402 ConstantRange FalseRange = 6403 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6404 6405 return TrueRange.unionWith(FalseRange); 6406 } 6407 6408 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6409 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6410 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6411 6412 // Return early if there are no flags to propagate to the SCEV. 6413 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6414 if (BinOp->hasNoUnsignedWrap()) 6415 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6416 if (BinOp->hasNoSignedWrap()) 6417 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6418 if (Flags == SCEV::FlagAnyWrap) 6419 return SCEV::FlagAnyWrap; 6420 6421 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6422 } 6423 6424 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6425 // Here we check that I is in the header of the innermost loop containing I, 6426 // since we only deal with instructions in the loop header. The actual loop we 6427 // need to check later will come from an add recurrence, but getting that 6428 // requires computing the SCEV of the operands, which can be expensive. This 6429 // check we can do cheaply to rule out some cases early. 6430 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6431 if (InnermostContainingLoop == nullptr || 6432 InnermostContainingLoop->getHeader() != I->getParent()) 6433 return false; 6434 6435 // Only proceed if we can prove that I does not yield poison. 6436 if (!programUndefinedIfPoison(I)) 6437 return false; 6438 6439 // At this point we know that if I is executed, then it does not wrap 6440 // according to at least one of NSW or NUW. If I is not executed, then we do 6441 // not know if the calculation that I represents would wrap. Multiple 6442 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6443 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6444 // derived from other instructions that map to the same SCEV. We cannot make 6445 // that guarantee for cases where I is not executed. So we need to find the 6446 // loop that I is considered in relation to and prove that I is executed for 6447 // every iteration of that loop. That implies that the value that I 6448 // calculates does not wrap anywhere in the loop, so then we can apply the 6449 // flags to the SCEV. 6450 // 6451 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6452 // from different loops, so that we know which loop to prove that I is 6453 // executed in. 6454 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6455 // I could be an extractvalue from a call to an overflow intrinsic. 6456 // TODO: We can do better here in some cases. 6457 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6458 return false; 6459 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6460 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6461 bool AllOtherOpsLoopInvariant = true; 6462 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6463 ++OtherOpIndex) { 6464 if (OtherOpIndex != OpIndex) { 6465 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6466 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6467 AllOtherOpsLoopInvariant = false; 6468 break; 6469 } 6470 } 6471 } 6472 if (AllOtherOpsLoopInvariant && 6473 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6474 return true; 6475 } 6476 } 6477 return false; 6478 } 6479 6480 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6481 // If we know that \c I can never be poison period, then that's enough. 6482 if (isSCEVExprNeverPoison(I)) 6483 return true; 6484 6485 // For an add recurrence specifically, we assume that infinite loops without 6486 // side effects are undefined behavior, and then reason as follows: 6487 // 6488 // If the add recurrence is poison in any iteration, it is poison on all 6489 // future iterations (since incrementing poison yields poison). If the result 6490 // of the add recurrence is fed into the loop latch condition and the loop 6491 // does not contain any throws or exiting blocks other than the latch, we now 6492 // have the ability to "choose" whether the backedge is taken or not (by 6493 // choosing a sufficiently evil value for the poison feeding into the branch) 6494 // for every iteration including and after the one in which \p I first became 6495 // poison. There are two possibilities (let's call the iteration in which \p 6496 // I first became poison as K): 6497 // 6498 // 1. In the set of iterations including and after K, the loop body executes 6499 // no side effects. In this case executing the backege an infinte number 6500 // of times will yield undefined behavior. 6501 // 6502 // 2. In the set of iterations including and after K, the loop body executes 6503 // at least one side effect. In this case, that specific instance of side 6504 // effect is control dependent on poison, which also yields undefined 6505 // behavior. 6506 6507 auto *ExitingBB = L->getExitingBlock(); 6508 auto *LatchBB = L->getLoopLatch(); 6509 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6510 return false; 6511 6512 SmallPtrSet<const Instruction *, 16> Pushed; 6513 SmallVector<const Instruction *, 8> PoisonStack; 6514 6515 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6516 // things that are known to be poison under that assumption go on the 6517 // PoisonStack. 6518 Pushed.insert(I); 6519 PoisonStack.push_back(I); 6520 6521 bool LatchControlDependentOnPoison = false; 6522 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6523 const Instruction *Poison = PoisonStack.pop_back_val(); 6524 6525 for (auto *PoisonUser : Poison->users()) { 6526 if (propagatesPoison(cast<Operator>(PoisonUser))) { 6527 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6528 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6529 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6530 assert(BI->isConditional() && "Only possibility!"); 6531 if (BI->getParent() == LatchBB) { 6532 LatchControlDependentOnPoison = true; 6533 break; 6534 } 6535 } 6536 } 6537 } 6538 6539 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6540 } 6541 6542 ScalarEvolution::LoopProperties 6543 ScalarEvolution::getLoopProperties(const Loop *L) { 6544 using LoopProperties = ScalarEvolution::LoopProperties; 6545 6546 auto Itr = LoopPropertiesCache.find(L); 6547 if (Itr == LoopPropertiesCache.end()) { 6548 auto HasSideEffects = [](Instruction *I) { 6549 if (auto *SI = dyn_cast<StoreInst>(I)) 6550 return !SI->isSimple(); 6551 6552 return I->mayHaveSideEffects(); 6553 }; 6554 6555 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6556 /*HasNoSideEffects*/ true}; 6557 6558 for (auto *BB : L->getBlocks()) 6559 for (auto &I : *BB) { 6560 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6561 LP.HasNoAbnormalExits = false; 6562 if (HasSideEffects(&I)) 6563 LP.HasNoSideEffects = false; 6564 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6565 break; // We're already as pessimistic as we can get. 6566 } 6567 6568 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6569 assert(InsertPair.second && "We just checked!"); 6570 Itr = InsertPair.first; 6571 } 6572 6573 return Itr->second; 6574 } 6575 6576 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 6577 // TODO: Use the loop metadata form of mustprogress as well. 6578 if (!L->getHeader()->getParent()->mustProgress()) 6579 return false; 6580 6581 // A loop without side effects must be finite. 6582 // TODO: The check used here is very conservative. It's only *specific* 6583 // side effects which are well defined in infinite loops. 6584 return loopHasNoSideEffects(L); 6585 } 6586 6587 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6588 if (!isSCEVable(V->getType())) 6589 return getUnknown(V); 6590 6591 if (Instruction *I = dyn_cast<Instruction>(V)) { 6592 // Don't attempt to analyze instructions in blocks that aren't 6593 // reachable. Such instructions don't matter, and they aren't required 6594 // to obey basic rules for definitions dominating uses which this 6595 // analysis depends on. 6596 if (!DT.isReachableFromEntry(I->getParent())) 6597 return getUnknown(UndefValue::get(V->getType())); 6598 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6599 return getConstant(CI); 6600 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6601 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6602 else if (!isa<ConstantExpr>(V)) 6603 return getUnknown(V); 6604 6605 Operator *U = cast<Operator>(V); 6606 if (auto BO = MatchBinaryOp(U, DT)) { 6607 switch (BO->Opcode) { 6608 case Instruction::Add: { 6609 // The simple thing to do would be to just call getSCEV on both operands 6610 // and call getAddExpr with the result. However if we're looking at a 6611 // bunch of things all added together, this can be quite inefficient, 6612 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6613 // Instead, gather up all the operands and make a single getAddExpr call. 6614 // LLVM IR canonical form means we need only traverse the left operands. 6615 SmallVector<const SCEV *, 4> AddOps; 6616 do { 6617 if (BO->Op) { 6618 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6619 AddOps.push_back(OpSCEV); 6620 break; 6621 } 6622 6623 // If a NUW or NSW flag can be applied to the SCEV for this 6624 // addition, then compute the SCEV for this addition by itself 6625 // with a separate call to getAddExpr. We need to do that 6626 // instead of pushing the operands of the addition onto AddOps, 6627 // since the flags are only known to apply to this particular 6628 // addition - they may not apply to other additions that can be 6629 // formed with operands from AddOps. 6630 const SCEV *RHS = getSCEV(BO->RHS); 6631 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6632 if (Flags != SCEV::FlagAnyWrap) { 6633 const SCEV *LHS = getSCEV(BO->LHS); 6634 if (BO->Opcode == Instruction::Sub) 6635 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6636 else 6637 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6638 break; 6639 } 6640 } 6641 6642 if (BO->Opcode == Instruction::Sub) 6643 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6644 else 6645 AddOps.push_back(getSCEV(BO->RHS)); 6646 6647 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6648 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6649 NewBO->Opcode != Instruction::Sub)) { 6650 AddOps.push_back(getSCEV(BO->LHS)); 6651 break; 6652 } 6653 BO = NewBO; 6654 } while (true); 6655 6656 return getAddExpr(AddOps); 6657 } 6658 6659 case Instruction::Mul: { 6660 SmallVector<const SCEV *, 4> MulOps; 6661 do { 6662 if (BO->Op) { 6663 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6664 MulOps.push_back(OpSCEV); 6665 break; 6666 } 6667 6668 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6669 if (Flags != SCEV::FlagAnyWrap) { 6670 MulOps.push_back( 6671 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6672 break; 6673 } 6674 } 6675 6676 MulOps.push_back(getSCEV(BO->RHS)); 6677 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6678 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6679 MulOps.push_back(getSCEV(BO->LHS)); 6680 break; 6681 } 6682 BO = NewBO; 6683 } while (true); 6684 6685 return getMulExpr(MulOps); 6686 } 6687 case Instruction::UDiv: 6688 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6689 case Instruction::URem: 6690 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6691 case Instruction::Sub: { 6692 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6693 if (BO->Op) 6694 Flags = getNoWrapFlagsFromUB(BO->Op); 6695 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6696 } 6697 case Instruction::And: 6698 // For an expression like x&255 that merely masks off the high bits, 6699 // use zext(trunc(x)) as the SCEV expression. 6700 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6701 if (CI->isZero()) 6702 return getSCEV(BO->RHS); 6703 if (CI->isMinusOne()) 6704 return getSCEV(BO->LHS); 6705 const APInt &A = CI->getValue(); 6706 6707 // Instcombine's ShrinkDemandedConstant may strip bits out of 6708 // constants, obscuring what would otherwise be a low-bits mask. 6709 // Use computeKnownBits to compute what ShrinkDemandedConstant 6710 // knew about to reconstruct a low-bits mask value. 6711 unsigned LZ = A.countLeadingZeros(); 6712 unsigned TZ = A.countTrailingZeros(); 6713 unsigned BitWidth = A.getBitWidth(); 6714 KnownBits Known(BitWidth); 6715 computeKnownBits(BO->LHS, Known, getDataLayout(), 6716 0, &AC, nullptr, &DT); 6717 6718 APInt EffectiveMask = 6719 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6720 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6721 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6722 const SCEV *LHS = getSCEV(BO->LHS); 6723 const SCEV *ShiftedLHS = nullptr; 6724 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6725 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6726 // For an expression like (x * 8) & 8, simplify the multiply. 6727 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6728 unsigned GCD = std::min(MulZeros, TZ); 6729 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6730 SmallVector<const SCEV*, 4> MulOps; 6731 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6732 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6733 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6734 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6735 } 6736 } 6737 if (!ShiftedLHS) 6738 ShiftedLHS = getUDivExpr(LHS, MulCount); 6739 return getMulExpr( 6740 getZeroExtendExpr( 6741 getTruncateExpr(ShiftedLHS, 6742 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6743 BO->LHS->getType()), 6744 MulCount); 6745 } 6746 } 6747 break; 6748 6749 case Instruction::Or: 6750 // If the RHS of the Or is a constant, we may have something like: 6751 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6752 // optimizations will transparently handle this case. 6753 // 6754 // In order for this transformation to be safe, the LHS must be of the 6755 // form X*(2^n) and the Or constant must be less than 2^n. 6756 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6757 const SCEV *LHS = getSCEV(BO->LHS); 6758 const APInt &CIVal = CI->getValue(); 6759 if (GetMinTrailingZeros(LHS) >= 6760 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6761 // Build a plain add SCEV. 6762 return getAddExpr(LHS, getSCEV(CI), 6763 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6764 } 6765 } 6766 break; 6767 6768 case Instruction::Xor: 6769 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6770 // If the RHS of xor is -1, then this is a not operation. 6771 if (CI->isMinusOne()) 6772 return getNotSCEV(getSCEV(BO->LHS)); 6773 6774 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6775 // This is a variant of the check for xor with -1, and it handles 6776 // the case where instcombine has trimmed non-demanded bits out 6777 // of an xor with -1. 6778 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6779 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6780 if (LBO->getOpcode() == Instruction::And && 6781 LCI->getValue() == CI->getValue()) 6782 if (const SCEVZeroExtendExpr *Z = 6783 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6784 Type *UTy = BO->LHS->getType(); 6785 const SCEV *Z0 = Z->getOperand(); 6786 Type *Z0Ty = Z0->getType(); 6787 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6788 6789 // If C is a low-bits mask, the zero extend is serving to 6790 // mask off the high bits. Complement the operand and 6791 // re-apply the zext. 6792 if (CI->getValue().isMask(Z0TySize)) 6793 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6794 6795 // If C is a single bit, it may be in the sign-bit position 6796 // before the zero-extend. In this case, represent the xor 6797 // using an add, which is equivalent, and re-apply the zext. 6798 APInt Trunc = CI->getValue().trunc(Z0TySize); 6799 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6800 Trunc.isSignMask()) 6801 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6802 UTy); 6803 } 6804 } 6805 break; 6806 6807 case Instruction::Shl: 6808 // Turn shift left of a constant amount into a multiply. 6809 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6810 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6811 6812 // If the shift count is not less than the bitwidth, the result of 6813 // the shift is undefined. Don't try to analyze it, because the 6814 // resolution chosen here may differ from the resolution chosen in 6815 // other parts of the compiler. 6816 if (SA->getValue().uge(BitWidth)) 6817 break; 6818 6819 // We can safely preserve the nuw flag in all cases. It's also safe to 6820 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6821 // requires special handling. It can be preserved as long as we're not 6822 // left shifting by bitwidth - 1. 6823 auto Flags = SCEV::FlagAnyWrap; 6824 if (BO->Op) { 6825 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6826 if ((MulFlags & SCEV::FlagNSW) && 6827 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6828 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6829 if (MulFlags & SCEV::FlagNUW) 6830 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6831 } 6832 6833 Constant *X = ConstantInt::get( 6834 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6835 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6836 } 6837 break; 6838 6839 case Instruction::AShr: { 6840 // AShr X, C, where C is a constant. 6841 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6842 if (!CI) 6843 break; 6844 6845 Type *OuterTy = BO->LHS->getType(); 6846 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6847 // If the shift count is not less than the bitwidth, the result of 6848 // the shift is undefined. Don't try to analyze it, because the 6849 // resolution chosen here may differ from the resolution chosen in 6850 // other parts of the compiler. 6851 if (CI->getValue().uge(BitWidth)) 6852 break; 6853 6854 if (CI->isZero()) 6855 return getSCEV(BO->LHS); // shift by zero --> noop 6856 6857 uint64_t AShrAmt = CI->getZExtValue(); 6858 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6859 6860 Operator *L = dyn_cast<Operator>(BO->LHS); 6861 if (L && L->getOpcode() == Instruction::Shl) { 6862 // X = Shl A, n 6863 // Y = AShr X, m 6864 // Both n and m are constant. 6865 6866 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6867 if (L->getOperand(1) == BO->RHS) 6868 // For a two-shift sext-inreg, i.e. n = m, 6869 // use sext(trunc(x)) as the SCEV expression. 6870 return getSignExtendExpr( 6871 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6872 6873 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6874 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6875 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6876 if (ShlAmt > AShrAmt) { 6877 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6878 // expression. We already checked that ShlAmt < BitWidth, so 6879 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6880 // ShlAmt - AShrAmt < Amt. 6881 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6882 ShlAmt - AShrAmt); 6883 return getSignExtendExpr( 6884 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6885 getConstant(Mul)), OuterTy); 6886 } 6887 } 6888 } 6889 break; 6890 } 6891 } 6892 } 6893 6894 switch (U->getOpcode()) { 6895 case Instruction::Trunc: 6896 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6897 6898 case Instruction::ZExt: 6899 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6900 6901 case Instruction::SExt: 6902 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6903 // The NSW flag of a subtract does not always survive the conversion to 6904 // A + (-1)*B. By pushing sign extension onto its operands we are much 6905 // more likely to preserve NSW and allow later AddRec optimisations. 6906 // 6907 // NOTE: This is effectively duplicating this logic from getSignExtend: 6908 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6909 // but by that point the NSW information has potentially been lost. 6910 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6911 Type *Ty = U->getType(); 6912 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6913 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6914 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6915 } 6916 } 6917 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6918 6919 case Instruction::BitCast: 6920 // BitCasts are no-op casts so we just eliminate the cast. 6921 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6922 return getSCEV(U->getOperand(0)); 6923 break; 6924 6925 case Instruction::PtrToInt: { 6926 // Pointer to integer cast is straight-forward, so do model it. 6927 const SCEV *Op = getSCEV(U->getOperand(0)); 6928 Type *DstIntTy = U->getType(); 6929 // But only if effective SCEV (integer) type is wide enough to represent 6930 // all possible pointer values. 6931 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 6932 if (isa<SCEVCouldNotCompute>(IntOp)) 6933 return getUnknown(V); 6934 return IntOp; 6935 } 6936 case Instruction::IntToPtr: 6937 // Just don't deal with inttoptr casts. 6938 return getUnknown(V); 6939 6940 case Instruction::SDiv: 6941 // If both operands are non-negative, this is just an udiv. 6942 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6943 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6944 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6945 break; 6946 6947 case Instruction::SRem: 6948 // If both operands are non-negative, this is just an urem. 6949 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6950 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6951 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6952 break; 6953 6954 case Instruction::GetElementPtr: 6955 return createNodeForGEP(cast<GEPOperator>(U)); 6956 6957 case Instruction::PHI: 6958 return createNodeForPHI(cast<PHINode>(U)); 6959 6960 case Instruction::Select: 6961 // U can also be a select constant expr, which let fall through. Since 6962 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6963 // constant expressions cannot have instructions as operands, we'd have 6964 // returned getUnknown for a select constant expressions anyway. 6965 if (isa<Instruction>(U)) 6966 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6967 U->getOperand(1), U->getOperand(2)); 6968 break; 6969 6970 case Instruction::Call: 6971 case Instruction::Invoke: 6972 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6973 return getSCEV(RV); 6974 6975 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6976 switch (II->getIntrinsicID()) { 6977 case Intrinsic::abs: 6978 return getAbsExpr( 6979 getSCEV(II->getArgOperand(0)), 6980 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6981 case Intrinsic::umax: 6982 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6983 getSCEV(II->getArgOperand(1))); 6984 case Intrinsic::umin: 6985 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6986 getSCEV(II->getArgOperand(1))); 6987 case Intrinsic::smax: 6988 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6989 getSCEV(II->getArgOperand(1))); 6990 case Intrinsic::smin: 6991 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6992 getSCEV(II->getArgOperand(1))); 6993 case Intrinsic::usub_sat: { 6994 const SCEV *X = getSCEV(II->getArgOperand(0)); 6995 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6996 const SCEV *ClampedY = getUMinExpr(X, Y); 6997 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6998 } 6999 case Intrinsic::uadd_sat: { 7000 const SCEV *X = getSCEV(II->getArgOperand(0)); 7001 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7002 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7003 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7004 } 7005 case Intrinsic::start_loop_iterations: 7006 // A start_loop_iterations is just equivalent to the first operand for 7007 // SCEV purposes. 7008 return getSCEV(II->getArgOperand(0)); 7009 default: 7010 break; 7011 } 7012 } 7013 break; 7014 } 7015 7016 return getUnknown(V); 7017 } 7018 7019 //===----------------------------------------------------------------------===// 7020 // Iteration Count Computation Code 7021 // 7022 7023 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount) { 7024 // Get the trip count from the BE count by adding 1. Overflow, results 7025 // in zero which means "unknown". 7026 return getAddExpr(ExitCount, getOne(ExitCount->getType())); 7027 } 7028 7029 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7030 if (!ExitCount) 7031 return 0; 7032 7033 ConstantInt *ExitConst = ExitCount->getValue(); 7034 7035 // Guard against huge trip counts. 7036 if (ExitConst->getValue().getActiveBits() > 32) 7037 return 0; 7038 7039 // In case of integer overflow, this returns 0, which is correct. 7040 return ((unsigned)ExitConst->getZExtValue()) + 1; 7041 } 7042 7043 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7044 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7045 return getConstantTripCount(ExitCount); 7046 } 7047 7048 unsigned 7049 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7050 const BasicBlock *ExitingBlock) { 7051 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7052 assert(L->isLoopExiting(ExitingBlock) && 7053 "Exiting block must actually branch out of the loop!"); 7054 const SCEVConstant *ExitCount = 7055 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7056 return getConstantTripCount(ExitCount); 7057 } 7058 7059 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7060 const auto *MaxExitCount = 7061 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7062 return getConstantTripCount(MaxExitCount); 7063 } 7064 7065 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7066 SmallVector<BasicBlock *, 8> ExitingBlocks; 7067 L->getExitingBlocks(ExitingBlocks); 7068 7069 Optional<unsigned> Res = None; 7070 for (auto *ExitingBB : ExitingBlocks) { 7071 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7072 if (!Res) 7073 Res = Multiple; 7074 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7075 } 7076 return Res.getValueOr(1); 7077 } 7078 7079 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7080 const SCEV *ExitCount) { 7081 if (ExitCount == getCouldNotCompute()) 7082 return 1; 7083 7084 // Get the trip count 7085 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7086 7087 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7088 if (!TC) 7089 // Attempt to factor more general cases. Returns the greatest power of 7090 // two divisor. If overflow happens, the trip count expression is still 7091 // divisible by the greatest power of 2 divisor returned. 7092 return 1U << std::min((uint32_t)31, 7093 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7094 7095 ConstantInt *Result = TC->getValue(); 7096 7097 // Guard against huge trip counts (this requires checking 7098 // for zero to handle the case where the trip count == -1 and the 7099 // addition wraps). 7100 if (!Result || Result->getValue().getActiveBits() > 32 || 7101 Result->getValue().getActiveBits() == 0) 7102 return 1; 7103 7104 return (unsigned)Result->getZExtValue(); 7105 } 7106 7107 /// Returns the largest constant divisor of the trip count of this loop as a 7108 /// normal unsigned value, if possible. This means that the actual trip count is 7109 /// always a multiple of the returned value (don't forget the trip count could 7110 /// very well be zero as well!). 7111 /// 7112 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7113 /// multiple of a constant (which is also the case if the trip count is simply 7114 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7115 /// if the trip count is very large (>= 2^32). 7116 /// 7117 /// As explained in the comments for getSmallConstantTripCount, this assumes 7118 /// that control exits the loop via ExitingBlock. 7119 unsigned 7120 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7121 const BasicBlock *ExitingBlock) { 7122 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7123 assert(L->isLoopExiting(ExitingBlock) && 7124 "Exiting block must actually branch out of the loop!"); 7125 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7126 return getSmallConstantTripMultiple(L, ExitCount); 7127 } 7128 7129 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7130 const BasicBlock *ExitingBlock, 7131 ExitCountKind Kind) { 7132 switch (Kind) { 7133 case Exact: 7134 case SymbolicMaximum: 7135 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7136 case ConstantMaximum: 7137 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7138 }; 7139 llvm_unreachable("Invalid ExitCountKind!"); 7140 } 7141 7142 const SCEV * 7143 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7144 SCEVUnionPredicate &Preds) { 7145 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7146 } 7147 7148 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7149 ExitCountKind Kind) { 7150 switch (Kind) { 7151 case Exact: 7152 return getBackedgeTakenInfo(L).getExact(L, this); 7153 case ConstantMaximum: 7154 return getBackedgeTakenInfo(L).getConstantMax(this); 7155 case SymbolicMaximum: 7156 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7157 }; 7158 llvm_unreachable("Invalid ExitCountKind!"); 7159 } 7160 7161 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7162 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7163 } 7164 7165 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7166 static void 7167 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 7168 BasicBlock *Header = L->getHeader(); 7169 7170 // Push all Loop-header PHIs onto the Worklist stack. 7171 for (PHINode &PN : Header->phis()) 7172 Worklist.push_back(&PN); 7173 } 7174 7175 const ScalarEvolution::BackedgeTakenInfo & 7176 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7177 auto &BTI = getBackedgeTakenInfo(L); 7178 if (BTI.hasFullInfo()) 7179 return BTI; 7180 7181 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7182 7183 if (!Pair.second) 7184 return Pair.first->second; 7185 7186 BackedgeTakenInfo Result = 7187 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7188 7189 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7190 } 7191 7192 ScalarEvolution::BackedgeTakenInfo & 7193 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7194 // Initially insert an invalid entry for this loop. If the insertion 7195 // succeeds, proceed to actually compute a backedge-taken count and 7196 // update the value. The temporary CouldNotCompute value tells SCEV 7197 // code elsewhere that it shouldn't attempt to request a new 7198 // backedge-taken count, which could result in infinite recursion. 7199 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7200 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7201 if (!Pair.second) 7202 return Pair.first->second; 7203 7204 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7205 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7206 // must be cleared in this scope. 7207 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7208 7209 // In product build, there are no usage of statistic. 7210 (void)NumTripCountsComputed; 7211 (void)NumTripCountsNotComputed; 7212 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7213 const SCEV *BEExact = Result.getExact(L, this); 7214 if (BEExact != getCouldNotCompute()) { 7215 assert(isLoopInvariant(BEExact, L) && 7216 isLoopInvariant(Result.getConstantMax(this), L) && 7217 "Computed backedge-taken count isn't loop invariant for loop!"); 7218 ++NumTripCountsComputed; 7219 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7220 isa<PHINode>(L->getHeader()->begin())) { 7221 // Only count loops that have phi nodes as not being computable. 7222 ++NumTripCountsNotComputed; 7223 } 7224 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7225 7226 // Now that we know more about the trip count for this loop, forget any 7227 // existing SCEV values for PHI nodes in this loop since they are only 7228 // conservative estimates made without the benefit of trip count 7229 // information. This is similar to the code in forgetLoop, except that 7230 // it handles SCEVUnknown PHI nodes specially. 7231 if (Result.hasAnyInfo()) { 7232 SmallVector<Instruction *, 16> Worklist; 7233 PushLoopPHIs(L, Worklist); 7234 7235 SmallPtrSet<Instruction *, 8> Discovered; 7236 while (!Worklist.empty()) { 7237 Instruction *I = Worklist.pop_back_val(); 7238 7239 ValueExprMapType::iterator It = 7240 ValueExprMap.find_as(static_cast<Value *>(I)); 7241 if (It != ValueExprMap.end()) { 7242 const SCEV *Old = It->second; 7243 7244 // SCEVUnknown for a PHI either means that it has an unrecognized 7245 // structure, or it's a PHI that's in the progress of being computed 7246 // by createNodeForPHI. In the former case, additional loop trip 7247 // count information isn't going to change anything. In the later 7248 // case, createNodeForPHI will perform the necessary updates on its 7249 // own when it gets to that point. 7250 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 7251 eraseValueFromMap(It->first); 7252 forgetMemoizedResults(Old); 7253 } 7254 if (PHINode *PN = dyn_cast<PHINode>(I)) 7255 ConstantEvolutionLoopExitValue.erase(PN); 7256 } 7257 7258 // Since we don't need to invalidate anything for correctness and we're 7259 // only invalidating to make SCEV's results more precise, we get to stop 7260 // early to avoid invalidating too much. This is especially important in 7261 // cases like: 7262 // 7263 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 7264 // loop0: 7265 // %pn0 = phi 7266 // ... 7267 // loop1: 7268 // %pn1 = phi 7269 // ... 7270 // 7271 // where both loop0 and loop1's backedge taken count uses the SCEV 7272 // expression for %v. If we don't have the early stop below then in cases 7273 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 7274 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 7275 // count for loop1, effectively nullifying SCEV's trip count cache. 7276 for (auto *U : I->users()) 7277 if (auto *I = dyn_cast<Instruction>(U)) { 7278 auto *LoopForUser = LI.getLoopFor(I->getParent()); 7279 if (LoopForUser && L->contains(LoopForUser) && 7280 Discovered.insert(I).second) 7281 Worklist.push_back(I); 7282 } 7283 } 7284 } 7285 7286 // Re-lookup the insert position, since the call to 7287 // computeBackedgeTakenCount above could result in a 7288 // recusive call to getBackedgeTakenInfo (on a different 7289 // loop), which would invalidate the iterator computed 7290 // earlier. 7291 return BackedgeTakenCounts.find(L)->second = std::move(Result); 7292 } 7293 7294 void ScalarEvolution::forgetAllLoops() { 7295 // This method is intended to forget all info about loops. It should 7296 // invalidate caches as if the following happened: 7297 // - The trip counts of all loops have changed arbitrarily 7298 // - Every llvm::Value has been updated in place to produce a different 7299 // result. 7300 BackedgeTakenCounts.clear(); 7301 PredicatedBackedgeTakenCounts.clear(); 7302 LoopPropertiesCache.clear(); 7303 ConstantEvolutionLoopExitValue.clear(); 7304 ValueExprMap.clear(); 7305 ValuesAtScopes.clear(); 7306 LoopDispositions.clear(); 7307 BlockDispositions.clear(); 7308 UnsignedRanges.clear(); 7309 SignedRanges.clear(); 7310 ExprValueMap.clear(); 7311 HasRecMap.clear(); 7312 MinTrailingZerosCache.clear(); 7313 PredicatedSCEVRewrites.clear(); 7314 } 7315 7316 void ScalarEvolution::forgetLoop(const Loop *L) { 7317 SmallVector<const Loop *, 16> LoopWorklist(1, L); 7318 SmallVector<Instruction *, 32> Worklist; 7319 SmallPtrSet<Instruction *, 16> Visited; 7320 7321 // Iterate over all the loops and sub-loops to drop SCEV information. 7322 while (!LoopWorklist.empty()) { 7323 auto *CurrL = LoopWorklist.pop_back_val(); 7324 7325 // Drop any stored trip count value. 7326 BackedgeTakenCounts.erase(CurrL); 7327 PredicatedBackedgeTakenCounts.erase(CurrL); 7328 7329 // Drop information about predicated SCEV rewrites for this loop. 7330 for (auto I = PredicatedSCEVRewrites.begin(); 7331 I != PredicatedSCEVRewrites.end();) { 7332 std::pair<const SCEV *, const Loop *> Entry = I->first; 7333 if (Entry.second == CurrL) 7334 PredicatedSCEVRewrites.erase(I++); 7335 else 7336 ++I; 7337 } 7338 7339 auto LoopUsersItr = LoopUsers.find(CurrL); 7340 if (LoopUsersItr != LoopUsers.end()) { 7341 for (auto *S : LoopUsersItr->second) 7342 forgetMemoizedResults(S); 7343 LoopUsers.erase(LoopUsersItr); 7344 } 7345 7346 // Drop information about expressions based on loop-header PHIs. 7347 PushLoopPHIs(CurrL, Worklist); 7348 7349 while (!Worklist.empty()) { 7350 Instruction *I = Worklist.pop_back_val(); 7351 if (!Visited.insert(I).second) 7352 continue; 7353 7354 ValueExprMapType::iterator It = 7355 ValueExprMap.find_as(static_cast<Value *>(I)); 7356 if (It != ValueExprMap.end()) { 7357 eraseValueFromMap(It->first); 7358 forgetMemoizedResults(It->second); 7359 if (PHINode *PN = dyn_cast<PHINode>(I)) 7360 ConstantEvolutionLoopExitValue.erase(PN); 7361 } 7362 7363 PushDefUseChildren(I, Worklist); 7364 } 7365 7366 LoopPropertiesCache.erase(CurrL); 7367 // Forget all contained loops too, to avoid dangling entries in the 7368 // ValuesAtScopes map. 7369 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7370 } 7371 } 7372 7373 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7374 while (Loop *Parent = L->getParentLoop()) 7375 L = Parent; 7376 forgetLoop(L); 7377 } 7378 7379 void ScalarEvolution::forgetValue(Value *V) { 7380 Instruction *I = dyn_cast<Instruction>(V); 7381 if (!I) return; 7382 7383 // Drop information about expressions based on loop-header PHIs. 7384 SmallVector<Instruction *, 16> Worklist; 7385 Worklist.push_back(I); 7386 7387 SmallPtrSet<Instruction *, 8> Visited; 7388 while (!Worklist.empty()) { 7389 I = Worklist.pop_back_val(); 7390 if (!Visited.insert(I).second) 7391 continue; 7392 7393 ValueExprMapType::iterator It = 7394 ValueExprMap.find_as(static_cast<Value *>(I)); 7395 if (It != ValueExprMap.end()) { 7396 eraseValueFromMap(It->first); 7397 forgetMemoizedResults(It->second); 7398 if (PHINode *PN = dyn_cast<PHINode>(I)) 7399 ConstantEvolutionLoopExitValue.erase(PN); 7400 } 7401 7402 PushDefUseChildren(I, Worklist); 7403 } 7404 } 7405 7406 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7407 LoopDispositions.clear(); 7408 } 7409 7410 /// Get the exact loop backedge taken count considering all loop exits. A 7411 /// computable result can only be returned for loops with all exiting blocks 7412 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7413 /// is never skipped. This is a valid assumption as long as the loop exits via 7414 /// that test. For precise results, it is the caller's responsibility to specify 7415 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7416 const SCEV * 7417 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7418 SCEVUnionPredicate *Preds) const { 7419 // If any exits were not computable, the loop is not computable. 7420 if (!isComplete() || ExitNotTaken.empty()) 7421 return SE->getCouldNotCompute(); 7422 7423 const BasicBlock *Latch = L->getLoopLatch(); 7424 // All exiting blocks we have collected must dominate the only backedge. 7425 if (!Latch) 7426 return SE->getCouldNotCompute(); 7427 7428 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7429 // count is simply a minimum out of all these calculated exit counts. 7430 SmallVector<const SCEV *, 2> Ops; 7431 for (auto &ENT : ExitNotTaken) { 7432 const SCEV *BECount = ENT.ExactNotTaken; 7433 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7434 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7435 "We should only have known counts for exiting blocks that dominate " 7436 "latch!"); 7437 7438 Ops.push_back(BECount); 7439 7440 if (Preds && !ENT.hasAlwaysTruePredicate()) 7441 Preds->add(ENT.Predicate.get()); 7442 7443 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7444 "Predicate should be always true!"); 7445 } 7446 7447 return SE->getUMinFromMismatchedTypes(Ops); 7448 } 7449 7450 /// Get the exact not taken count for this loop exit. 7451 const SCEV * 7452 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7453 ScalarEvolution *SE) const { 7454 for (auto &ENT : ExitNotTaken) 7455 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7456 return ENT.ExactNotTaken; 7457 7458 return SE->getCouldNotCompute(); 7459 } 7460 7461 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7462 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7463 for (auto &ENT : ExitNotTaken) 7464 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7465 return ENT.MaxNotTaken; 7466 7467 return SE->getCouldNotCompute(); 7468 } 7469 7470 /// getConstantMax - Get the constant max backedge taken count for the loop. 7471 const SCEV * 7472 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7473 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7474 return !ENT.hasAlwaysTruePredicate(); 7475 }; 7476 7477 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7478 return SE->getCouldNotCompute(); 7479 7480 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7481 isa<SCEVConstant>(getConstantMax())) && 7482 "No point in having a non-constant max backedge taken count!"); 7483 return getConstantMax(); 7484 } 7485 7486 const SCEV * 7487 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7488 ScalarEvolution *SE) { 7489 if (!SymbolicMax) 7490 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7491 return SymbolicMax; 7492 } 7493 7494 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7495 ScalarEvolution *SE) const { 7496 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7497 return !ENT.hasAlwaysTruePredicate(); 7498 }; 7499 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7500 } 7501 7502 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S) const { 7503 return Operands.contains(S); 7504 } 7505 7506 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7507 : ExactNotTaken(E), MaxNotTaken(E) { 7508 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7509 isa<SCEVConstant>(MaxNotTaken)) && 7510 "No point in having a non-constant max backedge taken count!"); 7511 } 7512 7513 ScalarEvolution::ExitLimit::ExitLimit( 7514 const SCEV *E, const SCEV *M, bool MaxOrZero, 7515 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7516 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7517 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7518 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7519 "Exact is not allowed to be less precise than Max"); 7520 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7521 isa<SCEVConstant>(MaxNotTaken)) && 7522 "No point in having a non-constant max backedge taken count!"); 7523 for (auto *PredSet : PredSetList) 7524 for (auto *P : *PredSet) 7525 addPredicate(P); 7526 } 7527 7528 ScalarEvolution::ExitLimit::ExitLimit( 7529 const SCEV *E, const SCEV *M, bool MaxOrZero, 7530 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7531 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7532 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7533 isa<SCEVConstant>(MaxNotTaken)) && 7534 "No point in having a non-constant max backedge taken count!"); 7535 } 7536 7537 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7538 bool MaxOrZero) 7539 : ExitLimit(E, M, MaxOrZero, None) { 7540 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7541 isa<SCEVConstant>(MaxNotTaken)) && 7542 "No point in having a non-constant max backedge taken count!"); 7543 } 7544 7545 class SCEVRecordOperands { 7546 SmallPtrSetImpl<const SCEV *> &Operands; 7547 7548 public: 7549 SCEVRecordOperands(SmallPtrSetImpl<const SCEV *> &Operands) 7550 : Operands(Operands) {} 7551 bool follow(const SCEV *S) { 7552 Operands.insert(S); 7553 return true; 7554 } 7555 bool isDone() { return false; } 7556 }; 7557 7558 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7559 /// computable exit into a persistent ExitNotTakenInfo array. 7560 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7561 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7562 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7563 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7564 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7565 7566 ExitNotTaken.reserve(ExitCounts.size()); 7567 std::transform( 7568 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7569 [&](const EdgeExitInfo &EEI) { 7570 BasicBlock *ExitBB = EEI.first; 7571 const ExitLimit &EL = EEI.second; 7572 if (EL.Predicates.empty()) 7573 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7574 nullptr); 7575 7576 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7577 for (auto *Pred : EL.Predicates) 7578 Predicate->add(Pred); 7579 7580 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7581 std::move(Predicate)); 7582 }); 7583 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7584 isa<SCEVConstant>(ConstantMax)) && 7585 "No point in having a non-constant max backedge taken count!"); 7586 7587 SCEVRecordOperands RecordOperands(Operands); 7588 SCEVTraversal<SCEVRecordOperands> ST(RecordOperands); 7589 if (!isa<SCEVCouldNotCompute>(ConstantMax)) 7590 ST.visitAll(ConstantMax); 7591 for (auto &ENT : ExitNotTaken) 7592 if (!isa<SCEVCouldNotCompute>(ENT.ExactNotTaken)) 7593 ST.visitAll(ENT.ExactNotTaken); 7594 } 7595 7596 /// Compute the number of times the backedge of the specified loop will execute. 7597 ScalarEvolution::BackedgeTakenInfo 7598 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7599 bool AllowPredicates) { 7600 SmallVector<BasicBlock *, 8> ExitingBlocks; 7601 L->getExitingBlocks(ExitingBlocks); 7602 7603 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7604 7605 SmallVector<EdgeExitInfo, 4> ExitCounts; 7606 bool CouldComputeBECount = true; 7607 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7608 const SCEV *MustExitMaxBECount = nullptr; 7609 const SCEV *MayExitMaxBECount = nullptr; 7610 bool MustExitMaxOrZero = false; 7611 7612 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7613 // and compute maxBECount. 7614 // Do a union of all the predicates here. 7615 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7616 BasicBlock *ExitBB = ExitingBlocks[i]; 7617 7618 // We canonicalize untaken exits to br (constant), ignore them so that 7619 // proving an exit untaken doesn't negatively impact our ability to reason 7620 // about the loop as whole. 7621 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7622 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7623 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7624 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7625 continue; 7626 } 7627 7628 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7629 7630 assert((AllowPredicates || EL.Predicates.empty()) && 7631 "Predicated exit limit when predicates are not allowed!"); 7632 7633 // 1. For each exit that can be computed, add an entry to ExitCounts. 7634 // CouldComputeBECount is true only if all exits can be computed. 7635 if (EL.ExactNotTaken == getCouldNotCompute()) 7636 // We couldn't compute an exact value for this exit, so 7637 // we won't be able to compute an exact value for the loop. 7638 CouldComputeBECount = false; 7639 else 7640 ExitCounts.emplace_back(ExitBB, EL); 7641 7642 // 2. Derive the loop's MaxBECount from each exit's max number of 7643 // non-exiting iterations. Partition the loop exits into two kinds: 7644 // LoopMustExits and LoopMayExits. 7645 // 7646 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7647 // is a LoopMayExit. If any computable LoopMustExit is found, then 7648 // MaxBECount is the minimum EL.MaxNotTaken of computable 7649 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7650 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7651 // computable EL.MaxNotTaken. 7652 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7653 DT.dominates(ExitBB, Latch)) { 7654 if (!MustExitMaxBECount) { 7655 MustExitMaxBECount = EL.MaxNotTaken; 7656 MustExitMaxOrZero = EL.MaxOrZero; 7657 } else { 7658 MustExitMaxBECount = 7659 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7660 } 7661 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7662 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7663 MayExitMaxBECount = EL.MaxNotTaken; 7664 else { 7665 MayExitMaxBECount = 7666 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7667 } 7668 } 7669 } 7670 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7671 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7672 // The loop backedge will be taken the maximum or zero times if there's 7673 // a single exit that must be taken the maximum or zero times. 7674 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7675 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7676 MaxBECount, MaxOrZero); 7677 } 7678 7679 ScalarEvolution::ExitLimit 7680 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7681 bool AllowPredicates) { 7682 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7683 // If our exiting block does not dominate the latch, then its connection with 7684 // loop's exit limit may be far from trivial. 7685 const BasicBlock *Latch = L->getLoopLatch(); 7686 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7687 return getCouldNotCompute(); 7688 7689 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7690 Instruction *Term = ExitingBlock->getTerminator(); 7691 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7692 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7693 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7694 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7695 "It should have one successor in loop and one exit block!"); 7696 // Proceed to the next level to examine the exit condition expression. 7697 return computeExitLimitFromCond( 7698 L, BI->getCondition(), ExitIfTrue, 7699 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7700 } 7701 7702 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7703 // For switch, make sure that there is a single exit from the loop. 7704 BasicBlock *Exit = nullptr; 7705 for (auto *SBB : successors(ExitingBlock)) 7706 if (!L->contains(SBB)) { 7707 if (Exit) // Multiple exit successors. 7708 return getCouldNotCompute(); 7709 Exit = SBB; 7710 } 7711 assert(Exit && "Exiting block must have at least one exit"); 7712 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7713 /*ControlsExit=*/IsOnlyExit); 7714 } 7715 7716 return getCouldNotCompute(); 7717 } 7718 7719 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7720 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7721 bool ControlsExit, bool AllowPredicates) { 7722 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7723 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7724 ControlsExit, AllowPredicates); 7725 } 7726 7727 Optional<ScalarEvolution::ExitLimit> 7728 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7729 bool ExitIfTrue, bool ControlsExit, 7730 bool AllowPredicates) { 7731 (void)this->L; 7732 (void)this->ExitIfTrue; 7733 (void)this->AllowPredicates; 7734 7735 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7736 this->AllowPredicates == AllowPredicates && 7737 "Variance in assumed invariant key components!"); 7738 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7739 if (Itr == TripCountMap.end()) 7740 return None; 7741 return Itr->second; 7742 } 7743 7744 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7745 bool ExitIfTrue, 7746 bool ControlsExit, 7747 bool AllowPredicates, 7748 const ExitLimit &EL) { 7749 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7750 this->AllowPredicates == AllowPredicates && 7751 "Variance in assumed invariant key components!"); 7752 7753 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7754 assert(InsertResult.second && "Expected successful insertion!"); 7755 (void)InsertResult; 7756 (void)ExitIfTrue; 7757 } 7758 7759 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7760 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7761 bool ControlsExit, bool AllowPredicates) { 7762 7763 if (auto MaybeEL = 7764 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7765 return *MaybeEL; 7766 7767 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7768 ControlsExit, AllowPredicates); 7769 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7770 return EL; 7771 } 7772 7773 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7774 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7775 bool ControlsExit, bool AllowPredicates) { 7776 // Handle BinOp conditions (And, Or). 7777 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 7778 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7779 return *LimitFromBinOp; 7780 7781 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7782 // Proceed to the next level to examine the icmp. 7783 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7784 ExitLimit EL = 7785 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7786 if (EL.hasFullInfo() || !AllowPredicates) 7787 return EL; 7788 7789 // Try again, but use SCEV predicates this time. 7790 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7791 /*AllowPredicates=*/true); 7792 } 7793 7794 // Check for a constant condition. These are normally stripped out by 7795 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7796 // preserve the CFG and is temporarily leaving constant conditions 7797 // in place. 7798 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7799 if (ExitIfTrue == !CI->getZExtValue()) 7800 // The backedge is always taken. 7801 return getCouldNotCompute(); 7802 else 7803 // The backedge is never taken. 7804 return getZero(CI->getType()); 7805 } 7806 7807 // If it's not an integer or pointer comparison then compute it the hard way. 7808 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7809 } 7810 7811 Optional<ScalarEvolution::ExitLimit> 7812 ScalarEvolution::computeExitLimitFromCondFromBinOp( 7813 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7814 bool ControlsExit, bool AllowPredicates) { 7815 // Check if the controlling expression for this loop is an And or Or. 7816 Value *Op0, *Op1; 7817 bool IsAnd = false; 7818 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 7819 IsAnd = true; 7820 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 7821 IsAnd = false; 7822 else 7823 return None; 7824 7825 // EitherMayExit is true in these two cases: 7826 // br (and Op0 Op1), loop, exit 7827 // br (or Op0 Op1), exit, loop 7828 bool EitherMayExit = IsAnd ^ ExitIfTrue; 7829 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 7830 ControlsExit && !EitherMayExit, 7831 AllowPredicates); 7832 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 7833 ControlsExit && !EitherMayExit, 7834 AllowPredicates); 7835 7836 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 7837 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 7838 if (isa<ConstantInt>(Op1)) 7839 return Op1 == NeutralElement ? EL0 : EL1; 7840 if (isa<ConstantInt>(Op0)) 7841 return Op0 == NeutralElement ? EL1 : EL0; 7842 7843 const SCEV *BECount = getCouldNotCompute(); 7844 const SCEV *MaxBECount = getCouldNotCompute(); 7845 if (EitherMayExit) { 7846 // Both conditions must be same for the loop to continue executing. 7847 // Choose the less conservative count. 7848 // If ExitCond is a short-circuit form (select), using 7849 // umin(EL0.ExactNotTaken, EL1.ExactNotTaken) is unsafe in general. 7850 // To see the detailed examples, please see 7851 // test/Analysis/ScalarEvolution/exit-count-select.ll 7852 bool PoisonSafe = isa<BinaryOperator>(ExitCond); 7853 if (!PoisonSafe) 7854 // Even if ExitCond is select, we can safely derive BECount using both 7855 // EL0 and EL1 in these cases: 7856 // (1) EL0.ExactNotTaken is non-zero 7857 // (2) EL1.ExactNotTaken is non-poison 7858 // (3) EL0.ExactNotTaken is zero (BECount should be simply zero and 7859 // it cannot be umin(0, ..)) 7860 // The PoisonSafe assignment below is simplified and the assertion after 7861 // BECount calculation fully guarantees the condition (3). 7862 PoisonSafe = isa<SCEVConstant>(EL0.ExactNotTaken) || 7863 isa<SCEVConstant>(EL1.ExactNotTaken); 7864 if (EL0.ExactNotTaken != getCouldNotCompute() && 7865 EL1.ExactNotTaken != getCouldNotCompute() && PoisonSafe) { 7866 BECount = 7867 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7868 7869 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 7870 // it should have been simplified to zero (see the condition (3) above) 7871 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 7872 BECount->isZero()); 7873 } 7874 if (EL0.MaxNotTaken == getCouldNotCompute()) 7875 MaxBECount = EL1.MaxNotTaken; 7876 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7877 MaxBECount = EL0.MaxNotTaken; 7878 else 7879 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7880 } else { 7881 // Both conditions must be same at the same time for the loop to exit. 7882 // For now, be conservative. 7883 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7884 BECount = EL0.ExactNotTaken; 7885 } 7886 7887 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7888 // to be more aggressive when computing BECount than when computing 7889 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7890 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7891 // to not. 7892 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7893 !isa<SCEVCouldNotCompute>(BECount)) 7894 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7895 7896 return ExitLimit(BECount, MaxBECount, false, 7897 { &EL0.Predicates, &EL1.Predicates }); 7898 } 7899 7900 ScalarEvolution::ExitLimit 7901 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7902 ICmpInst *ExitCond, 7903 bool ExitIfTrue, 7904 bool ControlsExit, 7905 bool AllowPredicates) { 7906 // If the condition was exit on true, convert the condition to exit on false 7907 ICmpInst::Predicate Pred; 7908 if (!ExitIfTrue) 7909 Pred = ExitCond->getPredicate(); 7910 else 7911 Pred = ExitCond->getInversePredicate(); 7912 const ICmpInst::Predicate OriginalPred = Pred; 7913 7914 // Handle common loops like: for (X = "string"; *X; ++X) 7915 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7916 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7917 ExitLimit ItCnt = 7918 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7919 if (ItCnt.hasAnyInfo()) 7920 return ItCnt; 7921 } 7922 7923 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7924 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7925 7926 // Try to evaluate any dependencies out of the loop. 7927 LHS = getSCEVAtScope(LHS, L); 7928 RHS = getSCEVAtScope(RHS, L); 7929 7930 // At this point, we would like to compute how many iterations of the 7931 // loop the predicate will return true for these inputs. 7932 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7933 // If there is a loop-invariant, force it into the RHS. 7934 std::swap(LHS, RHS); 7935 Pred = ICmpInst::getSwappedPredicate(Pred); 7936 } 7937 7938 // Simplify the operands before analyzing them. 7939 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7940 7941 // If we have a comparison of a chrec against a constant, try to use value 7942 // ranges to answer this query. 7943 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7944 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7945 if (AddRec->getLoop() == L) { 7946 // Form the constant range. 7947 ConstantRange CompRange = 7948 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7949 7950 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7951 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7952 } 7953 7954 switch (Pred) { 7955 case ICmpInst::ICMP_NE: { // while (X != Y) 7956 // Convert to: while (X-Y != 0) 7957 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7958 AllowPredicates); 7959 if (EL.hasAnyInfo()) return EL; 7960 break; 7961 } 7962 case ICmpInst::ICMP_EQ: { // while (X == Y) 7963 // Convert to: while (X-Y == 0) 7964 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7965 if (EL.hasAnyInfo()) return EL; 7966 break; 7967 } 7968 case ICmpInst::ICMP_SLT: 7969 case ICmpInst::ICMP_ULT: { // while (X < Y) 7970 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7971 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7972 AllowPredicates); 7973 if (EL.hasAnyInfo()) return EL; 7974 break; 7975 } 7976 case ICmpInst::ICMP_SGT: 7977 case ICmpInst::ICMP_UGT: { // while (X > Y) 7978 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7979 ExitLimit EL = 7980 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7981 AllowPredicates); 7982 if (EL.hasAnyInfo()) return EL; 7983 break; 7984 } 7985 default: 7986 break; 7987 } 7988 7989 auto *ExhaustiveCount = 7990 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7991 7992 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7993 return ExhaustiveCount; 7994 7995 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7996 ExitCond->getOperand(1), L, OriginalPred); 7997 } 7998 7999 ScalarEvolution::ExitLimit 8000 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8001 SwitchInst *Switch, 8002 BasicBlock *ExitingBlock, 8003 bool ControlsExit) { 8004 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8005 8006 // Give up if the exit is the default dest of a switch. 8007 if (Switch->getDefaultDest() == ExitingBlock) 8008 return getCouldNotCompute(); 8009 8010 assert(L->contains(Switch->getDefaultDest()) && 8011 "Default case must not exit the loop!"); 8012 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8013 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8014 8015 // while (X != Y) --> while (X-Y != 0) 8016 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8017 if (EL.hasAnyInfo()) 8018 return EL; 8019 8020 return getCouldNotCompute(); 8021 } 8022 8023 static ConstantInt * 8024 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8025 ScalarEvolution &SE) { 8026 const SCEV *InVal = SE.getConstant(C); 8027 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8028 assert(isa<SCEVConstant>(Val) && 8029 "Evaluation of SCEV at constant didn't fold correctly?"); 8030 return cast<SCEVConstant>(Val)->getValue(); 8031 } 8032 8033 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 8034 /// compute the backedge execution count. 8035 ScalarEvolution::ExitLimit 8036 ScalarEvolution::computeLoadConstantCompareExitLimit( 8037 LoadInst *LI, 8038 Constant *RHS, 8039 const Loop *L, 8040 ICmpInst::Predicate predicate) { 8041 if (LI->isVolatile()) return getCouldNotCompute(); 8042 8043 // Check to see if the loaded pointer is a getelementptr of a global. 8044 // TODO: Use SCEV instead of manually grubbing with GEPs. 8045 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 8046 if (!GEP) return getCouldNotCompute(); 8047 8048 // Make sure that it is really a constant global we are gepping, with an 8049 // initializer, and make sure the first IDX is really 0. 8050 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 8051 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 8052 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 8053 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 8054 return getCouldNotCompute(); 8055 8056 // Okay, we allow one non-constant index into the GEP instruction. 8057 Value *VarIdx = nullptr; 8058 std::vector<Constant*> Indexes; 8059 unsigned VarIdxNum = 0; 8060 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 8061 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 8062 Indexes.push_back(CI); 8063 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 8064 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 8065 VarIdx = GEP->getOperand(i); 8066 VarIdxNum = i-2; 8067 Indexes.push_back(nullptr); 8068 } 8069 8070 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 8071 if (!VarIdx) 8072 return getCouldNotCompute(); 8073 8074 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 8075 // Check to see if X is a loop variant variable value now. 8076 const SCEV *Idx = getSCEV(VarIdx); 8077 Idx = getSCEVAtScope(Idx, L); 8078 8079 // We can only recognize very limited forms of loop index expressions, in 8080 // particular, only affine AddRec's like {C1,+,C2}<L>. 8081 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 8082 if (!IdxExpr || IdxExpr->getLoop() != L || !IdxExpr->isAffine() || 8083 isLoopInvariant(IdxExpr, L) || 8084 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 8085 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 8086 return getCouldNotCompute(); 8087 8088 unsigned MaxSteps = MaxBruteForceIterations; 8089 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 8090 ConstantInt *ItCst = ConstantInt::get( 8091 cast<IntegerType>(IdxExpr->getType()), IterationNum); 8092 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 8093 8094 // Form the GEP offset. 8095 Indexes[VarIdxNum] = Val; 8096 8097 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 8098 Indexes); 8099 if (!Result) break; // Cannot compute! 8100 8101 // Evaluate the condition for this iteration. 8102 Result = ConstantExpr::getICmp(predicate, Result, RHS); 8103 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 8104 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 8105 ++NumArrayLenItCounts; 8106 return getConstant(ItCst); // Found terminating iteration! 8107 } 8108 } 8109 return getCouldNotCompute(); 8110 } 8111 8112 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8113 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8114 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8115 if (!RHS) 8116 return getCouldNotCompute(); 8117 8118 const BasicBlock *Latch = L->getLoopLatch(); 8119 if (!Latch) 8120 return getCouldNotCompute(); 8121 8122 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8123 if (!Predecessor) 8124 return getCouldNotCompute(); 8125 8126 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8127 // Return LHS in OutLHS and shift_opt in OutOpCode. 8128 auto MatchPositiveShift = 8129 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8130 8131 using namespace PatternMatch; 8132 8133 ConstantInt *ShiftAmt; 8134 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8135 OutOpCode = Instruction::LShr; 8136 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8137 OutOpCode = Instruction::AShr; 8138 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8139 OutOpCode = Instruction::Shl; 8140 else 8141 return false; 8142 8143 return ShiftAmt->getValue().isStrictlyPositive(); 8144 }; 8145 8146 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8147 // 8148 // loop: 8149 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8150 // %iv.shifted = lshr i32 %iv, <positive constant> 8151 // 8152 // Return true on a successful match. Return the corresponding PHI node (%iv 8153 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8154 auto MatchShiftRecurrence = 8155 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8156 Optional<Instruction::BinaryOps> PostShiftOpCode; 8157 8158 { 8159 Instruction::BinaryOps OpC; 8160 Value *V; 8161 8162 // If we encounter a shift instruction, "peel off" the shift operation, 8163 // and remember that we did so. Later when we inspect %iv's backedge 8164 // value, we will make sure that the backedge value uses the same 8165 // operation. 8166 // 8167 // Note: the peeled shift operation does not have to be the same 8168 // instruction as the one feeding into the PHI's backedge value. We only 8169 // really care about it being the same *kind* of shift instruction -- 8170 // that's all that is required for our later inferences to hold. 8171 if (MatchPositiveShift(LHS, V, OpC)) { 8172 PostShiftOpCode = OpC; 8173 LHS = V; 8174 } 8175 } 8176 8177 PNOut = dyn_cast<PHINode>(LHS); 8178 if (!PNOut || PNOut->getParent() != L->getHeader()) 8179 return false; 8180 8181 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8182 Value *OpLHS; 8183 8184 return 8185 // The backedge value for the PHI node must be a shift by a positive 8186 // amount 8187 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8188 8189 // of the PHI node itself 8190 OpLHS == PNOut && 8191 8192 // and the kind of shift should be match the kind of shift we peeled 8193 // off, if any. 8194 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8195 }; 8196 8197 PHINode *PN; 8198 Instruction::BinaryOps OpCode; 8199 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8200 return getCouldNotCompute(); 8201 8202 const DataLayout &DL = getDataLayout(); 8203 8204 // The key rationale for this optimization is that for some kinds of shift 8205 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8206 // within a finite number of iterations. If the condition guarding the 8207 // backedge (in the sense that the backedge is taken if the condition is true) 8208 // is false for the value the shift recurrence stabilizes to, then we know 8209 // that the backedge is taken only a finite number of times. 8210 8211 ConstantInt *StableValue = nullptr; 8212 switch (OpCode) { 8213 default: 8214 llvm_unreachable("Impossible case!"); 8215 8216 case Instruction::AShr: { 8217 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8218 // bitwidth(K) iterations. 8219 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8220 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8221 Predecessor->getTerminator(), &DT); 8222 auto *Ty = cast<IntegerType>(RHS->getType()); 8223 if (Known.isNonNegative()) 8224 StableValue = ConstantInt::get(Ty, 0); 8225 else if (Known.isNegative()) 8226 StableValue = ConstantInt::get(Ty, -1, true); 8227 else 8228 return getCouldNotCompute(); 8229 8230 break; 8231 } 8232 case Instruction::LShr: 8233 case Instruction::Shl: 8234 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8235 // stabilize to 0 in at most bitwidth(K) iterations. 8236 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8237 break; 8238 } 8239 8240 auto *Result = 8241 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8242 assert(Result->getType()->isIntegerTy(1) && 8243 "Otherwise cannot be an operand to a branch instruction"); 8244 8245 if (Result->isZeroValue()) { 8246 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8247 const SCEV *UpperBound = 8248 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8249 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8250 } 8251 8252 return getCouldNotCompute(); 8253 } 8254 8255 /// Return true if we can constant fold an instruction of the specified type, 8256 /// assuming that all operands were constants. 8257 static bool CanConstantFold(const Instruction *I) { 8258 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8259 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8260 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8261 return true; 8262 8263 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8264 if (const Function *F = CI->getCalledFunction()) 8265 return canConstantFoldCallTo(CI, F); 8266 return false; 8267 } 8268 8269 /// Determine whether this instruction can constant evolve within this loop 8270 /// assuming its operands can all constant evolve. 8271 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8272 // An instruction outside of the loop can't be derived from a loop PHI. 8273 if (!L->contains(I)) return false; 8274 8275 if (isa<PHINode>(I)) { 8276 // We don't currently keep track of the control flow needed to evaluate 8277 // PHIs, so we cannot handle PHIs inside of loops. 8278 return L->getHeader() == I->getParent(); 8279 } 8280 8281 // If we won't be able to constant fold this expression even if the operands 8282 // are constants, bail early. 8283 return CanConstantFold(I); 8284 } 8285 8286 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8287 /// recursing through each instruction operand until reaching a loop header phi. 8288 static PHINode * 8289 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8290 DenseMap<Instruction *, PHINode *> &PHIMap, 8291 unsigned Depth) { 8292 if (Depth > MaxConstantEvolvingDepth) 8293 return nullptr; 8294 8295 // Otherwise, we can evaluate this instruction if all of its operands are 8296 // constant or derived from a PHI node themselves. 8297 PHINode *PHI = nullptr; 8298 for (Value *Op : UseInst->operands()) { 8299 if (isa<Constant>(Op)) continue; 8300 8301 Instruction *OpInst = dyn_cast<Instruction>(Op); 8302 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8303 8304 PHINode *P = dyn_cast<PHINode>(OpInst); 8305 if (!P) 8306 // If this operand is already visited, reuse the prior result. 8307 // We may have P != PHI if this is the deepest point at which the 8308 // inconsistent paths meet. 8309 P = PHIMap.lookup(OpInst); 8310 if (!P) { 8311 // Recurse and memoize the results, whether a phi is found or not. 8312 // This recursive call invalidates pointers into PHIMap. 8313 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8314 PHIMap[OpInst] = P; 8315 } 8316 if (!P) 8317 return nullptr; // Not evolving from PHI 8318 if (PHI && PHI != P) 8319 return nullptr; // Evolving from multiple different PHIs. 8320 PHI = P; 8321 } 8322 // This is a expression evolving from a constant PHI! 8323 return PHI; 8324 } 8325 8326 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 8327 /// in the loop that V is derived from. We allow arbitrary operations along the 8328 /// way, but the operands of an operation must either be constants or a value 8329 /// derived from a constant PHI. If this expression does not fit with these 8330 /// constraints, return null. 8331 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 8332 Instruction *I = dyn_cast<Instruction>(V); 8333 if (!I || !canConstantEvolve(I, L)) return nullptr; 8334 8335 if (PHINode *PN = dyn_cast<PHINode>(I)) 8336 return PN; 8337 8338 // Record non-constant instructions contained by the loop. 8339 DenseMap<Instruction *, PHINode *> PHIMap; 8340 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 8341 } 8342 8343 /// EvaluateExpression - Given an expression that passes the 8344 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 8345 /// in the loop has the value PHIVal. If we can't fold this expression for some 8346 /// reason, return null. 8347 static Constant *EvaluateExpression(Value *V, const Loop *L, 8348 DenseMap<Instruction *, Constant *> &Vals, 8349 const DataLayout &DL, 8350 const TargetLibraryInfo *TLI) { 8351 // Convenient constant check, but redundant for recursive calls. 8352 if (Constant *C = dyn_cast<Constant>(V)) return C; 8353 Instruction *I = dyn_cast<Instruction>(V); 8354 if (!I) return nullptr; 8355 8356 if (Constant *C = Vals.lookup(I)) return C; 8357 8358 // An instruction inside the loop depends on a value outside the loop that we 8359 // weren't given a mapping for, or a value such as a call inside the loop. 8360 if (!canConstantEvolve(I, L)) return nullptr; 8361 8362 // An unmapped PHI can be due to a branch or another loop inside this loop, 8363 // or due to this not being the initial iteration through a loop where we 8364 // couldn't compute the evolution of this particular PHI last time. 8365 if (isa<PHINode>(I)) return nullptr; 8366 8367 std::vector<Constant*> Operands(I->getNumOperands()); 8368 8369 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8370 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8371 if (!Operand) { 8372 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8373 if (!Operands[i]) return nullptr; 8374 continue; 8375 } 8376 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8377 Vals[Operand] = C; 8378 if (!C) return nullptr; 8379 Operands[i] = C; 8380 } 8381 8382 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8383 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8384 Operands[1], DL, TLI); 8385 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8386 if (!LI->isVolatile()) 8387 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8388 } 8389 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8390 } 8391 8392 8393 // If every incoming value to PN except the one for BB is a specific Constant, 8394 // return that, else return nullptr. 8395 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8396 Constant *IncomingVal = nullptr; 8397 8398 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8399 if (PN->getIncomingBlock(i) == BB) 8400 continue; 8401 8402 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8403 if (!CurrentVal) 8404 return nullptr; 8405 8406 if (IncomingVal != CurrentVal) { 8407 if (IncomingVal) 8408 return nullptr; 8409 IncomingVal = CurrentVal; 8410 } 8411 } 8412 8413 return IncomingVal; 8414 } 8415 8416 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8417 /// in the header of its containing loop, we know the loop executes a 8418 /// constant number of times, and the PHI node is just a recurrence 8419 /// involving constants, fold it. 8420 Constant * 8421 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8422 const APInt &BEs, 8423 const Loop *L) { 8424 auto I = ConstantEvolutionLoopExitValue.find(PN); 8425 if (I != ConstantEvolutionLoopExitValue.end()) 8426 return I->second; 8427 8428 if (BEs.ugt(MaxBruteForceIterations)) 8429 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8430 8431 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8432 8433 DenseMap<Instruction *, Constant *> CurrentIterVals; 8434 BasicBlock *Header = L->getHeader(); 8435 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8436 8437 BasicBlock *Latch = L->getLoopLatch(); 8438 if (!Latch) 8439 return nullptr; 8440 8441 for (PHINode &PHI : Header->phis()) { 8442 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8443 CurrentIterVals[&PHI] = StartCST; 8444 } 8445 if (!CurrentIterVals.count(PN)) 8446 return RetVal = nullptr; 8447 8448 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8449 8450 // Execute the loop symbolically to determine the exit value. 8451 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8452 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8453 8454 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8455 unsigned IterationNum = 0; 8456 const DataLayout &DL = getDataLayout(); 8457 for (; ; ++IterationNum) { 8458 if (IterationNum == NumIterations) 8459 return RetVal = CurrentIterVals[PN]; // Got exit value! 8460 8461 // Compute the value of the PHIs for the next iteration. 8462 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8463 DenseMap<Instruction *, Constant *> NextIterVals; 8464 Constant *NextPHI = 8465 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8466 if (!NextPHI) 8467 return nullptr; // Couldn't evaluate! 8468 NextIterVals[PN] = NextPHI; 8469 8470 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8471 8472 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8473 // cease to be able to evaluate one of them or if they stop evolving, 8474 // because that doesn't necessarily prevent us from computing PN. 8475 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8476 for (const auto &I : CurrentIterVals) { 8477 PHINode *PHI = dyn_cast<PHINode>(I.first); 8478 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8479 PHIsToCompute.emplace_back(PHI, I.second); 8480 } 8481 // We use two distinct loops because EvaluateExpression may invalidate any 8482 // iterators into CurrentIterVals. 8483 for (const auto &I : PHIsToCompute) { 8484 PHINode *PHI = I.first; 8485 Constant *&NextPHI = NextIterVals[PHI]; 8486 if (!NextPHI) { // Not already computed. 8487 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8488 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8489 } 8490 if (NextPHI != I.second) 8491 StoppedEvolving = false; 8492 } 8493 8494 // If all entries in CurrentIterVals == NextIterVals then we can stop 8495 // iterating, the loop can't continue to change. 8496 if (StoppedEvolving) 8497 return RetVal = CurrentIterVals[PN]; 8498 8499 CurrentIterVals.swap(NextIterVals); 8500 } 8501 } 8502 8503 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8504 Value *Cond, 8505 bool ExitWhen) { 8506 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8507 if (!PN) return getCouldNotCompute(); 8508 8509 // If the loop is canonicalized, the PHI will have exactly two entries. 8510 // That's the only form we support here. 8511 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8512 8513 DenseMap<Instruction *, Constant *> CurrentIterVals; 8514 BasicBlock *Header = L->getHeader(); 8515 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8516 8517 BasicBlock *Latch = L->getLoopLatch(); 8518 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8519 8520 for (PHINode &PHI : Header->phis()) { 8521 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8522 CurrentIterVals[&PHI] = StartCST; 8523 } 8524 if (!CurrentIterVals.count(PN)) 8525 return getCouldNotCompute(); 8526 8527 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8528 // the loop symbolically to determine when the condition gets a value of 8529 // "ExitWhen". 8530 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8531 const DataLayout &DL = getDataLayout(); 8532 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8533 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8534 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8535 8536 // Couldn't symbolically evaluate. 8537 if (!CondVal) return getCouldNotCompute(); 8538 8539 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8540 ++NumBruteForceTripCountsComputed; 8541 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8542 } 8543 8544 // Update all the PHI nodes for the next iteration. 8545 DenseMap<Instruction *, Constant *> NextIterVals; 8546 8547 // Create a list of which PHIs we need to compute. We want to do this before 8548 // calling EvaluateExpression on them because that may invalidate iterators 8549 // into CurrentIterVals. 8550 SmallVector<PHINode *, 8> PHIsToCompute; 8551 for (const auto &I : CurrentIterVals) { 8552 PHINode *PHI = dyn_cast<PHINode>(I.first); 8553 if (!PHI || PHI->getParent() != Header) continue; 8554 PHIsToCompute.push_back(PHI); 8555 } 8556 for (PHINode *PHI : PHIsToCompute) { 8557 Constant *&NextPHI = NextIterVals[PHI]; 8558 if (NextPHI) continue; // Already computed! 8559 8560 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8561 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8562 } 8563 CurrentIterVals.swap(NextIterVals); 8564 } 8565 8566 // Too many iterations were needed to evaluate. 8567 return getCouldNotCompute(); 8568 } 8569 8570 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8571 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8572 ValuesAtScopes[V]; 8573 // Check to see if we've folded this expression at this loop before. 8574 for (auto &LS : Values) 8575 if (LS.first == L) 8576 return LS.second ? LS.second : V; 8577 8578 Values.emplace_back(L, nullptr); 8579 8580 // Otherwise compute it. 8581 const SCEV *C = computeSCEVAtScope(V, L); 8582 for (auto &LS : reverse(ValuesAtScopes[V])) 8583 if (LS.first == L) { 8584 LS.second = C; 8585 break; 8586 } 8587 return C; 8588 } 8589 8590 /// This builds up a Constant using the ConstantExpr interface. That way, we 8591 /// will return Constants for objects which aren't represented by a 8592 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8593 /// Returns NULL if the SCEV isn't representable as a Constant. 8594 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8595 switch (V->getSCEVType()) { 8596 case scCouldNotCompute: 8597 case scAddRecExpr: 8598 return nullptr; 8599 case scConstant: 8600 return cast<SCEVConstant>(V)->getValue(); 8601 case scUnknown: 8602 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8603 case scSignExtend: { 8604 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8605 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8606 return ConstantExpr::getSExt(CastOp, SS->getType()); 8607 return nullptr; 8608 } 8609 case scZeroExtend: { 8610 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8611 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8612 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8613 return nullptr; 8614 } 8615 case scPtrToInt: { 8616 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8617 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8618 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8619 8620 return nullptr; 8621 } 8622 case scTruncate: { 8623 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8624 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8625 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8626 return nullptr; 8627 } 8628 case scAddExpr: { 8629 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8630 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8631 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8632 unsigned AS = PTy->getAddressSpace(); 8633 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8634 C = ConstantExpr::getBitCast(C, DestPtrTy); 8635 } 8636 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8637 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8638 if (!C2) 8639 return nullptr; 8640 8641 // First pointer! 8642 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8643 unsigned AS = C2->getType()->getPointerAddressSpace(); 8644 std::swap(C, C2); 8645 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8646 // The offsets have been converted to bytes. We can add bytes to an 8647 // i8* by GEP with the byte count in the first index. 8648 C = ConstantExpr::getBitCast(C, DestPtrTy); 8649 } 8650 8651 // Don't bother trying to sum two pointers. We probably can't 8652 // statically compute a load that results from it anyway. 8653 if (C2->getType()->isPointerTy()) 8654 return nullptr; 8655 8656 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8657 if (PTy->getElementType()->isStructTy()) 8658 C2 = ConstantExpr::getIntegerCast( 8659 C2, Type::getInt32Ty(C->getContext()), true); 8660 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8661 } else 8662 C = ConstantExpr::getAdd(C, C2); 8663 } 8664 return C; 8665 } 8666 return nullptr; 8667 } 8668 case scMulExpr: { 8669 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8670 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8671 // Don't bother with pointers at all. 8672 if (C->getType()->isPointerTy()) 8673 return nullptr; 8674 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8675 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8676 if (!C2 || C2->getType()->isPointerTy()) 8677 return nullptr; 8678 C = ConstantExpr::getMul(C, C2); 8679 } 8680 return C; 8681 } 8682 return nullptr; 8683 } 8684 case scUDivExpr: { 8685 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8686 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8687 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8688 if (LHS->getType() == RHS->getType()) 8689 return ConstantExpr::getUDiv(LHS, RHS); 8690 return nullptr; 8691 } 8692 case scSMaxExpr: 8693 case scUMaxExpr: 8694 case scSMinExpr: 8695 case scUMinExpr: 8696 return nullptr; // TODO: smax, umax, smin, umax. 8697 } 8698 llvm_unreachable("Unknown SCEV kind!"); 8699 } 8700 8701 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8702 if (isa<SCEVConstant>(V)) return V; 8703 8704 // If this instruction is evolved from a constant-evolving PHI, compute the 8705 // exit value from the loop without using SCEVs. 8706 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8707 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8708 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8709 const Loop *CurrLoop = this->LI[I->getParent()]; 8710 // Looking for loop exit value. 8711 if (CurrLoop && CurrLoop->getParentLoop() == L && 8712 PN->getParent() == CurrLoop->getHeader()) { 8713 // Okay, there is no closed form solution for the PHI node. Check 8714 // to see if the loop that contains it has a known backedge-taken 8715 // count. If so, we may be able to force computation of the exit 8716 // value. 8717 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8718 // This trivial case can show up in some degenerate cases where 8719 // the incoming IR has not yet been fully simplified. 8720 if (BackedgeTakenCount->isZero()) { 8721 Value *InitValue = nullptr; 8722 bool MultipleInitValues = false; 8723 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8724 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8725 if (!InitValue) 8726 InitValue = PN->getIncomingValue(i); 8727 else if (InitValue != PN->getIncomingValue(i)) { 8728 MultipleInitValues = true; 8729 break; 8730 } 8731 } 8732 } 8733 if (!MultipleInitValues && InitValue) 8734 return getSCEV(InitValue); 8735 } 8736 // Do we have a loop invariant value flowing around the backedge 8737 // for a loop which must execute the backedge? 8738 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8739 isKnownPositive(BackedgeTakenCount) && 8740 PN->getNumIncomingValues() == 2) { 8741 8742 unsigned InLoopPred = 8743 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8744 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8745 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8746 return getSCEV(BackedgeVal); 8747 } 8748 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8749 // Okay, we know how many times the containing loop executes. If 8750 // this is a constant evolving PHI node, get the final value at 8751 // the specified iteration number. 8752 Constant *RV = getConstantEvolutionLoopExitValue( 8753 PN, BTCC->getAPInt(), CurrLoop); 8754 if (RV) return getSCEV(RV); 8755 } 8756 } 8757 8758 // If there is a single-input Phi, evaluate it at our scope. If we can 8759 // prove that this replacement does not break LCSSA form, use new value. 8760 if (PN->getNumOperands() == 1) { 8761 const SCEV *Input = getSCEV(PN->getOperand(0)); 8762 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8763 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8764 // for the simplest case just support constants. 8765 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8766 } 8767 } 8768 8769 // Okay, this is an expression that we cannot symbolically evaluate 8770 // into a SCEV. Check to see if it's possible to symbolically evaluate 8771 // the arguments into constants, and if so, try to constant propagate the 8772 // result. This is particularly useful for computing loop exit values. 8773 if (CanConstantFold(I)) { 8774 SmallVector<Constant *, 4> Operands; 8775 bool MadeImprovement = false; 8776 for (Value *Op : I->operands()) { 8777 if (Constant *C = dyn_cast<Constant>(Op)) { 8778 Operands.push_back(C); 8779 continue; 8780 } 8781 8782 // If any of the operands is non-constant and if they are 8783 // non-integer and non-pointer, don't even try to analyze them 8784 // with scev techniques. 8785 if (!isSCEVable(Op->getType())) 8786 return V; 8787 8788 const SCEV *OrigV = getSCEV(Op); 8789 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8790 MadeImprovement |= OrigV != OpV; 8791 8792 Constant *C = BuildConstantFromSCEV(OpV); 8793 if (!C) return V; 8794 if (C->getType() != Op->getType()) 8795 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8796 Op->getType(), 8797 false), 8798 C, Op->getType()); 8799 Operands.push_back(C); 8800 } 8801 8802 // Check to see if getSCEVAtScope actually made an improvement. 8803 if (MadeImprovement) { 8804 Constant *C = nullptr; 8805 const DataLayout &DL = getDataLayout(); 8806 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8807 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8808 Operands[1], DL, &TLI); 8809 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8810 if (!Load->isVolatile()) 8811 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8812 DL); 8813 } else 8814 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8815 if (!C) return V; 8816 return getSCEV(C); 8817 } 8818 } 8819 } 8820 8821 // This is some other type of SCEVUnknown, just return it. 8822 return V; 8823 } 8824 8825 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8826 // Avoid performing the look-up in the common case where the specified 8827 // expression has no loop-variant portions. 8828 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8829 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8830 if (OpAtScope != Comm->getOperand(i)) { 8831 // Okay, at least one of these operands is loop variant but might be 8832 // foldable. Build a new instance of the folded commutative expression. 8833 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8834 Comm->op_begin()+i); 8835 NewOps.push_back(OpAtScope); 8836 8837 for (++i; i != e; ++i) { 8838 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8839 NewOps.push_back(OpAtScope); 8840 } 8841 if (isa<SCEVAddExpr>(Comm)) 8842 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8843 if (isa<SCEVMulExpr>(Comm)) 8844 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8845 if (isa<SCEVMinMaxExpr>(Comm)) 8846 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8847 llvm_unreachable("Unknown commutative SCEV type!"); 8848 } 8849 } 8850 // If we got here, all operands are loop invariant. 8851 return Comm; 8852 } 8853 8854 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8855 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8856 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8857 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8858 return Div; // must be loop invariant 8859 return getUDivExpr(LHS, RHS); 8860 } 8861 8862 // If this is a loop recurrence for a loop that does not contain L, then we 8863 // are dealing with the final value computed by the loop. 8864 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8865 // First, attempt to evaluate each operand. 8866 // Avoid performing the look-up in the common case where the specified 8867 // expression has no loop-variant portions. 8868 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8869 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8870 if (OpAtScope == AddRec->getOperand(i)) 8871 continue; 8872 8873 // Okay, at least one of these operands is loop variant but might be 8874 // foldable. Build a new instance of the folded commutative expression. 8875 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8876 AddRec->op_begin()+i); 8877 NewOps.push_back(OpAtScope); 8878 for (++i; i != e; ++i) 8879 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8880 8881 const SCEV *FoldedRec = 8882 getAddRecExpr(NewOps, AddRec->getLoop(), 8883 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8884 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8885 // The addrec may be folded to a nonrecurrence, for example, if the 8886 // induction variable is multiplied by zero after constant folding. Go 8887 // ahead and return the folded value. 8888 if (!AddRec) 8889 return FoldedRec; 8890 break; 8891 } 8892 8893 // If the scope is outside the addrec's loop, evaluate it by using the 8894 // loop exit value of the addrec. 8895 if (!AddRec->getLoop()->contains(L)) { 8896 // To evaluate this recurrence, we need to know how many times the AddRec 8897 // loop iterates. Compute this now. 8898 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8899 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8900 8901 // Then, evaluate the AddRec. 8902 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8903 } 8904 8905 return AddRec; 8906 } 8907 8908 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8909 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8910 if (Op == Cast->getOperand()) 8911 return Cast; // must be loop invariant 8912 return getZeroExtendExpr(Op, Cast->getType()); 8913 } 8914 8915 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8916 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8917 if (Op == Cast->getOperand()) 8918 return Cast; // must be loop invariant 8919 return getSignExtendExpr(Op, Cast->getType()); 8920 } 8921 8922 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8923 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8924 if (Op == Cast->getOperand()) 8925 return Cast; // must be loop invariant 8926 return getTruncateExpr(Op, Cast->getType()); 8927 } 8928 8929 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 8930 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8931 if (Op == Cast->getOperand()) 8932 return Cast; // must be loop invariant 8933 return getPtrToIntExpr(Op, Cast->getType()); 8934 } 8935 8936 llvm_unreachable("Unknown SCEV type!"); 8937 } 8938 8939 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8940 return getSCEVAtScope(getSCEV(V), L); 8941 } 8942 8943 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8944 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8945 return stripInjectiveFunctions(ZExt->getOperand()); 8946 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8947 return stripInjectiveFunctions(SExt->getOperand()); 8948 return S; 8949 } 8950 8951 /// Finds the minimum unsigned root of the following equation: 8952 /// 8953 /// A * X = B (mod N) 8954 /// 8955 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8956 /// A and B isn't important. 8957 /// 8958 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8959 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8960 ScalarEvolution &SE) { 8961 uint32_t BW = A.getBitWidth(); 8962 assert(BW == SE.getTypeSizeInBits(B->getType())); 8963 assert(A != 0 && "A must be non-zero."); 8964 8965 // 1. D = gcd(A, N) 8966 // 8967 // The gcd of A and N may have only one prime factor: 2. The number of 8968 // trailing zeros in A is its multiplicity 8969 uint32_t Mult2 = A.countTrailingZeros(); 8970 // D = 2^Mult2 8971 8972 // 2. Check if B is divisible by D. 8973 // 8974 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8975 // is not less than multiplicity of this prime factor for D. 8976 if (SE.GetMinTrailingZeros(B) < Mult2) 8977 return SE.getCouldNotCompute(); 8978 8979 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8980 // modulo (N / D). 8981 // 8982 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8983 // (N / D) in general. The inverse itself always fits into BW bits, though, 8984 // so we immediately truncate it. 8985 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8986 APInt Mod(BW + 1, 0); 8987 Mod.setBit(BW - Mult2); // Mod = N / D 8988 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8989 8990 // 4. Compute the minimum unsigned root of the equation: 8991 // I * (B / D) mod (N / D) 8992 // To simplify the computation, we factor out the divide by D: 8993 // (I * B mod N) / D 8994 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8995 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8996 } 8997 8998 /// For a given quadratic addrec, generate coefficients of the corresponding 8999 /// quadratic equation, multiplied by a common value to ensure that they are 9000 /// integers. 9001 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9002 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9003 /// were multiplied by, and BitWidth is the bit width of the original addrec 9004 /// coefficients. 9005 /// This function returns None if the addrec coefficients are not compile- 9006 /// time constants. 9007 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9008 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9009 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9010 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9011 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9012 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9013 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9014 << *AddRec << '\n'); 9015 9016 // We currently can only solve this if the coefficients are constants. 9017 if (!LC || !MC || !NC) { 9018 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9019 return None; 9020 } 9021 9022 APInt L = LC->getAPInt(); 9023 APInt M = MC->getAPInt(); 9024 APInt N = NC->getAPInt(); 9025 assert(!N.isNullValue() && "This is not a quadratic addrec"); 9026 9027 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9028 unsigned NewWidth = BitWidth + 1; 9029 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9030 << BitWidth << '\n'); 9031 // The sign-extension (as opposed to a zero-extension) here matches the 9032 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9033 N = N.sext(NewWidth); 9034 M = M.sext(NewWidth); 9035 L = L.sext(NewWidth); 9036 9037 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9038 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9039 // L+M, L+2M+N, L+3M+3N, ... 9040 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9041 // 9042 // The equation Acc = 0 is then 9043 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9044 // In a quadratic form it becomes: 9045 // N n^2 + (2M-N) n + 2L = 0. 9046 9047 APInt A = N; 9048 APInt B = 2 * M - A; 9049 APInt C = 2 * L; 9050 APInt T = APInt(NewWidth, 2); 9051 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9052 << "x + " << C << ", coeff bw: " << NewWidth 9053 << ", multiplied by " << T << '\n'); 9054 return std::make_tuple(A, B, C, T, BitWidth); 9055 } 9056 9057 /// Helper function to compare optional APInts: 9058 /// (a) if X and Y both exist, return min(X, Y), 9059 /// (b) if neither X nor Y exist, return None, 9060 /// (c) if exactly one of X and Y exists, return that value. 9061 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9062 if (X.hasValue() && Y.hasValue()) { 9063 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9064 APInt XW = X->sextOrSelf(W); 9065 APInt YW = Y->sextOrSelf(W); 9066 return XW.slt(YW) ? *X : *Y; 9067 } 9068 if (!X.hasValue() && !Y.hasValue()) 9069 return None; 9070 return X.hasValue() ? *X : *Y; 9071 } 9072 9073 /// Helper function to truncate an optional APInt to a given BitWidth. 9074 /// When solving addrec-related equations, it is preferable to return a value 9075 /// that has the same bit width as the original addrec's coefficients. If the 9076 /// solution fits in the original bit width, truncate it (except for i1). 9077 /// Returning a value of a different bit width may inhibit some optimizations. 9078 /// 9079 /// In general, a solution to a quadratic equation generated from an addrec 9080 /// may require BW+1 bits, where BW is the bit width of the addrec's 9081 /// coefficients. The reason is that the coefficients of the quadratic 9082 /// equation are BW+1 bits wide (to avoid truncation when converting from 9083 /// the addrec to the equation). 9084 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9085 if (!X.hasValue()) 9086 return None; 9087 unsigned W = X->getBitWidth(); 9088 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9089 return X->trunc(BitWidth); 9090 return X; 9091 } 9092 9093 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9094 /// iterations. The values L, M, N are assumed to be signed, and they 9095 /// should all have the same bit widths. 9096 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9097 /// where BW is the bit width of the addrec's coefficients. 9098 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9099 /// returned as such, otherwise the bit width of the returned value may 9100 /// be greater than BW. 9101 /// 9102 /// This function returns None if 9103 /// (a) the addrec coefficients are not constant, or 9104 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9105 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9106 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9107 static Optional<APInt> 9108 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9109 APInt A, B, C, M; 9110 unsigned BitWidth; 9111 auto T = GetQuadraticEquation(AddRec); 9112 if (!T.hasValue()) 9113 return None; 9114 9115 std::tie(A, B, C, M, BitWidth) = *T; 9116 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9117 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9118 if (!X.hasValue()) 9119 return None; 9120 9121 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9122 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9123 if (!V->isZero()) 9124 return None; 9125 9126 return TruncIfPossible(X, BitWidth); 9127 } 9128 9129 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9130 /// iterations. The values M, N are assumed to be signed, and they 9131 /// should all have the same bit widths. 9132 /// Find the least n such that c(n) does not belong to the given range, 9133 /// while c(n-1) does. 9134 /// 9135 /// This function returns None if 9136 /// (a) the addrec coefficients are not constant, or 9137 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9138 /// bounds of the range. 9139 static Optional<APInt> 9140 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9141 const ConstantRange &Range, ScalarEvolution &SE) { 9142 assert(AddRec->getOperand(0)->isZero() && 9143 "Starting value of addrec should be 0"); 9144 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9145 << Range << ", addrec " << *AddRec << '\n'); 9146 // This case is handled in getNumIterationsInRange. Here we can assume that 9147 // we start in the range. 9148 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9149 "Addrec's initial value should be in range"); 9150 9151 APInt A, B, C, M; 9152 unsigned BitWidth; 9153 auto T = GetQuadraticEquation(AddRec); 9154 if (!T.hasValue()) 9155 return None; 9156 9157 // Be careful about the return value: there can be two reasons for not 9158 // returning an actual number. First, if no solutions to the equations 9159 // were found, and second, if the solutions don't leave the given range. 9160 // The first case means that the actual solution is "unknown", the second 9161 // means that it's known, but not valid. If the solution is unknown, we 9162 // cannot make any conclusions. 9163 // Return a pair: the optional solution and a flag indicating if the 9164 // solution was found. 9165 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9166 // Solve for signed overflow and unsigned overflow, pick the lower 9167 // solution. 9168 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9169 << Bound << " (before multiplying by " << M << ")\n"); 9170 Bound *= M; // The quadratic equation multiplier. 9171 9172 Optional<APInt> SO = None; 9173 if (BitWidth > 1) { 9174 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9175 "signed overflow\n"); 9176 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9177 } 9178 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9179 "unsigned overflow\n"); 9180 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9181 BitWidth+1); 9182 9183 auto LeavesRange = [&] (const APInt &X) { 9184 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9185 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9186 if (Range.contains(V0->getValue())) 9187 return false; 9188 // X should be at least 1, so X-1 is non-negative. 9189 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9190 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9191 if (Range.contains(V1->getValue())) 9192 return true; 9193 return false; 9194 }; 9195 9196 // If SolveQuadraticEquationWrap returns None, it means that there can 9197 // be a solution, but the function failed to find it. We cannot treat it 9198 // as "no solution". 9199 if (!SO.hasValue() || !UO.hasValue()) 9200 return { None, false }; 9201 9202 // Check the smaller value first to see if it leaves the range. 9203 // At this point, both SO and UO must have values. 9204 Optional<APInt> Min = MinOptional(SO, UO); 9205 if (LeavesRange(*Min)) 9206 return { Min, true }; 9207 Optional<APInt> Max = Min == SO ? UO : SO; 9208 if (LeavesRange(*Max)) 9209 return { Max, true }; 9210 9211 // Solutions were found, but were eliminated, hence the "true". 9212 return { None, true }; 9213 }; 9214 9215 std::tie(A, B, C, M, BitWidth) = *T; 9216 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9217 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9218 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9219 auto SL = SolveForBoundary(Lower); 9220 auto SU = SolveForBoundary(Upper); 9221 // If any of the solutions was unknown, no meaninigful conclusions can 9222 // be made. 9223 if (!SL.second || !SU.second) 9224 return None; 9225 9226 // Claim: The correct solution is not some value between Min and Max. 9227 // 9228 // Justification: Assuming that Min and Max are different values, one of 9229 // them is when the first signed overflow happens, the other is when the 9230 // first unsigned overflow happens. Crossing the range boundary is only 9231 // possible via an overflow (treating 0 as a special case of it, modeling 9232 // an overflow as crossing k*2^W for some k). 9233 // 9234 // The interesting case here is when Min was eliminated as an invalid 9235 // solution, but Max was not. The argument is that if there was another 9236 // overflow between Min and Max, it would also have been eliminated if 9237 // it was considered. 9238 // 9239 // For a given boundary, it is possible to have two overflows of the same 9240 // type (signed/unsigned) without having the other type in between: this 9241 // can happen when the vertex of the parabola is between the iterations 9242 // corresponding to the overflows. This is only possible when the two 9243 // overflows cross k*2^W for the same k. In such case, if the second one 9244 // left the range (and was the first one to do so), the first overflow 9245 // would have to enter the range, which would mean that either we had left 9246 // the range before or that we started outside of it. Both of these cases 9247 // are contradictions. 9248 // 9249 // Claim: In the case where SolveForBoundary returns None, the correct 9250 // solution is not some value between the Max for this boundary and the 9251 // Min of the other boundary. 9252 // 9253 // Justification: Assume that we had such Max_A and Min_B corresponding 9254 // to range boundaries A and B and such that Max_A < Min_B. If there was 9255 // a solution between Max_A and Min_B, it would have to be caused by an 9256 // overflow corresponding to either A or B. It cannot correspond to B, 9257 // since Min_B is the first occurrence of such an overflow. If it 9258 // corresponded to A, it would have to be either a signed or an unsigned 9259 // overflow that is larger than both eliminated overflows for A. But 9260 // between the eliminated overflows and this overflow, the values would 9261 // cover the entire value space, thus crossing the other boundary, which 9262 // is a contradiction. 9263 9264 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9265 } 9266 9267 ScalarEvolution::ExitLimit 9268 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9269 bool AllowPredicates) { 9270 9271 // This is only used for loops with a "x != y" exit test. The exit condition 9272 // is now expressed as a single expression, V = x-y. So the exit test is 9273 // effectively V != 0. We know and take advantage of the fact that this 9274 // expression only being used in a comparison by zero context. 9275 9276 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9277 // If the value is a constant 9278 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9279 // If the value is already zero, the branch will execute zero times. 9280 if (C->getValue()->isZero()) return C; 9281 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9282 } 9283 9284 const SCEVAddRecExpr *AddRec = 9285 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9286 9287 if (!AddRec && AllowPredicates) 9288 // Try to make this an AddRec using runtime tests, in the first X 9289 // iterations of this loop, where X is the SCEV expression found by the 9290 // algorithm below. 9291 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9292 9293 if (!AddRec || AddRec->getLoop() != L) 9294 return getCouldNotCompute(); 9295 9296 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9297 // the quadratic equation to solve it. 9298 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9299 // We can only use this value if the chrec ends up with an exact zero 9300 // value at this index. When solving for "X*X != 5", for example, we 9301 // should not accept a root of 2. 9302 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9303 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9304 return ExitLimit(R, R, false, Predicates); 9305 } 9306 return getCouldNotCompute(); 9307 } 9308 9309 // Otherwise we can only handle this if it is affine. 9310 if (!AddRec->isAffine()) 9311 return getCouldNotCompute(); 9312 9313 // If this is an affine expression, the execution count of this branch is 9314 // the minimum unsigned root of the following equation: 9315 // 9316 // Start + Step*N = 0 (mod 2^BW) 9317 // 9318 // equivalent to: 9319 // 9320 // Step*N = -Start (mod 2^BW) 9321 // 9322 // where BW is the common bit width of Start and Step. 9323 9324 // Get the initial value for the loop. 9325 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9326 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9327 9328 // For now we handle only constant steps. 9329 // 9330 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9331 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9332 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 9333 // We have not yet seen any such cases. 9334 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 9335 if (!StepC || StepC->getValue()->isZero()) 9336 return getCouldNotCompute(); 9337 9338 // For positive steps (counting up until unsigned overflow): 9339 // N = -Start/Step (as unsigned) 9340 // For negative steps (counting down to zero): 9341 // N = Start/-Step 9342 // First compute the unsigned distance from zero in the direction of Step. 9343 bool CountDown = StepC->getAPInt().isNegative(); 9344 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 9345 9346 // Handle unitary steps, which cannot wraparound. 9347 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 9348 // N = Distance (as unsigned) 9349 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 9350 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 9351 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 9352 if (MaxBECountBase.ult(MaxBECount)) 9353 MaxBECount = MaxBECountBase; 9354 9355 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9356 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9357 // case, and see if we can improve the bound. 9358 // 9359 // Explicitly handling this here is necessary because getUnsignedRange 9360 // isn't context-sensitive; it doesn't know that we only care about the 9361 // range inside the loop. 9362 const SCEV *Zero = getZero(Distance->getType()); 9363 const SCEV *One = getOne(Distance->getType()); 9364 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9365 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9366 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9367 // as "unsigned_max(Distance + 1) - 1". 9368 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9369 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9370 } 9371 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9372 } 9373 9374 // If the condition controls loop exit (the loop exits only if the expression 9375 // is true) and the addition is no-wrap we can use unsigned divide to 9376 // compute the backedge count. In this case, the step may not divide the 9377 // distance, but we don't care because if the condition is "missed" the loop 9378 // will have undefined behavior due to wrapping. 9379 if (ControlsExit && AddRec->hasNoSelfWrap() && 9380 loopHasNoAbnormalExits(AddRec->getLoop())) { 9381 const SCEV *Exact = 9382 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9383 const SCEV *Max = getCouldNotCompute(); 9384 if (Exact != getCouldNotCompute()) { 9385 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 9386 APInt BaseMaxInt = getUnsignedRangeMax(Exact); 9387 if (BaseMaxInt.ult(MaxInt)) 9388 Max = getConstant(BaseMaxInt); 9389 else 9390 Max = getConstant(MaxInt); 9391 } 9392 return ExitLimit(Exact, Max, false, Predicates); 9393 } 9394 9395 // Solve the general equation. 9396 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9397 getNegativeSCEV(Start), *this); 9398 const SCEV *M = E == getCouldNotCompute() 9399 ? E 9400 : getConstant(getUnsignedRangeMax(E)); 9401 return ExitLimit(E, M, false, Predicates); 9402 } 9403 9404 ScalarEvolution::ExitLimit 9405 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9406 // Loops that look like: while (X == 0) are very strange indeed. We don't 9407 // handle them yet except for the trivial case. This could be expanded in the 9408 // future as needed. 9409 9410 // If the value is a constant, check to see if it is known to be non-zero 9411 // already. If so, the backedge will execute zero times. 9412 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9413 if (!C->getValue()->isZero()) 9414 return getZero(C->getType()); 9415 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9416 } 9417 9418 // We could implement others, but I really doubt anyone writes loops like 9419 // this, and if they did, they would already be constant folded. 9420 return getCouldNotCompute(); 9421 } 9422 9423 std::pair<const BasicBlock *, const BasicBlock *> 9424 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9425 const { 9426 // If the block has a unique predecessor, then there is no path from the 9427 // predecessor to the block that does not go through the direct edge 9428 // from the predecessor to the block. 9429 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9430 return {Pred, BB}; 9431 9432 // A loop's header is defined to be a block that dominates the loop. 9433 // If the header has a unique predecessor outside the loop, it must be 9434 // a block that has exactly one successor that can reach the loop. 9435 if (const Loop *L = LI.getLoopFor(BB)) 9436 return {L->getLoopPredecessor(), L->getHeader()}; 9437 9438 return {nullptr, nullptr}; 9439 } 9440 9441 /// SCEV structural equivalence is usually sufficient for testing whether two 9442 /// expressions are equal, however for the purposes of looking for a condition 9443 /// guarding a loop, it can be useful to be a little more general, since a 9444 /// front-end may have replicated the controlling expression. 9445 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9446 // Quick check to see if they are the same SCEV. 9447 if (A == B) return true; 9448 9449 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9450 // Not all instructions that are "identical" compute the same value. For 9451 // instance, two distinct alloca instructions allocating the same type are 9452 // identical and do not read memory; but compute distinct values. 9453 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9454 }; 9455 9456 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9457 // two different instructions with the same value. Check for this case. 9458 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9459 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9460 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9461 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9462 if (ComputesEqualValues(AI, BI)) 9463 return true; 9464 9465 // Otherwise assume they may have a different value. 9466 return false; 9467 } 9468 9469 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9470 const SCEV *&LHS, const SCEV *&RHS, 9471 unsigned Depth) { 9472 bool Changed = false; 9473 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9474 // '0 != 0'. 9475 auto TrivialCase = [&](bool TriviallyTrue) { 9476 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9477 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9478 return true; 9479 }; 9480 // If we hit the max recursion limit bail out. 9481 if (Depth >= 3) 9482 return false; 9483 9484 // Canonicalize a constant to the right side. 9485 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9486 // Check for both operands constant. 9487 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9488 if (ConstantExpr::getICmp(Pred, 9489 LHSC->getValue(), 9490 RHSC->getValue())->isNullValue()) 9491 return TrivialCase(false); 9492 else 9493 return TrivialCase(true); 9494 } 9495 // Otherwise swap the operands to put the constant on the right. 9496 std::swap(LHS, RHS); 9497 Pred = ICmpInst::getSwappedPredicate(Pred); 9498 Changed = true; 9499 } 9500 9501 // If we're comparing an addrec with a value which is loop-invariant in the 9502 // addrec's loop, put the addrec on the left. Also make a dominance check, 9503 // as both operands could be addrecs loop-invariant in each other's loop. 9504 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9505 const Loop *L = AR->getLoop(); 9506 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9507 std::swap(LHS, RHS); 9508 Pred = ICmpInst::getSwappedPredicate(Pred); 9509 Changed = true; 9510 } 9511 } 9512 9513 // If there's a constant operand, canonicalize comparisons with boundary 9514 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9515 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9516 const APInt &RA = RC->getAPInt(); 9517 9518 bool SimplifiedByConstantRange = false; 9519 9520 if (!ICmpInst::isEquality(Pred)) { 9521 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9522 if (ExactCR.isFullSet()) 9523 return TrivialCase(true); 9524 else if (ExactCR.isEmptySet()) 9525 return TrivialCase(false); 9526 9527 APInt NewRHS; 9528 CmpInst::Predicate NewPred; 9529 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9530 ICmpInst::isEquality(NewPred)) { 9531 // We were able to convert an inequality to an equality. 9532 Pred = NewPred; 9533 RHS = getConstant(NewRHS); 9534 Changed = SimplifiedByConstantRange = true; 9535 } 9536 } 9537 9538 if (!SimplifiedByConstantRange) { 9539 switch (Pred) { 9540 default: 9541 break; 9542 case ICmpInst::ICMP_EQ: 9543 case ICmpInst::ICMP_NE: 9544 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9545 if (!RA) 9546 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9547 if (const SCEVMulExpr *ME = 9548 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9549 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9550 ME->getOperand(0)->isAllOnesValue()) { 9551 RHS = AE->getOperand(1); 9552 LHS = ME->getOperand(1); 9553 Changed = true; 9554 } 9555 break; 9556 9557 9558 // The "Should have been caught earlier!" messages refer to the fact 9559 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9560 // should have fired on the corresponding cases, and canonicalized the 9561 // check to trivial case. 9562 9563 case ICmpInst::ICMP_UGE: 9564 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9565 Pred = ICmpInst::ICMP_UGT; 9566 RHS = getConstant(RA - 1); 9567 Changed = true; 9568 break; 9569 case ICmpInst::ICMP_ULE: 9570 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9571 Pred = ICmpInst::ICMP_ULT; 9572 RHS = getConstant(RA + 1); 9573 Changed = true; 9574 break; 9575 case ICmpInst::ICMP_SGE: 9576 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9577 Pred = ICmpInst::ICMP_SGT; 9578 RHS = getConstant(RA - 1); 9579 Changed = true; 9580 break; 9581 case ICmpInst::ICMP_SLE: 9582 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9583 Pred = ICmpInst::ICMP_SLT; 9584 RHS = getConstant(RA + 1); 9585 Changed = true; 9586 break; 9587 } 9588 } 9589 } 9590 9591 // Check for obvious equality. 9592 if (HasSameValue(LHS, RHS)) { 9593 if (ICmpInst::isTrueWhenEqual(Pred)) 9594 return TrivialCase(true); 9595 if (ICmpInst::isFalseWhenEqual(Pred)) 9596 return TrivialCase(false); 9597 } 9598 9599 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9600 // adding or subtracting 1 from one of the operands. 9601 switch (Pred) { 9602 case ICmpInst::ICMP_SLE: 9603 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9604 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9605 SCEV::FlagNSW); 9606 Pred = ICmpInst::ICMP_SLT; 9607 Changed = true; 9608 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9609 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9610 SCEV::FlagNSW); 9611 Pred = ICmpInst::ICMP_SLT; 9612 Changed = true; 9613 } 9614 break; 9615 case ICmpInst::ICMP_SGE: 9616 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9617 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9618 SCEV::FlagNSW); 9619 Pred = ICmpInst::ICMP_SGT; 9620 Changed = true; 9621 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9622 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9623 SCEV::FlagNSW); 9624 Pred = ICmpInst::ICMP_SGT; 9625 Changed = true; 9626 } 9627 break; 9628 case ICmpInst::ICMP_ULE: 9629 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9630 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9631 SCEV::FlagNUW); 9632 Pred = ICmpInst::ICMP_ULT; 9633 Changed = true; 9634 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9635 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9636 Pred = ICmpInst::ICMP_ULT; 9637 Changed = true; 9638 } 9639 break; 9640 case ICmpInst::ICMP_UGE: 9641 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9642 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9643 Pred = ICmpInst::ICMP_UGT; 9644 Changed = true; 9645 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9646 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9647 SCEV::FlagNUW); 9648 Pred = ICmpInst::ICMP_UGT; 9649 Changed = true; 9650 } 9651 break; 9652 default: 9653 break; 9654 } 9655 9656 // TODO: More simplifications are possible here. 9657 9658 // Recursively simplify until we either hit a recursion limit or nothing 9659 // changes. 9660 if (Changed) 9661 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9662 9663 return Changed; 9664 } 9665 9666 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9667 return getSignedRangeMax(S).isNegative(); 9668 } 9669 9670 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9671 return getSignedRangeMin(S).isStrictlyPositive(); 9672 } 9673 9674 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9675 return !getSignedRangeMin(S).isNegative(); 9676 } 9677 9678 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9679 return !getSignedRangeMax(S).isStrictlyPositive(); 9680 } 9681 9682 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9683 return isKnownNegative(S) || isKnownPositive(S); 9684 } 9685 9686 std::pair<const SCEV *, const SCEV *> 9687 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9688 // Compute SCEV on entry of loop L. 9689 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9690 if (Start == getCouldNotCompute()) 9691 return { Start, Start }; 9692 // Compute post increment SCEV for loop L. 9693 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9694 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9695 return { Start, PostInc }; 9696 } 9697 9698 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9699 const SCEV *LHS, const SCEV *RHS) { 9700 // First collect all loops. 9701 SmallPtrSet<const Loop *, 8> LoopsUsed; 9702 getUsedLoops(LHS, LoopsUsed); 9703 getUsedLoops(RHS, LoopsUsed); 9704 9705 if (LoopsUsed.empty()) 9706 return false; 9707 9708 // Domination relationship must be a linear order on collected loops. 9709 #ifndef NDEBUG 9710 for (auto *L1 : LoopsUsed) 9711 for (auto *L2 : LoopsUsed) 9712 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9713 DT.dominates(L2->getHeader(), L1->getHeader())) && 9714 "Domination relationship is not a linear order"); 9715 #endif 9716 9717 const Loop *MDL = 9718 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9719 [&](const Loop *L1, const Loop *L2) { 9720 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9721 }); 9722 9723 // Get init and post increment value for LHS. 9724 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9725 // if LHS contains unknown non-invariant SCEV then bail out. 9726 if (SplitLHS.first == getCouldNotCompute()) 9727 return false; 9728 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9729 // Get init and post increment value for RHS. 9730 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9731 // if RHS contains unknown non-invariant SCEV then bail out. 9732 if (SplitRHS.first == getCouldNotCompute()) 9733 return false; 9734 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9735 // It is possible that init SCEV contains an invariant load but it does 9736 // not dominate MDL and is not available at MDL loop entry, so we should 9737 // check it here. 9738 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9739 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9740 return false; 9741 9742 // It seems backedge guard check is faster than entry one so in some cases 9743 // it can speed up whole estimation by short circuit 9744 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9745 SplitRHS.second) && 9746 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9747 } 9748 9749 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9750 const SCEV *LHS, const SCEV *RHS) { 9751 // Canonicalize the inputs first. 9752 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9753 9754 if (isKnownViaInduction(Pred, LHS, RHS)) 9755 return true; 9756 9757 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9758 return true; 9759 9760 // Otherwise see what can be done with some simple reasoning. 9761 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9762 } 9763 9764 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 9765 const SCEV *LHS, 9766 const SCEV *RHS) { 9767 if (isKnownPredicate(Pred, LHS, RHS)) 9768 return true; 9769 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 9770 return false; 9771 return None; 9772 } 9773 9774 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9775 const SCEV *LHS, const SCEV *RHS, 9776 const Instruction *Context) { 9777 // TODO: Analyze guards and assumes from Context's block. 9778 return isKnownPredicate(Pred, LHS, RHS) || 9779 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9780 } 9781 9782 Optional<bool> 9783 ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS, 9784 const SCEV *RHS, 9785 const Instruction *Context) { 9786 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 9787 if (KnownWithoutContext) 9788 return KnownWithoutContext; 9789 9790 if (isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS)) 9791 return true; 9792 else if (isBasicBlockEntryGuardedByCond(Context->getParent(), 9793 ICmpInst::getInversePredicate(Pred), 9794 LHS, RHS)) 9795 return false; 9796 return None; 9797 } 9798 9799 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9800 const SCEVAddRecExpr *LHS, 9801 const SCEV *RHS) { 9802 const Loop *L = LHS->getLoop(); 9803 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9804 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9805 } 9806 9807 Optional<ScalarEvolution::MonotonicPredicateType> 9808 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9809 ICmpInst::Predicate Pred) { 9810 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9811 9812 #ifndef NDEBUG 9813 // Verify an invariant: inverting the predicate should turn a monotonically 9814 // increasing change to a monotonically decreasing one, and vice versa. 9815 if (Result) { 9816 auto ResultSwapped = 9817 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9818 9819 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9820 assert(ResultSwapped.getValue() != Result.getValue() && 9821 "monotonicity should flip as we flip the predicate"); 9822 } 9823 #endif 9824 9825 return Result; 9826 } 9827 9828 Optional<ScalarEvolution::MonotonicPredicateType> 9829 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9830 ICmpInst::Predicate Pred) { 9831 // A zero step value for LHS means the induction variable is essentially a 9832 // loop invariant value. We don't really depend on the predicate actually 9833 // flipping from false to true (for increasing predicates, and the other way 9834 // around for decreasing predicates), all we care about is that *if* the 9835 // predicate changes then it only changes from false to true. 9836 // 9837 // A zero step value in itself is not very useful, but there may be places 9838 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9839 // as general as possible. 9840 9841 // Only handle LE/LT/GE/GT predicates. 9842 if (!ICmpInst::isRelational(Pred)) 9843 return None; 9844 9845 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9846 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9847 "Should be greater or less!"); 9848 9849 // Check that AR does not wrap. 9850 if (ICmpInst::isUnsigned(Pred)) { 9851 if (!LHS->hasNoUnsignedWrap()) 9852 return None; 9853 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9854 } else { 9855 assert(ICmpInst::isSigned(Pred) && 9856 "Relational predicate is either signed or unsigned!"); 9857 if (!LHS->hasNoSignedWrap()) 9858 return None; 9859 9860 const SCEV *Step = LHS->getStepRecurrence(*this); 9861 9862 if (isKnownNonNegative(Step)) 9863 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9864 9865 if (isKnownNonPositive(Step)) 9866 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9867 9868 return None; 9869 } 9870 } 9871 9872 Optional<ScalarEvolution::LoopInvariantPredicate> 9873 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 9874 const SCEV *LHS, const SCEV *RHS, 9875 const Loop *L) { 9876 9877 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9878 if (!isLoopInvariant(RHS, L)) { 9879 if (!isLoopInvariant(LHS, L)) 9880 return None; 9881 9882 std::swap(LHS, RHS); 9883 Pred = ICmpInst::getSwappedPredicate(Pred); 9884 } 9885 9886 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9887 if (!ArLHS || ArLHS->getLoop() != L) 9888 return None; 9889 9890 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 9891 if (!MonotonicType) 9892 return None; 9893 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9894 // true as the loop iterates, and the backedge is control dependent on 9895 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9896 // 9897 // * if the predicate was false in the first iteration then the predicate 9898 // is never evaluated again, since the loop exits without taking the 9899 // backedge. 9900 // * if the predicate was true in the first iteration then it will 9901 // continue to be true for all future iterations since it is 9902 // monotonically increasing. 9903 // 9904 // For both the above possibilities, we can replace the loop varying 9905 // predicate with its value on the first iteration of the loop (which is 9906 // loop invariant). 9907 // 9908 // A similar reasoning applies for a monotonically decreasing predicate, by 9909 // replacing true with false and false with true in the above two bullets. 9910 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 9911 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9912 9913 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9914 return None; 9915 9916 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 9917 } 9918 9919 Optional<ScalarEvolution::LoopInvariantPredicate> 9920 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 9921 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9922 const Instruction *Context, const SCEV *MaxIter) { 9923 // Try to prove the following set of facts: 9924 // - The predicate is monotonic in the iteration space. 9925 // - If the check does not fail on the 1st iteration: 9926 // - No overflow will happen during first MaxIter iterations; 9927 // - It will not fail on the MaxIter'th iteration. 9928 // If the check does fail on the 1st iteration, we leave the loop and no 9929 // other checks matter. 9930 9931 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9932 if (!isLoopInvariant(RHS, L)) { 9933 if (!isLoopInvariant(LHS, L)) 9934 return None; 9935 9936 std::swap(LHS, RHS); 9937 Pred = ICmpInst::getSwappedPredicate(Pred); 9938 } 9939 9940 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 9941 if (!AR || AR->getLoop() != L) 9942 return None; 9943 9944 // The predicate must be relational (i.e. <, <=, >=, >). 9945 if (!ICmpInst::isRelational(Pred)) 9946 return None; 9947 9948 // TODO: Support steps other than +/- 1. 9949 const SCEV *Step = AR->getStepRecurrence(*this); 9950 auto *One = getOne(Step->getType()); 9951 auto *MinusOne = getNegativeSCEV(One); 9952 if (Step != One && Step != MinusOne) 9953 return None; 9954 9955 // Type mismatch here means that MaxIter is potentially larger than max 9956 // unsigned value in start type, which mean we cannot prove no wrap for the 9957 // indvar. 9958 if (AR->getType() != MaxIter->getType()) 9959 return None; 9960 9961 // Value of IV on suggested last iteration. 9962 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 9963 // Does it still meet the requirement? 9964 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 9965 return None; 9966 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 9967 // not exceed max unsigned value of this type), this effectively proves 9968 // that there is no wrap during the iteration. To prove that there is no 9969 // signed/unsigned wrap, we need to check that 9970 // Start <= Last for step = 1 or Start >= Last for step = -1. 9971 ICmpInst::Predicate NoOverflowPred = 9972 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 9973 if (Step == MinusOne) 9974 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 9975 const SCEV *Start = AR->getStart(); 9976 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context)) 9977 return None; 9978 9979 // Everything is fine. 9980 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 9981 } 9982 9983 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9984 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9985 if (HasSameValue(LHS, RHS)) 9986 return ICmpInst::isTrueWhenEqual(Pred); 9987 9988 // This code is split out from isKnownPredicate because it is called from 9989 // within isLoopEntryGuardedByCond. 9990 9991 auto CheckRanges = [&](const ConstantRange &RangeLHS, 9992 const ConstantRange &RangeRHS) { 9993 return RangeLHS.icmp(Pred, RangeRHS); 9994 }; 9995 9996 // The check at the top of the function catches the case where the values are 9997 // known to be equal. 9998 if (Pred == CmpInst::ICMP_EQ) 9999 return false; 10000 10001 if (Pred == CmpInst::ICMP_NE) 10002 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10003 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 10004 isKnownNonZero(getMinusSCEV(LHS, RHS)); 10005 10006 if (CmpInst::isSigned(Pred)) 10007 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10008 10009 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10010 } 10011 10012 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10013 const SCEV *LHS, 10014 const SCEV *RHS) { 10015 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 10016 // Return Y via OutY. 10017 auto MatchBinaryAddToConst = 10018 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 10019 SCEV::NoWrapFlags ExpectedFlags) { 10020 const SCEV *NonConstOp, *ConstOp; 10021 SCEV::NoWrapFlags FlagsPresent; 10022 10023 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 10024 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 10025 return false; 10026 10027 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 10028 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 10029 }; 10030 10031 APInt C; 10032 10033 switch (Pred) { 10034 default: 10035 break; 10036 10037 case ICmpInst::ICMP_SGE: 10038 std::swap(LHS, RHS); 10039 LLVM_FALLTHROUGH; 10040 case ICmpInst::ICMP_SLE: 10041 // X s<= (X + C)<nsw> if C >= 0 10042 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 10043 return true; 10044 10045 // (X + C)<nsw> s<= X if C <= 0 10046 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 10047 !C.isStrictlyPositive()) 10048 return true; 10049 break; 10050 10051 case ICmpInst::ICMP_SGT: 10052 std::swap(LHS, RHS); 10053 LLVM_FALLTHROUGH; 10054 case ICmpInst::ICMP_SLT: 10055 // X s< (X + C)<nsw> if C > 0 10056 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 10057 C.isStrictlyPositive()) 10058 return true; 10059 10060 // (X + C)<nsw> s< X if C < 0 10061 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 10062 return true; 10063 break; 10064 10065 case ICmpInst::ICMP_UGE: 10066 std::swap(LHS, RHS); 10067 LLVM_FALLTHROUGH; 10068 case ICmpInst::ICMP_ULE: 10069 // X u<= (X + C)<nuw> for any C 10070 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 10071 return true; 10072 break; 10073 10074 case ICmpInst::ICMP_UGT: 10075 std::swap(LHS, RHS); 10076 LLVM_FALLTHROUGH; 10077 case ICmpInst::ICMP_ULT: 10078 // X u< (X + C)<nuw> if C != 0 10079 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 10080 return true; 10081 break; 10082 } 10083 10084 return false; 10085 } 10086 10087 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10088 const SCEV *LHS, 10089 const SCEV *RHS) { 10090 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10091 return false; 10092 10093 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10094 // the stack can result in exponential time complexity. 10095 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10096 10097 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10098 // 10099 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10100 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10101 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10102 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10103 // use isKnownPredicate later if needed. 10104 return isKnownNonNegative(RHS) && 10105 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10106 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10107 } 10108 10109 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10110 ICmpInst::Predicate Pred, 10111 const SCEV *LHS, const SCEV *RHS) { 10112 // No need to even try if we know the module has no guards. 10113 if (!HasGuards) 10114 return false; 10115 10116 return any_of(*BB, [&](const Instruction &I) { 10117 using namespace llvm::PatternMatch; 10118 10119 Value *Condition; 10120 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10121 m_Value(Condition))) && 10122 isImpliedCond(Pred, LHS, RHS, Condition, false); 10123 }); 10124 } 10125 10126 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10127 /// protected by a conditional between LHS and RHS. This is used to 10128 /// to eliminate casts. 10129 bool 10130 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10131 ICmpInst::Predicate Pred, 10132 const SCEV *LHS, const SCEV *RHS) { 10133 // Interpret a null as meaning no loop, where there is obviously no guard 10134 // (interprocedural conditions notwithstanding). 10135 if (!L) return true; 10136 10137 if (VerifyIR) 10138 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10139 "This cannot be done on broken IR!"); 10140 10141 10142 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10143 return true; 10144 10145 BasicBlock *Latch = L->getLoopLatch(); 10146 if (!Latch) 10147 return false; 10148 10149 BranchInst *LoopContinuePredicate = 10150 dyn_cast<BranchInst>(Latch->getTerminator()); 10151 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10152 isImpliedCond(Pred, LHS, RHS, 10153 LoopContinuePredicate->getCondition(), 10154 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10155 return true; 10156 10157 // We don't want more than one activation of the following loops on the stack 10158 // -- that can lead to O(n!) time complexity. 10159 if (WalkingBEDominatingConds) 10160 return false; 10161 10162 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10163 10164 // See if we can exploit a trip count to prove the predicate. 10165 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10166 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10167 if (LatchBECount != getCouldNotCompute()) { 10168 // We know that Latch branches back to the loop header exactly 10169 // LatchBECount times. This means the backdege condition at Latch is 10170 // equivalent to "{0,+,1} u< LatchBECount". 10171 Type *Ty = LatchBECount->getType(); 10172 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10173 const SCEV *LoopCounter = 10174 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10175 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10176 LatchBECount)) 10177 return true; 10178 } 10179 10180 // Check conditions due to any @llvm.assume intrinsics. 10181 for (auto &AssumeVH : AC.assumptions()) { 10182 if (!AssumeVH) 10183 continue; 10184 auto *CI = cast<CallInst>(AssumeVH); 10185 if (!DT.dominates(CI, Latch->getTerminator())) 10186 continue; 10187 10188 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10189 return true; 10190 } 10191 10192 // If the loop is not reachable from the entry block, we risk running into an 10193 // infinite loop as we walk up into the dom tree. These loops do not matter 10194 // anyway, so we just return a conservative answer when we see them. 10195 if (!DT.isReachableFromEntry(L->getHeader())) 10196 return false; 10197 10198 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10199 return true; 10200 10201 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10202 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10203 assert(DTN && "should reach the loop header before reaching the root!"); 10204 10205 BasicBlock *BB = DTN->getBlock(); 10206 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10207 return true; 10208 10209 BasicBlock *PBB = BB->getSinglePredecessor(); 10210 if (!PBB) 10211 continue; 10212 10213 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10214 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10215 continue; 10216 10217 Value *Condition = ContinuePredicate->getCondition(); 10218 10219 // If we have an edge `E` within the loop body that dominates the only 10220 // latch, the condition guarding `E` also guards the backedge. This 10221 // reasoning works only for loops with a single latch. 10222 10223 BasicBlockEdge DominatingEdge(PBB, BB); 10224 if (DominatingEdge.isSingleEdge()) { 10225 // We're constructively (and conservatively) enumerating edges within the 10226 // loop body that dominate the latch. The dominator tree better agree 10227 // with us on this: 10228 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10229 10230 if (isImpliedCond(Pred, LHS, RHS, Condition, 10231 BB != ContinuePredicate->getSuccessor(0))) 10232 return true; 10233 } 10234 } 10235 10236 return false; 10237 } 10238 10239 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10240 ICmpInst::Predicate Pred, 10241 const SCEV *LHS, 10242 const SCEV *RHS) { 10243 if (VerifyIR) 10244 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10245 "This cannot be done on broken IR!"); 10246 10247 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10248 // the facts (a >= b && a != b) separately. A typical situation is when the 10249 // non-strict comparison is known from ranges and non-equality is known from 10250 // dominating predicates. If we are proving strict comparison, we always try 10251 // to prove non-equality and non-strict comparison separately. 10252 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10253 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10254 bool ProvedNonStrictComparison = false; 10255 bool ProvedNonEquality = false; 10256 10257 auto SplitAndProve = 10258 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10259 if (!ProvedNonStrictComparison) 10260 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10261 if (!ProvedNonEquality) 10262 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10263 if (ProvedNonStrictComparison && ProvedNonEquality) 10264 return true; 10265 return false; 10266 }; 10267 10268 if (ProvingStrictComparison) { 10269 auto ProofFn = [&](ICmpInst::Predicate P) { 10270 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10271 }; 10272 if (SplitAndProve(ProofFn)) 10273 return true; 10274 } 10275 10276 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10277 auto ProveViaGuard = [&](const BasicBlock *Block) { 10278 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10279 return true; 10280 if (ProvingStrictComparison) { 10281 auto ProofFn = [&](ICmpInst::Predicate P) { 10282 return isImpliedViaGuard(Block, P, LHS, RHS); 10283 }; 10284 if (SplitAndProve(ProofFn)) 10285 return true; 10286 } 10287 return false; 10288 }; 10289 10290 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10291 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10292 const Instruction *Context = &BB->front(); 10293 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 10294 return true; 10295 if (ProvingStrictComparison) { 10296 auto ProofFn = [&](ICmpInst::Predicate P) { 10297 return isImpliedCond(P, LHS, RHS, Condition, Inverse, Context); 10298 }; 10299 if (SplitAndProve(ProofFn)) 10300 return true; 10301 } 10302 return false; 10303 }; 10304 10305 // Starting at the block's predecessor, climb up the predecessor chain, as long 10306 // as there are predecessors that can be found that have unique successors 10307 // leading to the original block. 10308 const Loop *ContainingLoop = LI.getLoopFor(BB); 10309 const BasicBlock *PredBB; 10310 if (ContainingLoop && ContainingLoop->getHeader() == BB) 10311 PredBB = ContainingLoop->getLoopPredecessor(); 10312 else 10313 PredBB = BB->getSinglePredecessor(); 10314 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 10315 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 10316 if (ProveViaGuard(Pair.first)) 10317 return true; 10318 10319 const BranchInst *LoopEntryPredicate = 10320 dyn_cast<BranchInst>(Pair.first->getTerminator()); 10321 if (!LoopEntryPredicate || 10322 LoopEntryPredicate->isUnconditional()) 10323 continue; 10324 10325 if (ProveViaCond(LoopEntryPredicate->getCondition(), 10326 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 10327 return true; 10328 } 10329 10330 // Check conditions due to any @llvm.assume intrinsics. 10331 for (auto &AssumeVH : AC.assumptions()) { 10332 if (!AssumeVH) 10333 continue; 10334 auto *CI = cast<CallInst>(AssumeVH); 10335 if (!DT.dominates(CI, BB)) 10336 continue; 10337 10338 if (ProveViaCond(CI->getArgOperand(0), false)) 10339 return true; 10340 } 10341 10342 return false; 10343 } 10344 10345 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 10346 ICmpInst::Predicate Pred, 10347 const SCEV *LHS, 10348 const SCEV *RHS) { 10349 // Interpret a null as meaning no loop, where there is obviously no guard 10350 // (interprocedural conditions notwithstanding). 10351 if (!L) 10352 return false; 10353 10354 // Both LHS and RHS must be available at loop entry. 10355 assert(isAvailableAtLoopEntry(LHS, L) && 10356 "LHS is not available at Loop Entry"); 10357 assert(isAvailableAtLoopEntry(RHS, L) && 10358 "RHS is not available at Loop Entry"); 10359 10360 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10361 return true; 10362 10363 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 10364 } 10365 10366 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10367 const SCEV *RHS, 10368 const Value *FoundCondValue, bool Inverse, 10369 const Instruction *Context) { 10370 // False conditions implies anything. Do not bother analyzing it further. 10371 if (FoundCondValue == 10372 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 10373 return true; 10374 10375 if (!PendingLoopPredicates.insert(FoundCondValue).second) 10376 return false; 10377 10378 auto ClearOnExit = 10379 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 10380 10381 // Recursively handle And and Or conditions. 10382 const Value *Op0, *Op1; 10383 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 10384 if (!Inverse) 10385 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10386 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10387 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 10388 if (Inverse) 10389 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, Context) || 10390 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, Context); 10391 } 10392 10393 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10394 if (!ICI) return false; 10395 10396 // Now that we found a conditional branch that dominates the loop or controls 10397 // the loop latch. Check to see if it is the comparison we are looking for. 10398 ICmpInst::Predicate FoundPred; 10399 if (Inverse) 10400 FoundPred = ICI->getInversePredicate(); 10401 else 10402 FoundPred = ICI->getPredicate(); 10403 10404 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10405 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10406 10407 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10408 } 10409 10410 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10411 const SCEV *RHS, 10412 ICmpInst::Predicate FoundPred, 10413 const SCEV *FoundLHS, const SCEV *FoundRHS, 10414 const Instruction *Context) { 10415 // Balance the types. 10416 if (getTypeSizeInBits(LHS->getType()) < 10417 getTypeSizeInBits(FoundLHS->getType())) { 10418 // For unsigned and equality predicates, try to prove that both found 10419 // operands fit into narrow unsigned range. If so, try to prove facts in 10420 // narrow types. 10421 if (!CmpInst::isSigned(FoundPred)) { 10422 auto *NarrowType = LHS->getType(); 10423 auto *WideType = FoundLHS->getType(); 10424 auto BitWidth = getTypeSizeInBits(NarrowType); 10425 const SCEV *MaxValue = getZeroExtendExpr( 10426 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10427 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10428 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10429 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10430 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10431 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10432 TruncFoundRHS, Context)) 10433 return true; 10434 } 10435 } 10436 10437 if (CmpInst::isSigned(Pred)) { 10438 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10439 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10440 } else { 10441 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10442 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10443 } 10444 } else if (getTypeSizeInBits(LHS->getType()) > 10445 getTypeSizeInBits(FoundLHS->getType())) { 10446 if (CmpInst::isSigned(FoundPred)) { 10447 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10448 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10449 } else { 10450 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10451 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10452 } 10453 } 10454 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10455 FoundRHS, Context); 10456 } 10457 10458 bool ScalarEvolution::isImpliedCondBalancedTypes( 10459 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10460 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10461 const Instruction *Context) { 10462 assert(getTypeSizeInBits(LHS->getType()) == 10463 getTypeSizeInBits(FoundLHS->getType()) && 10464 "Types should be balanced!"); 10465 // Canonicalize the query to match the way instcombine will have 10466 // canonicalized the comparison. 10467 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10468 if (LHS == RHS) 10469 return CmpInst::isTrueWhenEqual(Pred); 10470 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10471 if (FoundLHS == FoundRHS) 10472 return CmpInst::isFalseWhenEqual(FoundPred); 10473 10474 // Check to see if we can make the LHS or RHS match. 10475 if (LHS == FoundRHS || RHS == FoundLHS) { 10476 if (isa<SCEVConstant>(RHS)) { 10477 std::swap(FoundLHS, FoundRHS); 10478 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10479 } else { 10480 std::swap(LHS, RHS); 10481 Pred = ICmpInst::getSwappedPredicate(Pred); 10482 } 10483 } 10484 10485 // Check whether the found predicate is the same as the desired predicate. 10486 if (FoundPred == Pred) 10487 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10488 10489 // Check whether swapping the found predicate makes it the same as the 10490 // desired predicate. 10491 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10492 // We can write the implication 10493 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 10494 // using one of the following ways: 10495 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 10496 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 10497 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 10498 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 10499 // Forms 1. and 2. require swapping the operands of one condition. Don't 10500 // do this if it would break canonical constant/addrec ordering. 10501 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 10502 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 10503 Context); 10504 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 10505 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10506 10507 // There's no clear preference between forms 3. and 4., try both. 10508 return isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 10509 FoundLHS, FoundRHS, Context) || 10510 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 10511 getNotSCEV(FoundRHS), Context); 10512 } 10513 10514 // Unsigned comparison is the same as signed comparison when both the operands 10515 // are non-negative. 10516 if (CmpInst::isUnsigned(FoundPred) && 10517 CmpInst::getSignedPredicate(FoundPred) == Pred && 10518 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10519 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10520 10521 // Check if we can make progress by sharpening ranges. 10522 if (FoundPred == ICmpInst::ICMP_NE && 10523 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10524 10525 const SCEVConstant *C = nullptr; 10526 const SCEV *V = nullptr; 10527 10528 if (isa<SCEVConstant>(FoundLHS)) { 10529 C = cast<SCEVConstant>(FoundLHS); 10530 V = FoundRHS; 10531 } else { 10532 C = cast<SCEVConstant>(FoundRHS); 10533 V = FoundLHS; 10534 } 10535 10536 // The guarding predicate tells us that C != V. If the known range 10537 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10538 // range we consider has to correspond to same signedness as the 10539 // predicate we're interested in folding. 10540 10541 APInt Min = ICmpInst::isSigned(Pred) ? 10542 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10543 10544 if (Min == C->getAPInt()) { 10545 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10546 // This is true even if (Min + 1) wraps around -- in case of 10547 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10548 10549 APInt SharperMin = Min + 1; 10550 10551 switch (Pred) { 10552 case ICmpInst::ICMP_SGE: 10553 case ICmpInst::ICMP_UGE: 10554 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10555 // RHS, we're done. 10556 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10557 Context)) 10558 return true; 10559 LLVM_FALLTHROUGH; 10560 10561 case ICmpInst::ICMP_SGT: 10562 case ICmpInst::ICMP_UGT: 10563 // We know from the range information that (V `Pred` Min || 10564 // V == Min). We know from the guarding condition that !(V 10565 // == Min). This gives us 10566 // 10567 // V `Pred` Min || V == Min && !(V == Min) 10568 // => V `Pred` Min 10569 // 10570 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10571 10572 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10573 Context)) 10574 return true; 10575 break; 10576 10577 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10578 case ICmpInst::ICMP_SLE: 10579 case ICmpInst::ICMP_ULE: 10580 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10581 LHS, V, getConstant(SharperMin), Context)) 10582 return true; 10583 LLVM_FALLTHROUGH; 10584 10585 case ICmpInst::ICMP_SLT: 10586 case ICmpInst::ICMP_ULT: 10587 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10588 LHS, V, getConstant(Min), Context)) 10589 return true; 10590 break; 10591 10592 default: 10593 // No change 10594 break; 10595 } 10596 } 10597 } 10598 10599 // Check whether the actual condition is beyond sufficient. 10600 if (FoundPred == ICmpInst::ICMP_EQ) 10601 if (ICmpInst::isTrueWhenEqual(Pred)) 10602 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10603 return true; 10604 if (Pred == ICmpInst::ICMP_NE) 10605 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10606 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10607 Context)) 10608 return true; 10609 10610 // Otherwise assume the worst. 10611 return false; 10612 } 10613 10614 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10615 const SCEV *&L, const SCEV *&R, 10616 SCEV::NoWrapFlags &Flags) { 10617 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10618 if (!AE || AE->getNumOperands() != 2) 10619 return false; 10620 10621 L = AE->getOperand(0); 10622 R = AE->getOperand(1); 10623 Flags = AE->getNoWrapFlags(); 10624 return true; 10625 } 10626 10627 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10628 const SCEV *Less) { 10629 // We avoid subtracting expressions here because this function is usually 10630 // fairly deep in the call stack (i.e. is called many times). 10631 10632 // X - X = 0. 10633 if (More == Less) 10634 return APInt(getTypeSizeInBits(More->getType()), 0); 10635 10636 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10637 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10638 const auto *MAR = cast<SCEVAddRecExpr>(More); 10639 10640 if (LAR->getLoop() != MAR->getLoop()) 10641 return None; 10642 10643 // We look at affine expressions only; not for correctness but to keep 10644 // getStepRecurrence cheap. 10645 if (!LAR->isAffine() || !MAR->isAffine()) 10646 return None; 10647 10648 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10649 return None; 10650 10651 Less = LAR->getStart(); 10652 More = MAR->getStart(); 10653 10654 // fall through 10655 } 10656 10657 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10658 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10659 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10660 return M - L; 10661 } 10662 10663 SCEV::NoWrapFlags Flags; 10664 const SCEV *LLess = nullptr, *RLess = nullptr; 10665 const SCEV *LMore = nullptr, *RMore = nullptr; 10666 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10667 // Compare (X + C1) vs X. 10668 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10669 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10670 if (RLess == More) 10671 return -(C1->getAPInt()); 10672 10673 // Compare X vs (X + C2). 10674 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10675 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10676 if (RMore == Less) 10677 return C2->getAPInt(); 10678 10679 // Compare (X + C1) vs (X + C2). 10680 if (C1 && C2 && RLess == RMore) 10681 return C2->getAPInt() - C1->getAPInt(); 10682 10683 return None; 10684 } 10685 10686 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10687 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10688 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10689 // Try to recognize the following pattern: 10690 // 10691 // FoundRHS = ... 10692 // ... 10693 // loop: 10694 // FoundLHS = {Start,+,W} 10695 // context_bb: // Basic block from the same loop 10696 // known(Pred, FoundLHS, FoundRHS) 10697 // 10698 // If some predicate is known in the context of a loop, it is also known on 10699 // each iteration of this loop, including the first iteration. Therefore, in 10700 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10701 // prove the original pred using this fact. 10702 if (!Context) 10703 return false; 10704 const BasicBlock *ContextBB = Context->getParent(); 10705 // Make sure AR varies in the context block. 10706 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10707 const Loop *L = AR->getLoop(); 10708 // Make sure that context belongs to the loop and executes on 1st iteration 10709 // (if it ever executes at all). 10710 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10711 return false; 10712 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10713 return false; 10714 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10715 } 10716 10717 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10718 const Loop *L = AR->getLoop(); 10719 // Make sure that context belongs to the loop and executes on 1st iteration 10720 // (if it ever executes at all). 10721 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10722 return false; 10723 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10724 return false; 10725 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10726 } 10727 10728 return false; 10729 } 10730 10731 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10732 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10733 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10734 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10735 return false; 10736 10737 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10738 if (!AddRecLHS) 10739 return false; 10740 10741 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10742 if (!AddRecFoundLHS) 10743 return false; 10744 10745 // We'd like to let SCEV reason about control dependencies, so we constrain 10746 // both the inequalities to be about add recurrences on the same loop. This 10747 // way we can use isLoopEntryGuardedByCond later. 10748 10749 const Loop *L = AddRecFoundLHS->getLoop(); 10750 if (L != AddRecLHS->getLoop()) 10751 return false; 10752 10753 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10754 // 10755 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10756 // ... (2) 10757 // 10758 // Informal proof for (2), assuming (1) [*]: 10759 // 10760 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10761 // 10762 // Then 10763 // 10764 // FoundLHS s< FoundRHS s< INT_MIN - C 10765 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10766 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10767 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10768 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10769 // <=> FoundLHS + C s< FoundRHS + C 10770 // 10771 // [*]: (1) can be proved by ruling out overflow. 10772 // 10773 // [**]: This can be proved by analyzing all the four possibilities: 10774 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10775 // (A s>= 0, B s>= 0). 10776 // 10777 // Note: 10778 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10779 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10780 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10781 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10782 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10783 // C)". 10784 10785 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10786 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10787 if (!LDiff || !RDiff || *LDiff != *RDiff) 10788 return false; 10789 10790 if (LDiff->isMinValue()) 10791 return true; 10792 10793 APInt FoundRHSLimit; 10794 10795 if (Pred == CmpInst::ICMP_ULT) { 10796 FoundRHSLimit = -(*RDiff); 10797 } else { 10798 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10799 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10800 } 10801 10802 // Try to prove (1) or (2), as needed. 10803 return isAvailableAtLoopEntry(FoundRHS, L) && 10804 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10805 getConstant(FoundRHSLimit)); 10806 } 10807 10808 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10809 const SCEV *LHS, const SCEV *RHS, 10810 const SCEV *FoundLHS, 10811 const SCEV *FoundRHS, unsigned Depth) { 10812 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10813 10814 auto ClearOnExit = make_scope_exit([&]() { 10815 if (LPhi) { 10816 bool Erased = PendingMerges.erase(LPhi); 10817 assert(Erased && "Failed to erase LPhi!"); 10818 (void)Erased; 10819 } 10820 if (RPhi) { 10821 bool Erased = PendingMerges.erase(RPhi); 10822 assert(Erased && "Failed to erase RPhi!"); 10823 (void)Erased; 10824 } 10825 }); 10826 10827 // Find respective Phis and check that they are not being pending. 10828 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10829 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10830 if (!PendingMerges.insert(Phi).second) 10831 return false; 10832 LPhi = Phi; 10833 } 10834 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10835 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10836 // If we detect a loop of Phi nodes being processed by this method, for 10837 // example: 10838 // 10839 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10840 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10841 // 10842 // we don't want to deal with a case that complex, so return conservative 10843 // answer false. 10844 if (!PendingMerges.insert(Phi).second) 10845 return false; 10846 RPhi = Phi; 10847 } 10848 10849 // If none of LHS, RHS is a Phi, nothing to do here. 10850 if (!LPhi && !RPhi) 10851 return false; 10852 10853 // If there is a SCEVUnknown Phi we are interested in, make it left. 10854 if (!LPhi) { 10855 std::swap(LHS, RHS); 10856 std::swap(FoundLHS, FoundRHS); 10857 std::swap(LPhi, RPhi); 10858 Pred = ICmpInst::getSwappedPredicate(Pred); 10859 } 10860 10861 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10862 const BasicBlock *LBB = LPhi->getParent(); 10863 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10864 10865 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10866 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10867 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10868 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10869 }; 10870 10871 if (RPhi && RPhi->getParent() == LBB) { 10872 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10873 // If we compare two Phis from the same block, and for each entry block 10874 // the predicate is true for incoming values from this block, then the 10875 // predicate is also true for the Phis. 10876 for (const BasicBlock *IncBB : predecessors(LBB)) { 10877 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10878 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10879 if (!ProvedEasily(L, R)) 10880 return false; 10881 } 10882 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10883 // Case two: RHS is also a Phi from the same basic block, and it is an 10884 // AddRec. It means that there is a loop which has both AddRec and Unknown 10885 // PHIs, for it we can compare incoming values of AddRec from above the loop 10886 // and latch with their respective incoming values of LPhi. 10887 // TODO: Generalize to handle loops with many inputs in a header. 10888 if (LPhi->getNumIncomingValues() != 2) return false; 10889 10890 auto *RLoop = RAR->getLoop(); 10891 auto *Predecessor = RLoop->getLoopPredecessor(); 10892 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10893 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10894 if (!ProvedEasily(L1, RAR->getStart())) 10895 return false; 10896 auto *Latch = RLoop->getLoopLatch(); 10897 assert(Latch && "Loop with AddRec with no latch?"); 10898 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10899 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10900 return false; 10901 } else { 10902 // In all other cases go over inputs of LHS and compare each of them to RHS, 10903 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10904 // At this point RHS is either a non-Phi, or it is a Phi from some block 10905 // different from LBB. 10906 for (const BasicBlock *IncBB : predecessors(LBB)) { 10907 // Check that RHS is available in this block. 10908 if (!dominates(RHS, IncBB)) 10909 return false; 10910 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10911 // Make sure L does not refer to a value from a potentially previous 10912 // iteration of a loop. 10913 if (!properlyDominates(L, IncBB)) 10914 return false; 10915 if (!ProvedEasily(L, RHS)) 10916 return false; 10917 } 10918 } 10919 return true; 10920 } 10921 10922 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10923 const SCEV *LHS, const SCEV *RHS, 10924 const SCEV *FoundLHS, 10925 const SCEV *FoundRHS, 10926 const Instruction *Context) { 10927 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10928 return true; 10929 10930 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10931 return true; 10932 10933 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10934 Context)) 10935 return true; 10936 10937 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10938 FoundLHS, FoundRHS); 10939 } 10940 10941 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10942 template <typename MinMaxExprType> 10943 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10944 const SCEV *Candidate) { 10945 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10946 if (!MinMaxExpr) 10947 return false; 10948 10949 return is_contained(MinMaxExpr->operands(), Candidate); 10950 } 10951 10952 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10953 ICmpInst::Predicate Pred, 10954 const SCEV *LHS, const SCEV *RHS) { 10955 // If both sides are affine addrecs for the same loop, with equal 10956 // steps, and we know the recurrences don't wrap, then we only 10957 // need to check the predicate on the starting values. 10958 10959 if (!ICmpInst::isRelational(Pred)) 10960 return false; 10961 10962 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10963 if (!LAR) 10964 return false; 10965 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10966 if (!RAR) 10967 return false; 10968 if (LAR->getLoop() != RAR->getLoop()) 10969 return false; 10970 if (!LAR->isAffine() || !RAR->isAffine()) 10971 return false; 10972 10973 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10974 return false; 10975 10976 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10977 SCEV::FlagNSW : SCEV::FlagNUW; 10978 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10979 return false; 10980 10981 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10982 } 10983 10984 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10985 /// expression? 10986 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10987 ICmpInst::Predicate Pred, 10988 const SCEV *LHS, const SCEV *RHS) { 10989 switch (Pred) { 10990 default: 10991 return false; 10992 10993 case ICmpInst::ICMP_SGE: 10994 std::swap(LHS, RHS); 10995 LLVM_FALLTHROUGH; 10996 case ICmpInst::ICMP_SLE: 10997 return 10998 // min(A, ...) <= A 10999 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11000 // A <= max(A, ...) 11001 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11002 11003 case ICmpInst::ICMP_UGE: 11004 std::swap(LHS, RHS); 11005 LLVM_FALLTHROUGH; 11006 case ICmpInst::ICMP_ULE: 11007 return 11008 // min(A, ...) <= A 11009 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11010 // A <= max(A, ...) 11011 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11012 } 11013 11014 llvm_unreachable("covered switch fell through?!"); 11015 } 11016 11017 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11018 const SCEV *LHS, const SCEV *RHS, 11019 const SCEV *FoundLHS, 11020 const SCEV *FoundRHS, 11021 unsigned Depth) { 11022 assert(getTypeSizeInBits(LHS->getType()) == 11023 getTypeSizeInBits(RHS->getType()) && 11024 "LHS and RHS have different sizes?"); 11025 assert(getTypeSizeInBits(FoundLHS->getType()) == 11026 getTypeSizeInBits(FoundRHS->getType()) && 11027 "FoundLHS and FoundRHS have different sizes?"); 11028 // We want to avoid hurting the compile time with analysis of too big trees. 11029 if (Depth > MaxSCEVOperationsImplicationDepth) 11030 return false; 11031 11032 // We only want to work with GT comparison so far. 11033 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11034 Pred = CmpInst::getSwappedPredicate(Pred); 11035 std::swap(LHS, RHS); 11036 std::swap(FoundLHS, FoundRHS); 11037 } 11038 11039 // For unsigned, try to reduce it to corresponding signed comparison. 11040 if (Pred == ICmpInst::ICMP_UGT) 11041 // We can replace unsigned predicate with its signed counterpart if all 11042 // involved values are non-negative. 11043 // TODO: We could have better support for unsigned. 11044 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11045 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11046 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11047 // use this fact to prove that LHS and RHS are non-negative. 11048 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11049 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11050 FoundRHS) && 11051 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11052 FoundRHS)) 11053 Pred = ICmpInst::ICMP_SGT; 11054 } 11055 11056 if (Pred != ICmpInst::ICMP_SGT) 11057 return false; 11058 11059 auto GetOpFromSExt = [&](const SCEV *S) { 11060 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11061 return Ext->getOperand(); 11062 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11063 // the constant in some cases. 11064 return S; 11065 }; 11066 11067 // Acquire values from extensions. 11068 auto *OrigLHS = LHS; 11069 auto *OrigFoundLHS = FoundLHS; 11070 LHS = GetOpFromSExt(LHS); 11071 FoundLHS = GetOpFromSExt(FoundLHS); 11072 11073 // Is the SGT predicate can be proved trivially or using the found context. 11074 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11075 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11076 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11077 FoundRHS, Depth + 1); 11078 }; 11079 11080 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11081 // We want to avoid creation of any new non-constant SCEV. Since we are 11082 // going to compare the operands to RHS, we should be certain that we don't 11083 // need any size extensions for this. So let's decline all cases when the 11084 // sizes of types of LHS and RHS do not match. 11085 // TODO: Maybe try to get RHS from sext to catch more cases? 11086 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11087 return false; 11088 11089 // Should not overflow. 11090 if (!LHSAddExpr->hasNoSignedWrap()) 11091 return false; 11092 11093 auto *LL = LHSAddExpr->getOperand(0); 11094 auto *LR = LHSAddExpr->getOperand(1); 11095 auto *MinusOne = getMinusOne(RHS->getType()); 11096 11097 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11098 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11099 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11100 }; 11101 // Try to prove the following rule: 11102 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11103 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11104 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11105 return true; 11106 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11107 Value *LL, *LR; 11108 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11109 11110 using namespace llvm::PatternMatch; 11111 11112 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11113 // Rules for division. 11114 // We are going to perform some comparisons with Denominator and its 11115 // derivative expressions. In general case, creating a SCEV for it may 11116 // lead to a complex analysis of the entire graph, and in particular it 11117 // can request trip count recalculation for the same loop. This would 11118 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11119 // this, we only want to create SCEVs that are constants in this section. 11120 // So we bail if Denominator is not a constant. 11121 if (!isa<ConstantInt>(LR)) 11122 return false; 11123 11124 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11125 11126 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11127 // then a SCEV for the numerator already exists and matches with FoundLHS. 11128 auto *Numerator = getExistingSCEV(LL); 11129 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11130 return false; 11131 11132 // Make sure that the numerator matches with FoundLHS and the denominator 11133 // is positive. 11134 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11135 return false; 11136 11137 auto *DTy = Denominator->getType(); 11138 auto *FRHSTy = FoundRHS->getType(); 11139 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11140 // One of types is a pointer and another one is not. We cannot extend 11141 // them properly to a wider type, so let us just reject this case. 11142 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11143 // to avoid this check. 11144 return false; 11145 11146 // Given that: 11147 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11148 auto *WTy = getWiderType(DTy, FRHSTy); 11149 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11150 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11151 11152 // Try to prove the following rule: 11153 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11154 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11155 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11156 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11157 if (isKnownNonPositive(RHS) && 11158 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11159 return true; 11160 11161 // Try to prove the following rule: 11162 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11163 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11164 // If we divide it by Denominator > 2, then: 11165 // 1. If FoundLHS is negative, then the result is 0. 11166 // 2. If FoundLHS is non-negative, then the result is non-negative. 11167 // Anyways, the result is non-negative. 11168 auto *MinusOne = getMinusOne(WTy); 11169 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11170 if (isKnownNegative(RHS) && 11171 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11172 return true; 11173 } 11174 } 11175 11176 // If our expression contained SCEVUnknown Phis, and we split it down and now 11177 // need to prove something for them, try to prove the predicate for every 11178 // possible incoming values of those Phis. 11179 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11180 return true; 11181 11182 return false; 11183 } 11184 11185 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11186 const SCEV *LHS, const SCEV *RHS) { 11187 // zext x u<= sext x, sext x s<= zext x 11188 switch (Pred) { 11189 case ICmpInst::ICMP_SGE: 11190 std::swap(LHS, RHS); 11191 LLVM_FALLTHROUGH; 11192 case ICmpInst::ICMP_SLE: { 11193 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11194 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11195 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11196 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11197 return true; 11198 break; 11199 } 11200 case ICmpInst::ICMP_UGE: 11201 std::swap(LHS, RHS); 11202 LLVM_FALLTHROUGH; 11203 case ICmpInst::ICMP_ULE: { 11204 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11205 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11206 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11207 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11208 return true; 11209 break; 11210 } 11211 default: 11212 break; 11213 }; 11214 return false; 11215 } 11216 11217 bool 11218 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 11219 const SCEV *LHS, const SCEV *RHS) { 11220 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 11221 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 11222 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 11223 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 11224 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 11225 } 11226 11227 bool 11228 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 11229 const SCEV *LHS, const SCEV *RHS, 11230 const SCEV *FoundLHS, 11231 const SCEV *FoundRHS) { 11232 switch (Pred) { 11233 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 11234 case ICmpInst::ICMP_EQ: 11235 case ICmpInst::ICMP_NE: 11236 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 11237 return true; 11238 break; 11239 case ICmpInst::ICMP_SLT: 11240 case ICmpInst::ICMP_SLE: 11241 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 11242 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 11243 return true; 11244 break; 11245 case ICmpInst::ICMP_SGT: 11246 case ICmpInst::ICMP_SGE: 11247 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 11248 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 11249 return true; 11250 break; 11251 case ICmpInst::ICMP_ULT: 11252 case ICmpInst::ICMP_ULE: 11253 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 11254 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 11255 return true; 11256 break; 11257 case ICmpInst::ICMP_UGT: 11258 case ICmpInst::ICMP_UGE: 11259 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 11260 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 11261 return true; 11262 break; 11263 } 11264 11265 // Maybe it can be proved via operations? 11266 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11267 return true; 11268 11269 return false; 11270 } 11271 11272 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 11273 const SCEV *LHS, 11274 const SCEV *RHS, 11275 const SCEV *FoundLHS, 11276 const SCEV *FoundRHS) { 11277 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 11278 // The restriction on `FoundRHS` be lifted easily -- it exists only to 11279 // reduce the compile time impact of this optimization. 11280 return false; 11281 11282 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 11283 if (!Addend) 11284 return false; 11285 11286 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 11287 11288 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 11289 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 11290 ConstantRange FoundLHSRange = 11291 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 11292 11293 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 11294 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 11295 11296 // We can also compute the range of values for `LHS` that satisfy the 11297 // consequent, "`LHS` `Pred` `RHS`": 11298 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 11299 // The antecedent implies the consequent if every value of `LHS` that 11300 // satisfies the antecedent also satisfies the consequent. 11301 return LHSRange.icmp(Pred, ConstRHS); 11302 } 11303 11304 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 11305 bool IsSigned) { 11306 assert(isKnownPositive(Stride) && "Positive stride expected!"); 11307 11308 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11309 const SCEV *One = getOne(Stride->getType()); 11310 11311 if (IsSigned) { 11312 APInt MaxRHS = getSignedRangeMax(RHS); 11313 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 11314 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11315 11316 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 11317 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 11318 } 11319 11320 APInt MaxRHS = getUnsignedRangeMax(RHS); 11321 APInt MaxValue = APInt::getMaxValue(BitWidth); 11322 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11323 11324 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 11325 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 11326 } 11327 11328 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 11329 bool IsSigned) { 11330 11331 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 11332 const SCEV *One = getOne(Stride->getType()); 11333 11334 if (IsSigned) { 11335 APInt MinRHS = getSignedRangeMin(RHS); 11336 APInt MinValue = APInt::getSignedMinValue(BitWidth); 11337 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 11338 11339 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 11340 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 11341 } 11342 11343 APInt MinRHS = getUnsignedRangeMin(RHS); 11344 APInt MinValue = APInt::getMinValue(BitWidth); 11345 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 11346 11347 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 11348 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 11349 } 11350 11351 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, 11352 const SCEV *Step) { 11353 const SCEV *One = getOne(Step->getType()); 11354 Delta = getAddExpr(Delta, getMinusSCEV(Step, One)); 11355 return getUDivExpr(Delta, Step); 11356 } 11357 11358 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 11359 const SCEV *Stride, 11360 const SCEV *End, 11361 unsigned BitWidth, 11362 bool IsSigned) { 11363 11364 assert(!isKnownNonPositive(Stride) && 11365 "Stride is expected strictly positive!"); 11366 // Calculate the maximum backedge count based on the range of values 11367 // permitted by Start, End, and Stride. 11368 const SCEV *MaxBECount; 11369 APInt MinStart = 11370 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 11371 11372 APInt StrideForMaxBECount = 11373 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 11374 11375 // We already know that the stride is positive, so we paper over conservatism 11376 // in our range computation by forcing StrideForMaxBECount to be at least one. 11377 // In theory this is unnecessary, but we expect MaxBECount to be a 11378 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 11379 // is nothing to constant fold it to). 11380 APInt One(BitWidth, 1, IsSigned); 11381 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 11382 11383 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 11384 : APInt::getMaxValue(BitWidth); 11385 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 11386 11387 // Although End can be a MAX expression we estimate MaxEnd considering only 11388 // the case End = RHS of the loop termination condition. This is safe because 11389 // in the other case (End - Start) is zero, leading to a zero maximum backedge 11390 // taken count. 11391 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11392 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11393 11394 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 11395 getConstant(StrideForMaxBECount) /* Step */); 11396 11397 return MaxBECount; 11398 } 11399 11400 ScalarEvolution::ExitLimit 11401 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11402 const Loop *L, bool IsSigned, 11403 bool ControlsExit, bool AllowPredicates) { 11404 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11405 11406 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11407 bool PredicatedIV = false; 11408 11409 if (!IV && AllowPredicates) { 11410 // Try to make this an AddRec using runtime tests, in the first X 11411 // iterations of this loop, where X is the SCEV expression found by the 11412 // algorithm below. 11413 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11414 PredicatedIV = true; 11415 } 11416 11417 // Avoid weird loops 11418 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11419 return getCouldNotCompute(); 11420 11421 bool NoWrap = ControlsExit && 11422 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11423 11424 const SCEV *Stride = IV->getStepRecurrence(*this); 11425 11426 bool PositiveStride = isKnownPositive(Stride); 11427 11428 // Avoid negative or zero stride values. 11429 if (!PositiveStride) { 11430 // We can compute the correct backedge taken count for loops with unknown 11431 // strides if we can prove that the loop is not an infinite loop with side 11432 // effects. Here's the loop structure we are trying to handle - 11433 // 11434 // i = start 11435 // do { 11436 // A[i] = i; 11437 // i += s; 11438 // } while (i < end); 11439 // 11440 // The backedge taken count for such loops is evaluated as - 11441 // (max(end, start + stride) - start - 1) /u stride 11442 // 11443 // The additional preconditions that we need to check to prove correctness 11444 // of the above formula is as follows - 11445 // 11446 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11447 // NoWrap flag). 11448 // b) loop is single exit with no side effects. 11449 // 11450 // 11451 // Precondition a) implies that if the stride is negative, this is a single 11452 // trip loop. The backedge taken count formula reduces to zero in this case. 11453 // 11454 // Precondition b) implies that the unknown stride cannot be zero otherwise 11455 // we have UB. 11456 // 11457 // The positive stride case is the same as isKnownPositive(Stride) returning 11458 // true (original behavior of the function). 11459 // 11460 // We want to make sure that the stride is truly unknown as there are edge 11461 // cases where ScalarEvolution propagates no wrap flags to the 11462 // post-increment/decrement IV even though the increment/decrement operation 11463 // itself is wrapping. The computed backedge taken count may be wrong in 11464 // such cases. This is prevented by checking that the stride is not known to 11465 // be either positive or non-positive. For example, no wrap flags are 11466 // propagated to the post-increment IV of this loop with a trip count of 2 - 11467 // 11468 // unsigned char i; 11469 // for(i=127; i<128; i+=129) 11470 // A[i] = i; 11471 // 11472 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11473 !loopIsFiniteByAssumption(L)) 11474 return getCouldNotCompute(); 11475 } else if (!Stride->isOne() && !NoWrap) { 11476 auto isUBOnWrap = [&]() { 11477 // Can we prove this loop *must* be UB if overflow of IV occurs? 11478 // Reasoning goes as follows: 11479 // * Suppose the IV did self wrap. 11480 // * If Stride evenly divides the iteration space, then once wrap 11481 // occurs, the loop must revisit the same values. 11482 // * We know that RHS is invariant, and that none of those values 11483 // caused this exit to be taken previously. Thus, this exit is 11484 // dynamically dead. 11485 // * If this is the sole exit, then a dead exit implies the loop 11486 // must be infinite if there are no abnormal exits. 11487 // * If the loop were infinite, then it must either not be mustprogress 11488 // or have side effects. Otherwise, it must be UB. 11489 // * It can't (by assumption), be UB so we have contradicted our 11490 // premise and can conclude the IV did not in fact self-wrap. 11491 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 11492 // follows trivially from the fact that every (un)signed-wrapped, but 11493 // not self-wrapped value must be LT than the last value before 11494 // (un)signed wrap. Since we know that last value didn't exit, nor 11495 // will any smaller one. 11496 11497 if (!isLoopInvariant(RHS, L)) 11498 return false; 11499 11500 auto *StrideC = dyn_cast<SCEVConstant>(Stride); 11501 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 11502 return false; 11503 11504 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 11505 return false; 11506 11507 return loopIsFiniteByAssumption(L); 11508 }; 11509 11510 // Avoid proven overflow cases: this will ensure that the backedge taken 11511 // count will not generate any unsigned overflow. Relaxed no-overflow 11512 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11513 // undefined behaviors like the case of C language. 11514 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 11515 return getCouldNotCompute(); 11516 } 11517 11518 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 11519 : ICmpInst::ICMP_ULT; 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 bool NoWrap = ControlsExit && 11603 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11604 11605 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 11606 11607 // Avoid negative or zero stride values 11608 if (!isKnownPositive(Stride)) 11609 return getCouldNotCompute(); 11610 11611 // Avoid proven overflow cases: this will ensure that the backedge taken count 11612 // will not generate any unsigned overflow. Relaxed no-overflow conditions 11613 // exploit NoWrapFlags, allowing to optimize in presence of undefined 11614 // behaviors like the case of C language. 11615 if (!Stride->isOne() && !NoWrap) 11616 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 11617 return getCouldNotCompute(); 11618 11619 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 11620 : ICmpInst::ICMP_UGT; 11621 11622 const SCEV *Start = IV->getStart(); 11623 const SCEV *End = RHS; 11624 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 11625 // If we know that Start >= RHS in the context of loop, then we know that 11626 // min(RHS, Start) = RHS at this point. 11627 if (isLoopEntryGuardedByCond( 11628 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 11629 End = RHS; 11630 else 11631 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 11632 } 11633 11634 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride); 11635 11636 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 11637 : getUnsignedRangeMax(Start); 11638 11639 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 11640 : getUnsignedRangeMin(Stride); 11641 11642 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 11643 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 11644 : APInt::getMinValue(BitWidth) + (MinStride - 1); 11645 11646 // Although End can be a MIN expression we estimate MinEnd considering only 11647 // the case End = RHS. This is safe because in the other case (Start - End) 11648 // is zero, leading to a zero maximum backedge taken count. 11649 APInt MinEnd = 11650 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 11651 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 11652 11653 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 11654 ? BECount 11655 : computeBECount(getConstant(MaxStart - MinEnd), 11656 getConstant(MinStride)); 11657 11658 if (isa<SCEVCouldNotCompute>(MaxBECount)) 11659 MaxBECount = BECount; 11660 11661 return ExitLimit(BECount, MaxBECount, false, Predicates); 11662 } 11663 11664 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 11665 ScalarEvolution &SE) const { 11666 if (Range.isFullSet()) // Infinite loop. 11667 return SE.getCouldNotCompute(); 11668 11669 // If the start is a non-zero constant, shift the range to simplify things. 11670 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 11671 if (!SC->getValue()->isZero()) { 11672 SmallVector<const SCEV *, 4> Operands(operands()); 11673 Operands[0] = SE.getZero(SC->getType()); 11674 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 11675 getNoWrapFlags(FlagNW)); 11676 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 11677 return ShiftedAddRec->getNumIterationsInRange( 11678 Range.subtract(SC->getAPInt()), SE); 11679 // This is strange and shouldn't happen. 11680 return SE.getCouldNotCompute(); 11681 } 11682 11683 // The only time we can solve this is when we have all constant indices. 11684 // Otherwise, we cannot determine the overflow conditions. 11685 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 11686 return SE.getCouldNotCompute(); 11687 11688 // Okay at this point we know that all elements of the chrec are constants and 11689 // that the start element is zero. 11690 11691 // First check to see if the range contains zero. If not, the first 11692 // iteration exits. 11693 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 11694 if (!Range.contains(APInt(BitWidth, 0))) 11695 return SE.getZero(getType()); 11696 11697 if (isAffine()) { 11698 // If this is an affine expression then we have this situation: 11699 // Solve {0,+,A} in Range === Ax in Range 11700 11701 // We know that zero is in the range. If A is positive then we know that 11702 // the upper value of the range must be the first possible exit value. 11703 // If A is negative then the lower of the range is the last possible loop 11704 // value. Also note that we already checked for a full range. 11705 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11706 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11707 11708 // The exit value should be (End+A)/A. 11709 APInt ExitVal = (End + A).udiv(A); 11710 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11711 11712 // Evaluate at the exit value. If we really did fall out of the valid 11713 // range, then we computed our trip count, otherwise wrap around or other 11714 // things must have happened. 11715 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11716 if (Range.contains(Val->getValue())) 11717 return SE.getCouldNotCompute(); // Something strange happened 11718 11719 // Ensure that the previous value is in the range. This is a sanity check. 11720 assert(Range.contains( 11721 EvaluateConstantChrecAtConstant(this, 11722 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11723 "Linear scev computation is off in a bad way!"); 11724 return SE.getConstant(ExitValue); 11725 } 11726 11727 if (isQuadratic()) { 11728 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11729 return SE.getConstant(S.getValue()); 11730 } 11731 11732 return SE.getCouldNotCompute(); 11733 } 11734 11735 const SCEVAddRecExpr * 11736 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11737 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11738 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11739 // but in this case we cannot guarantee that the value returned will be an 11740 // AddRec because SCEV does not have a fixed point where it stops 11741 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11742 // may happen if we reach arithmetic depth limit while simplifying. So we 11743 // construct the returned value explicitly. 11744 SmallVector<const SCEV *, 3> Ops; 11745 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11746 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11747 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11748 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11749 // We know that the last operand is not a constant zero (otherwise it would 11750 // have been popped out earlier). This guarantees us that if the result has 11751 // the same last operand, then it will also not be popped out, meaning that 11752 // the returned value will be an AddRec. 11753 const SCEV *Last = getOperand(getNumOperands() - 1); 11754 assert(!Last->isZero() && "Recurrency with zero step?"); 11755 Ops.push_back(Last); 11756 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11757 SCEV::FlagAnyWrap)); 11758 } 11759 11760 // Return true when S contains at least an undef value. 11761 static inline bool containsUndefs(const SCEV *S) { 11762 return SCEVExprContains(S, [](const SCEV *S) { 11763 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11764 return isa<UndefValue>(SU->getValue()); 11765 return false; 11766 }); 11767 } 11768 11769 namespace { 11770 11771 // Collect all steps of SCEV expressions. 11772 struct SCEVCollectStrides { 11773 ScalarEvolution &SE; 11774 SmallVectorImpl<const SCEV *> &Strides; 11775 11776 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11777 : SE(SE), Strides(S) {} 11778 11779 bool follow(const SCEV *S) { 11780 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11781 Strides.push_back(AR->getStepRecurrence(SE)); 11782 return true; 11783 } 11784 11785 bool isDone() const { return false; } 11786 }; 11787 11788 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11789 struct SCEVCollectTerms { 11790 SmallVectorImpl<const SCEV *> &Terms; 11791 11792 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11793 11794 bool follow(const SCEV *S) { 11795 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11796 isa<SCEVSignExtendExpr>(S)) { 11797 if (!containsUndefs(S)) 11798 Terms.push_back(S); 11799 11800 // Stop recursion: once we collected a term, do not walk its operands. 11801 return false; 11802 } 11803 11804 // Keep looking. 11805 return true; 11806 } 11807 11808 bool isDone() const { return false; } 11809 }; 11810 11811 // Check if a SCEV contains an AddRecExpr. 11812 struct SCEVHasAddRec { 11813 bool &ContainsAddRec; 11814 11815 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11816 ContainsAddRec = false; 11817 } 11818 11819 bool follow(const SCEV *S) { 11820 if (isa<SCEVAddRecExpr>(S)) { 11821 ContainsAddRec = true; 11822 11823 // Stop recursion: once we collected a term, do not walk its operands. 11824 return false; 11825 } 11826 11827 // Keep looking. 11828 return true; 11829 } 11830 11831 bool isDone() const { return false; } 11832 }; 11833 11834 // Find factors that are multiplied with an expression that (possibly as a 11835 // subexpression) contains an AddRecExpr. In the expression: 11836 // 11837 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11838 // 11839 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11840 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11841 // parameters as they form a product with an induction variable. 11842 // 11843 // This collector expects all array size parameters to be in the same MulExpr. 11844 // It might be necessary to later add support for collecting parameters that are 11845 // spread over different nested MulExpr. 11846 struct SCEVCollectAddRecMultiplies { 11847 SmallVectorImpl<const SCEV *> &Terms; 11848 ScalarEvolution &SE; 11849 11850 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11851 : Terms(T), SE(SE) {} 11852 11853 bool follow(const SCEV *S) { 11854 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11855 bool HasAddRec = false; 11856 SmallVector<const SCEV *, 0> Operands; 11857 for (auto Op : Mul->operands()) { 11858 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11859 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11860 Operands.push_back(Op); 11861 } else if (Unknown) { 11862 HasAddRec = true; 11863 } else { 11864 bool ContainsAddRec = false; 11865 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11866 visitAll(Op, ContiansAddRec); 11867 HasAddRec |= ContainsAddRec; 11868 } 11869 } 11870 if (Operands.size() == 0) 11871 return true; 11872 11873 if (!HasAddRec) 11874 return false; 11875 11876 Terms.push_back(SE.getMulExpr(Operands)); 11877 // Stop recursion: once we collected a term, do not walk its operands. 11878 return false; 11879 } 11880 11881 // Keep looking. 11882 return true; 11883 } 11884 11885 bool isDone() const { return false; } 11886 }; 11887 11888 } // end anonymous namespace 11889 11890 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11891 /// two places: 11892 /// 1) The strides of AddRec expressions. 11893 /// 2) Unknowns that are multiplied with AddRec expressions. 11894 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11895 SmallVectorImpl<const SCEV *> &Terms) { 11896 SmallVector<const SCEV *, 4> Strides; 11897 SCEVCollectStrides StrideCollector(*this, Strides); 11898 visitAll(Expr, StrideCollector); 11899 11900 LLVM_DEBUG({ 11901 dbgs() << "Strides:\n"; 11902 for (const SCEV *S : Strides) 11903 dbgs() << *S << "\n"; 11904 }); 11905 11906 for (const SCEV *S : Strides) { 11907 SCEVCollectTerms TermCollector(Terms); 11908 visitAll(S, TermCollector); 11909 } 11910 11911 LLVM_DEBUG({ 11912 dbgs() << "Terms:\n"; 11913 for (const SCEV *T : Terms) 11914 dbgs() << *T << "\n"; 11915 }); 11916 11917 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11918 visitAll(Expr, MulCollector); 11919 } 11920 11921 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11922 SmallVectorImpl<const SCEV *> &Terms, 11923 SmallVectorImpl<const SCEV *> &Sizes) { 11924 int Last = Terms.size() - 1; 11925 const SCEV *Step = Terms[Last]; 11926 11927 // End of recursion. 11928 if (Last == 0) { 11929 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11930 SmallVector<const SCEV *, 2> Qs; 11931 for (const SCEV *Op : M->operands()) 11932 if (!isa<SCEVConstant>(Op)) 11933 Qs.push_back(Op); 11934 11935 Step = SE.getMulExpr(Qs); 11936 } 11937 11938 Sizes.push_back(Step); 11939 return true; 11940 } 11941 11942 for (const SCEV *&Term : Terms) { 11943 // Normalize the terms before the next call to findArrayDimensionsRec. 11944 const SCEV *Q, *R; 11945 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11946 11947 // Bail out when GCD does not evenly divide one of the terms. 11948 if (!R->isZero()) 11949 return false; 11950 11951 Term = Q; 11952 } 11953 11954 // Remove all SCEVConstants. 11955 erase_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }); 11956 11957 if (Terms.size() > 0) 11958 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11959 return false; 11960 11961 Sizes.push_back(Step); 11962 return true; 11963 } 11964 11965 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11966 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11967 for (const SCEV *T : Terms) 11968 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11969 return true; 11970 11971 return false; 11972 } 11973 11974 // Return the number of product terms in S. 11975 static inline int numberOfTerms(const SCEV *S) { 11976 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11977 return Expr->getNumOperands(); 11978 return 1; 11979 } 11980 11981 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11982 if (isa<SCEVConstant>(T)) 11983 return nullptr; 11984 11985 if (isa<SCEVUnknown>(T)) 11986 return T; 11987 11988 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11989 SmallVector<const SCEV *, 2> Factors; 11990 for (const SCEV *Op : M->operands()) 11991 if (!isa<SCEVConstant>(Op)) 11992 Factors.push_back(Op); 11993 11994 return SE.getMulExpr(Factors); 11995 } 11996 11997 return T; 11998 } 11999 12000 /// Return the size of an element read or written by Inst. 12001 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12002 Type *Ty; 12003 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12004 Ty = Store->getValueOperand()->getType(); 12005 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12006 Ty = Load->getType(); 12007 else 12008 return nullptr; 12009 12010 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12011 return getSizeOfExpr(ETy, Ty); 12012 } 12013 12014 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 12015 SmallVectorImpl<const SCEV *> &Sizes, 12016 const SCEV *ElementSize) { 12017 if (Terms.size() < 1 || !ElementSize) 12018 return; 12019 12020 // Early return when Terms do not contain parameters: we do not delinearize 12021 // non parametric SCEVs. 12022 if (!containsParameters(Terms)) 12023 return; 12024 12025 LLVM_DEBUG({ 12026 dbgs() << "Terms:\n"; 12027 for (const SCEV *T : Terms) 12028 dbgs() << *T << "\n"; 12029 }); 12030 12031 // Remove duplicates. 12032 array_pod_sort(Terms.begin(), Terms.end()); 12033 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 12034 12035 // Put larger terms first. 12036 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 12037 return numberOfTerms(LHS) > numberOfTerms(RHS); 12038 }); 12039 12040 // Try to divide all terms by the element size. If term is not divisible by 12041 // element size, proceed with the original term. 12042 for (const SCEV *&Term : Terms) { 12043 const SCEV *Q, *R; 12044 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 12045 if (!Q->isZero()) 12046 Term = Q; 12047 } 12048 12049 SmallVector<const SCEV *, 4> NewTerms; 12050 12051 // Remove constant factors. 12052 for (const SCEV *T : Terms) 12053 if (const SCEV *NewT = removeConstantFactors(*this, T)) 12054 NewTerms.push_back(NewT); 12055 12056 LLVM_DEBUG({ 12057 dbgs() << "Terms after sorting:\n"; 12058 for (const SCEV *T : NewTerms) 12059 dbgs() << *T << "\n"; 12060 }); 12061 12062 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 12063 Sizes.clear(); 12064 return; 12065 } 12066 12067 // The last element to be pushed into Sizes is the size of an element. 12068 Sizes.push_back(ElementSize); 12069 12070 LLVM_DEBUG({ 12071 dbgs() << "Sizes:\n"; 12072 for (const SCEV *S : Sizes) 12073 dbgs() << *S << "\n"; 12074 }); 12075 } 12076 12077 void ScalarEvolution::computeAccessFunctions( 12078 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 12079 SmallVectorImpl<const SCEV *> &Sizes) { 12080 // Early exit in case this SCEV is not an affine multivariate function. 12081 if (Sizes.empty()) 12082 return; 12083 12084 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 12085 if (!AR->isAffine()) 12086 return; 12087 12088 const SCEV *Res = Expr; 12089 int Last = Sizes.size() - 1; 12090 for (int i = Last; i >= 0; i--) { 12091 const SCEV *Q, *R; 12092 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 12093 12094 LLVM_DEBUG({ 12095 dbgs() << "Res: " << *Res << "\n"; 12096 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 12097 dbgs() << "Res divided by Sizes[i]:\n"; 12098 dbgs() << "Quotient: " << *Q << "\n"; 12099 dbgs() << "Remainder: " << *R << "\n"; 12100 }); 12101 12102 Res = Q; 12103 12104 // Do not record the last subscript corresponding to the size of elements in 12105 // the array. 12106 if (i == Last) { 12107 12108 // Bail out if the remainder is too complex. 12109 if (isa<SCEVAddRecExpr>(R)) { 12110 Subscripts.clear(); 12111 Sizes.clear(); 12112 return; 12113 } 12114 12115 continue; 12116 } 12117 12118 // Record the access function for the current subscript. 12119 Subscripts.push_back(R); 12120 } 12121 12122 // Also push in last position the remainder of the last division: it will be 12123 // the access function of the innermost dimension. 12124 Subscripts.push_back(Res); 12125 12126 std::reverse(Subscripts.begin(), Subscripts.end()); 12127 12128 LLVM_DEBUG({ 12129 dbgs() << "Subscripts:\n"; 12130 for (const SCEV *S : Subscripts) 12131 dbgs() << *S << "\n"; 12132 }); 12133 } 12134 12135 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 12136 /// sizes of an array access. Returns the remainder of the delinearization that 12137 /// is the offset start of the array. The SCEV->delinearize algorithm computes 12138 /// the multiples of SCEV coefficients: that is a pattern matching of sub 12139 /// expressions in the stride and base of a SCEV corresponding to the 12140 /// computation of a GCD (greatest common divisor) of base and stride. When 12141 /// SCEV->delinearize fails, it returns the SCEV unchanged. 12142 /// 12143 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 12144 /// 12145 /// void foo(long n, long m, long o, double A[n][m][o]) { 12146 /// 12147 /// for (long i = 0; i < n; i++) 12148 /// for (long j = 0; j < m; j++) 12149 /// for (long k = 0; k < o; k++) 12150 /// A[i][j][k] = 1.0; 12151 /// } 12152 /// 12153 /// the delinearization input is the following AddRec SCEV: 12154 /// 12155 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 12156 /// 12157 /// From this SCEV, we are able to say that the base offset of the access is %A 12158 /// because it appears as an offset that does not divide any of the strides in 12159 /// the loops: 12160 /// 12161 /// CHECK: Base offset: %A 12162 /// 12163 /// and then SCEV->delinearize determines the size of some of the dimensions of 12164 /// the array as these are the multiples by which the strides are happening: 12165 /// 12166 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 12167 /// 12168 /// Note that the outermost dimension remains of UnknownSize because there are 12169 /// no strides that would help identifying the size of the last dimension: when 12170 /// the array has been statically allocated, one could compute the size of that 12171 /// dimension by dividing the overall size of the array by the size of the known 12172 /// dimensions: %m * %o * 8. 12173 /// 12174 /// Finally delinearize provides the access functions for the array reference 12175 /// that does correspond to A[i][j][k] of the above C testcase: 12176 /// 12177 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 12178 /// 12179 /// The testcases are checking the output of a function pass: 12180 /// DelinearizationPass that walks through all loads and stores of a function 12181 /// asking for the SCEV of the memory access with respect to all enclosing 12182 /// loops, calling SCEV->delinearize on that and printing the results. 12183 void ScalarEvolution::delinearize(const SCEV *Expr, 12184 SmallVectorImpl<const SCEV *> &Subscripts, 12185 SmallVectorImpl<const SCEV *> &Sizes, 12186 const SCEV *ElementSize) { 12187 // First step: collect parametric terms. 12188 SmallVector<const SCEV *, 4> Terms; 12189 collectParametricTerms(Expr, Terms); 12190 12191 if (Terms.empty()) 12192 return; 12193 12194 // Second step: find subscript sizes. 12195 findArrayDimensions(Terms, Sizes, ElementSize); 12196 12197 if (Sizes.empty()) 12198 return; 12199 12200 // Third step: compute the access functions for each subscript. 12201 computeAccessFunctions(Expr, Subscripts, Sizes); 12202 12203 if (Subscripts.empty()) 12204 return; 12205 12206 LLVM_DEBUG({ 12207 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 12208 dbgs() << "ArrayDecl[UnknownSize]"; 12209 for (const SCEV *S : Sizes) 12210 dbgs() << "[" << *S << "]"; 12211 12212 dbgs() << "\nArrayRef"; 12213 for (const SCEV *S : Subscripts) 12214 dbgs() << "[" << *S << "]"; 12215 dbgs() << "\n"; 12216 }); 12217 } 12218 12219 bool ScalarEvolution::getIndexExpressionsFromGEP( 12220 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 12221 SmallVectorImpl<int> &Sizes) { 12222 assert(Subscripts.empty() && Sizes.empty() && 12223 "Expected output lists to be empty on entry to this function."); 12224 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 12225 Type *Ty = GEP->getPointerOperandType(); 12226 bool DroppedFirstDim = false; 12227 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 12228 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 12229 if (i == 1) { 12230 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 12231 Ty = PtrTy->getElementType(); 12232 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 12233 Ty = ArrayTy->getElementType(); 12234 } else { 12235 Subscripts.clear(); 12236 Sizes.clear(); 12237 return false; 12238 } 12239 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 12240 if (Const->getValue()->isZero()) { 12241 DroppedFirstDim = true; 12242 continue; 12243 } 12244 Subscripts.push_back(Expr); 12245 continue; 12246 } 12247 12248 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 12249 if (!ArrayTy) { 12250 Subscripts.clear(); 12251 Sizes.clear(); 12252 return false; 12253 } 12254 12255 Subscripts.push_back(Expr); 12256 if (!(DroppedFirstDim && i == 2)) 12257 Sizes.push_back(ArrayTy->getNumElements()); 12258 12259 Ty = ArrayTy->getElementType(); 12260 } 12261 return !Subscripts.empty(); 12262 } 12263 12264 //===----------------------------------------------------------------------===// 12265 // SCEVCallbackVH Class Implementation 12266 //===----------------------------------------------------------------------===// 12267 12268 void ScalarEvolution::SCEVCallbackVH::deleted() { 12269 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12270 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12271 SE->ConstantEvolutionLoopExitValue.erase(PN); 12272 SE->eraseValueFromMap(getValPtr()); 12273 // this now dangles! 12274 } 12275 12276 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12277 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12278 12279 // Forget all the expressions associated with users of the old value, 12280 // so that future queries will recompute the expressions using the new 12281 // value. 12282 Value *Old = getValPtr(); 12283 SmallVector<User *, 16> Worklist(Old->users()); 12284 SmallPtrSet<User *, 8> Visited; 12285 while (!Worklist.empty()) { 12286 User *U = Worklist.pop_back_val(); 12287 // Deleting the Old value will cause this to dangle. Postpone 12288 // that until everything else is done. 12289 if (U == Old) 12290 continue; 12291 if (!Visited.insert(U).second) 12292 continue; 12293 if (PHINode *PN = dyn_cast<PHINode>(U)) 12294 SE->ConstantEvolutionLoopExitValue.erase(PN); 12295 SE->eraseValueFromMap(U); 12296 llvm::append_range(Worklist, U->users()); 12297 } 12298 // Delete the Old value. 12299 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12300 SE->ConstantEvolutionLoopExitValue.erase(PN); 12301 SE->eraseValueFromMap(Old); 12302 // this now dangles! 12303 } 12304 12305 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12306 : CallbackVH(V), SE(se) {} 12307 12308 //===----------------------------------------------------------------------===// 12309 // ScalarEvolution Class Implementation 12310 //===----------------------------------------------------------------------===// 12311 12312 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12313 AssumptionCache &AC, DominatorTree &DT, 12314 LoopInfo &LI) 12315 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12316 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12317 LoopDispositions(64), BlockDispositions(64) { 12318 // To use guards for proving predicates, we need to scan every instruction in 12319 // relevant basic blocks, and not just terminators. Doing this is a waste of 12320 // time if the IR does not actually contain any calls to 12321 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12322 // 12323 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12324 // to _add_ guards to the module when there weren't any before, and wants 12325 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12326 // efficient in lieu of being smart in that rather obscure case. 12327 12328 auto *GuardDecl = F.getParent()->getFunction( 12329 Intrinsic::getName(Intrinsic::experimental_guard)); 12330 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12331 } 12332 12333 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12334 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12335 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12336 ValueExprMap(std::move(Arg.ValueExprMap)), 12337 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12338 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12339 PendingMerges(std::move(Arg.PendingMerges)), 12340 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12341 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12342 PredicatedBackedgeTakenCounts( 12343 std::move(Arg.PredicatedBackedgeTakenCounts)), 12344 ConstantEvolutionLoopExitValue( 12345 std::move(Arg.ConstantEvolutionLoopExitValue)), 12346 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12347 LoopDispositions(std::move(Arg.LoopDispositions)), 12348 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12349 BlockDispositions(std::move(Arg.BlockDispositions)), 12350 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12351 SignedRanges(std::move(Arg.SignedRanges)), 12352 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12353 UniquePreds(std::move(Arg.UniquePreds)), 12354 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12355 LoopUsers(std::move(Arg.LoopUsers)), 12356 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12357 FirstUnknown(Arg.FirstUnknown) { 12358 Arg.FirstUnknown = nullptr; 12359 } 12360 12361 ScalarEvolution::~ScalarEvolution() { 12362 // Iterate through all the SCEVUnknown instances and call their 12363 // destructors, so that they release their references to their values. 12364 for (SCEVUnknown *U = FirstUnknown; U;) { 12365 SCEVUnknown *Tmp = U; 12366 U = U->Next; 12367 Tmp->~SCEVUnknown(); 12368 } 12369 FirstUnknown = nullptr; 12370 12371 ExprValueMap.clear(); 12372 ValueExprMap.clear(); 12373 HasRecMap.clear(); 12374 BackedgeTakenCounts.clear(); 12375 PredicatedBackedgeTakenCounts.clear(); 12376 12377 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12378 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12379 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12380 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12381 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12382 } 12383 12384 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12385 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12386 } 12387 12388 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12389 const Loop *L) { 12390 // Print all inner loops first 12391 for (Loop *I : *L) 12392 PrintLoopInfo(OS, SE, I); 12393 12394 OS << "Loop "; 12395 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12396 OS << ": "; 12397 12398 SmallVector<BasicBlock *, 8> ExitingBlocks; 12399 L->getExitingBlocks(ExitingBlocks); 12400 if (ExitingBlocks.size() != 1) 12401 OS << "<multiple exits> "; 12402 12403 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12404 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12405 else 12406 OS << "Unpredictable backedge-taken count.\n"; 12407 12408 if (ExitingBlocks.size() > 1) 12409 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12410 OS << " exit count for " << ExitingBlock->getName() << ": " 12411 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12412 } 12413 12414 OS << "Loop "; 12415 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12416 OS << ": "; 12417 12418 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 12419 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12420 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12421 OS << ", actual taken count either this or zero."; 12422 } else { 12423 OS << "Unpredictable max backedge-taken count. "; 12424 } 12425 12426 OS << "\n" 12427 "Loop "; 12428 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12429 OS << ": "; 12430 12431 SCEVUnionPredicate Pred; 12432 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12433 if (!isa<SCEVCouldNotCompute>(PBT)) { 12434 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12435 OS << " Predicates:\n"; 12436 Pred.print(OS, 4); 12437 } else { 12438 OS << "Unpredictable predicated backedge-taken count. "; 12439 } 12440 OS << "\n"; 12441 12442 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12443 OS << "Loop "; 12444 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12445 OS << ": "; 12446 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12447 } 12448 } 12449 12450 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12451 switch (LD) { 12452 case ScalarEvolution::LoopVariant: 12453 return "Variant"; 12454 case ScalarEvolution::LoopInvariant: 12455 return "Invariant"; 12456 case ScalarEvolution::LoopComputable: 12457 return "Computable"; 12458 } 12459 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12460 } 12461 12462 void ScalarEvolution::print(raw_ostream &OS) const { 12463 // ScalarEvolution's implementation of the print method is to print 12464 // out SCEV values of all instructions that are interesting. Doing 12465 // this potentially causes it to create new SCEV objects though, 12466 // which technically conflicts with the const qualifier. This isn't 12467 // observable from outside the class though, so casting away the 12468 // const isn't dangerous. 12469 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12470 12471 if (ClassifyExpressions) { 12472 OS << "Classifying expressions for: "; 12473 F.printAsOperand(OS, /*PrintType=*/false); 12474 OS << "\n"; 12475 for (Instruction &I : instructions(F)) 12476 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12477 OS << I << '\n'; 12478 OS << " --> "; 12479 const SCEV *SV = SE.getSCEV(&I); 12480 SV->print(OS); 12481 if (!isa<SCEVCouldNotCompute>(SV)) { 12482 OS << " U: "; 12483 SE.getUnsignedRange(SV).print(OS); 12484 OS << " S: "; 12485 SE.getSignedRange(SV).print(OS); 12486 } 12487 12488 const Loop *L = LI.getLoopFor(I.getParent()); 12489 12490 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12491 if (AtUse != SV) { 12492 OS << " --> "; 12493 AtUse->print(OS); 12494 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12495 OS << " U: "; 12496 SE.getUnsignedRange(AtUse).print(OS); 12497 OS << " S: "; 12498 SE.getSignedRange(AtUse).print(OS); 12499 } 12500 } 12501 12502 if (L) { 12503 OS << "\t\t" "Exits: "; 12504 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12505 if (!SE.isLoopInvariant(ExitValue, L)) { 12506 OS << "<<Unknown>>"; 12507 } else { 12508 OS << *ExitValue; 12509 } 12510 12511 bool First = true; 12512 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12513 if (First) { 12514 OS << "\t\t" "LoopDispositions: { "; 12515 First = false; 12516 } else { 12517 OS << ", "; 12518 } 12519 12520 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12521 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12522 } 12523 12524 for (auto *InnerL : depth_first(L)) { 12525 if (InnerL == L) 12526 continue; 12527 if (First) { 12528 OS << "\t\t" "LoopDispositions: { "; 12529 First = false; 12530 } else { 12531 OS << ", "; 12532 } 12533 12534 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12535 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12536 } 12537 12538 OS << " }"; 12539 } 12540 12541 OS << "\n"; 12542 } 12543 } 12544 12545 OS << "Determining loop execution counts for: "; 12546 F.printAsOperand(OS, /*PrintType=*/false); 12547 OS << "\n"; 12548 for (Loop *I : LI) 12549 PrintLoopInfo(OS, &SE, I); 12550 } 12551 12552 ScalarEvolution::LoopDisposition 12553 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12554 auto &Values = LoopDispositions[S]; 12555 for (auto &V : Values) { 12556 if (V.getPointer() == L) 12557 return V.getInt(); 12558 } 12559 Values.emplace_back(L, LoopVariant); 12560 LoopDisposition D = computeLoopDisposition(S, L); 12561 auto &Values2 = LoopDispositions[S]; 12562 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12563 if (V.getPointer() == L) { 12564 V.setInt(D); 12565 break; 12566 } 12567 } 12568 return D; 12569 } 12570 12571 ScalarEvolution::LoopDisposition 12572 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12573 switch (S->getSCEVType()) { 12574 case scConstant: 12575 return LoopInvariant; 12576 case scPtrToInt: 12577 case scTruncate: 12578 case scZeroExtend: 12579 case scSignExtend: 12580 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12581 case scAddRecExpr: { 12582 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12583 12584 // If L is the addrec's loop, it's computable. 12585 if (AR->getLoop() == L) 12586 return LoopComputable; 12587 12588 // Add recurrences are never invariant in the function-body (null loop). 12589 if (!L) 12590 return LoopVariant; 12591 12592 // Everything that is not defined at loop entry is variant. 12593 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12594 return LoopVariant; 12595 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12596 " dominate the contained loop's header?"); 12597 12598 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12599 if (AR->getLoop()->contains(L)) 12600 return LoopInvariant; 12601 12602 // This recurrence is variant w.r.t. L if any of its operands 12603 // are variant. 12604 for (auto *Op : AR->operands()) 12605 if (!isLoopInvariant(Op, L)) 12606 return LoopVariant; 12607 12608 // Otherwise it's loop-invariant. 12609 return LoopInvariant; 12610 } 12611 case scAddExpr: 12612 case scMulExpr: 12613 case scUMaxExpr: 12614 case scSMaxExpr: 12615 case scUMinExpr: 12616 case scSMinExpr: { 12617 bool HasVarying = false; 12618 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12619 LoopDisposition D = getLoopDisposition(Op, L); 12620 if (D == LoopVariant) 12621 return LoopVariant; 12622 if (D == LoopComputable) 12623 HasVarying = true; 12624 } 12625 return HasVarying ? LoopComputable : LoopInvariant; 12626 } 12627 case scUDivExpr: { 12628 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12629 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12630 if (LD == LoopVariant) 12631 return LoopVariant; 12632 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12633 if (RD == LoopVariant) 12634 return LoopVariant; 12635 return (LD == LoopInvariant && RD == LoopInvariant) ? 12636 LoopInvariant : LoopComputable; 12637 } 12638 case scUnknown: 12639 // All non-instruction values are loop invariant. All instructions are loop 12640 // invariant if they are not contained in the specified loop. 12641 // Instructions are never considered invariant in the function body 12642 // (null loop) because they are defined within the "loop". 12643 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12644 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12645 return LoopInvariant; 12646 case scCouldNotCompute: 12647 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12648 } 12649 llvm_unreachable("Unknown SCEV kind!"); 12650 } 12651 12652 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12653 return getLoopDisposition(S, L) == LoopInvariant; 12654 } 12655 12656 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12657 return getLoopDisposition(S, L) == LoopComputable; 12658 } 12659 12660 ScalarEvolution::BlockDisposition 12661 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12662 auto &Values = BlockDispositions[S]; 12663 for (auto &V : Values) { 12664 if (V.getPointer() == BB) 12665 return V.getInt(); 12666 } 12667 Values.emplace_back(BB, DoesNotDominateBlock); 12668 BlockDisposition D = computeBlockDisposition(S, BB); 12669 auto &Values2 = BlockDispositions[S]; 12670 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12671 if (V.getPointer() == BB) { 12672 V.setInt(D); 12673 break; 12674 } 12675 } 12676 return D; 12677 } 12678 12679 ScalarEvolution::BlockDisposition 12680 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12681 switch (S->getSCEVType()) { 12682 case scConstant: 12683 return ProperlyDominatesBlock; 12684 case scPtrToInt: 12685 case scTruncate: 12686 case scZeroExtend: 12687 case scSignExtend: 12688 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12689 case scAddRecExpr: { 12690 // This uses a "dominates" query instead of "properly dominates" query 12691 // to test for proper dominance too, because the instruction which 12692 // produces the addrec's value is a PHI, and a PHI effectively properly 12693 // dominates its entire containing block. 12694 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12695 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12696 return DoesNotDominateBlock; 12697 12698 // Fall through into SCEVNAryExpr handling. 12699 LLVM_FALLTHROUGH; 12700 } 12701 case scAddExpr: 12702 case scMulExpr: 12703 case scUMaxExpr: 12704 case scSMaxExpr: 12705 case scUMinExpr: 12706 case scSMinExpr: { 12707 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12708 bool Proper = true; 12709 for (const SCEV *NAryOp : NAry->operands()) { 12710 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12711 if (D == DoesNotDominateBlock) 12712 return DoesNotDominateBlock; 12713 if (D == DominatesBlock) 12714 Proper = false; 12715 } 12716 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12717 } 12718 case scUDivExpr: { 12719 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12720 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12721 BlockDisposition LD = getBlockDisposition(LHS, BB); 12722 if (LD == DoesNotDominateBlock) 12723 return DoesNotDominateBlock; 12724 BlockDisposition RD = getBlockDisposition(RHS, BB); 12725 if (RD == DoesNotDominateBlock) 12726 return DoesNotDominateBlock; 12727 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12728 ProperlyDominatesBlock : DominatesBlock; 12729 } 12730 case scUnknown: 12731 if (Instruction *I = 12732 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12733 if (I->getParent() == BB) 12734 return DominatesBlock; 12735 if (DT.properlyDominates(I->getParent(), BB)) 12736 return ProperlyDominatesBlock; 12737 return DoesNotDominateBlock; 12738 } 12739 return ProperlyDominatesBlock; 12740 case scCouldNotCompute: 12741 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12742 } 12743 llvm_unreachable("Unknown SCEV kind!"); 12744 } 12745 12746 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12747 return getBlockDisposition(S, BB) >= DominatesBlock; 12748 } 12749 12750 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12751 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12752 } 12753 12754 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12755 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12756 } 12757 12758 void 12759 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12760 ValuesAtScopes.erase(S); 12761 LoopDispositions.erase(S); 12762 BlockDispositions.erase(S); 12763 UnsignedRanges.erase(S); 12764 SignedRanges.erase(S); 12765 ExprValueMap.erase(S); 12766 HasRecMap.erase(S); 12767 MinTrailingZerosCache.erase(S); 12768 12769 for (auto I = PredicatedSCEVRewrites.begin(); 12770 I != PredicatedSCEVRewrites.end();) { 12771 std::pair<const SCEV *, const Loop *> Entry = I->first; 12772 if (Entry.first == S) 12773 PredicatedSCEVRewrites.erase(I++); 12774 else 12775 ++I; 12776 } 12777 12778 auto RemoveSCEVFromBackedgeMap = 12779 [S](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12780 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12781 BackedgeTakenInfo &BEInfo = I->second; 12782 if (BEInfo.hasOperand(S)) 12783 Map.erase(I++); 12784 else 12785 ++I; 12786 } 12787 }; 12788 12789 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12790 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12791 } 12792 12793 void 12794 ScalarEvolution::getUsedLoops(const SCEV *S, 12795 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12796 struct FindUsedLoops { 12797 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12798 : LoopsUsed(LoopsUsed) {} 12799 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12800 bool follow(const SCEV *S) { 12801 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12802 LoopsUsed.insert(AR->getLoop()); 12803 return true; 12804 } 12805 12806 bool isDone() const { return false; } 12807 }; 12808 12809 FindUsedLoops F(LoopsUsed); 12810 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12811 } 12812 12813 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12814 SmallPtrSet<const Loop *, 8> LoopsUsed; 12815 getUsedLoops(S, LoopsUsed); 12816 for (auto *L : LoopsUsed) 12817 LoopUsers[L].push_back(S); 12818 } 12819 12820 void ScalarEvolution::verify() const { 12821 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12822 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12823 12824 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12825 12826 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12827 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12828 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12829 12830 const SCEV *visitConstant(const SCEVConstant *Constant) { 12831 return SE.getConstant(Constant->getAPInt()); 12832 } 12833 12834 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12835 return SE.getUnknown(Expr->getValue()); 12836 } 12837 12838 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12839 return SE.getCouldNotCompute(); 12840 } 12841 }; 12842 12843 SCEVMapper SCM(SE2); 12844 12845 while (!LoopStack.empty()) { 12846 auto *L = LoopStack.pop_back_val(); 12847 llvm::append_range(LoopStack, *L); 12848 12849 auto *CurBECount = SCM.visit( 12850 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12851 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12852 12853 if (CurBECount == SE2.getCouldNotCompute() || 12854 NewBECount == SE2.getCouldNotCompute()) { 12855 // NB! This situation is legal, but is very suspicious -- whatever pass 12856 // change the loop to make a trip count go from could not compute to 12857 // computable or vice-versa *should have* invalidated SCEV. However, we 12858 // choose not to assert here (for now) since we don't want false 12859 // positives. 12860 continue; 12861 } 12862 12863 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12864 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12865 // not propagate undef aggressively). This means we can (and do) fail 12866 // verification in cases where a transform makes the trip count of a loop 12867 // go from "undef" to "undef+1" (say). The transform is fine, since in 12868 // both cases the loop iterates "undef" times, but SCEV thinks we 12869 // increased the trip count of the loop by 1 incorrectly. 12870 continue; 12871 } 12872 12873 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12874 SE.getTypeSizeInBits(NewBECount->getType())) 12875 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12876 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12877 SE.getTypeSizeInBits(NewBECount->getType())) 12878 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12879 12880 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12881 12882 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12883 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12884 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12885 dbgs() << "Old: " << *CurBECount << "\n"; 12886 dbgs() << "New: " << *NewBECount << "\n"; 12887 dbgs() << "Delta: " << *Delta << "\n"; 12888 std::abort(); 12889 } 12890 } 12891 12892 // Collect all valid loops currently in LoopInfo. 12893 SmallPtrSet<Loop *, 32> ValidLoops; 12894 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12895 while (!Worklist.empty()) { 12896 Loop *L = Worklist.pop_back_val(); 12897 if (ValidLoops.contains(L)) 12898 continue; 12899 ValidLoops.insert(L); 12900 Worklist.append(L->begin(), L->end()); 12901 } 12902 // Check for SCEV expressions referencing invalid/deleted loops. 12903 for (auto &KV : ValueExprMap) { 12904 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12905 if (!AR) 12906 continue; 12907 assert(ValidLoops.contains(AR->getLoop()) && 12908 "AddRec references invalid loop"); 12909 } 12910 } 12911 12912 bool ScalarEvolution::invalidate( 12913 Function &F, const PreservedAnalyses &PA, 12914 FunctionAnalysisManager::Invalidator &Inv) { 12915 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12916 // of its dependencies is invalidated. 12917 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12918 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12919 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12920 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12921 Inv.invalidate<LoopAnalysis>(F, PA); 12922 } 12923 12924 AnalysisKey ScalarEvolutionAnalysis::Key; 12925 12926 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12927 FunctionAnalysisManager &AM) { 12928 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12929 AM.getResult<AssumptionAnalysis>(F), 12930 AM.getResult<DominatorTreeAnalysis>(F), 12931 AM.getResult<LoopAnalysis>(F)); 12932 } 12933 12934 PreservedAnalyses 12935 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12936 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12937 return PreservedAnalyses::all(); 12938 } 12939 12940 PreservedAnalyses 12941 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12942 // For compatibility with opt's -analyze feature under legacy pass manager 12943 // which was not ported to NPM. This keeps tests using 12944 // update_analyze_test_checks.py working. 12945 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12946 << F.getName() << "':\n"; 12947 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12948 return PreservedAnalyses::all(); 12949 } 12950 12951 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12952 "Scalar Evolution Analysis", false, true) 12953 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12954 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12955 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12956 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12957 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12958 "Scalar Evolution Analysis", false, true) 12959 12960 char ScalarEvolutionWrapperPass::ID = 0; 12961 12962 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12963 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12964 } 12965 12966 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12967 SE.reset(new ScalarEvolution( 12968 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12969 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12970 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12971 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12972 return false; 12973 } 12974 12975 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12976 12977 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12978 SE->print(OS); 12979 } 12980 12981 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12982 if (!VerifySCEV) 12983 return; 12984 12985 SE->verify(); 12986 } 12987 12988 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12989 AU.setPreservesAll(); 12990 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12991 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12992 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12993 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12994 } 12995 12996 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12997 const SCEV *RHS) { 12998 FoldingSetNodeID ID; 12999 assert(LHS->getType() == RHS->getType() && 13000 "Type mismatch between LHS and RHS"); 13001 // Unique this node based on the arguments 13002 ID.AddInteger(SCEVPredicate::P_Equal); 13003 ID.AddPointer(LHS); 13004 ID.AddPointer(RHS); 13005 void *IP = nullptr; 13006 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13007 return S; 13008 SCEVEqualPredicate *Eq = new (SCEVAllocator) 13009 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 13010 UniquePreds.InsertNode(Eq, IP); 13011 return Eq; 13012 } 13013 13014 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13015 const SCEVAddRecExpr *AR, 13016 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13017 FoldingSetNodeID ID; 13018 // Unique this node based on the arguments 13019 ID.AddInteger(SCEVPredicate::P_Wrap); 13020 ID.AddPointer(AR); 13021 ID.AddInteger(AddedFlags); 13022 void *IP = nullptr; 13023 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13024 return S; 13025 auto *OF = new (SCEVAllocator) 13026 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13027 UniquePreds.InsertNode(OF, IP); 13028 return OF; 13029 } 13030 13031 namespace { 13032 13033 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13034 public: 13035 13036 /// Rewrites \p S in the context of a loop L and the SCEV predication 13037 /// infrastructure. 13038 /// 13039 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13040 /// equivalences present in \p Pred. 13041 /// 13042 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13043 /// \p NewPreds such that the result will be an AddRecExpr. 13044 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13045 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13046 SCEVUnionPredicate *Pred) { 13047 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13048 return Rewriter.visit(S); 13049 } 13050 13051 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13052 if (Pred) { 13053 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 13054 for (auto *Pred : ExprPreds) 13055 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 13056 if (IPred->getLHS() == Expr) 13057 return IPred->getRHS(); 13058 } 13059 return convertToAddRecWithPreds(Expr); 13060 } 13061 13062 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13063 const SCEV *Operand = visit(Expr->getOperand()); 13064 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13065 if (AR && AR->getLoop() == L && AR->isAffine()) { 13066 // This couldn't be folded because the operand didn't have the nuw 13067 // flag. Add the nusw flag as an assumption that we could make. 13068 const SCEV *Step = AR->getStepRecurrence(SE); 13069 Type *Ty = Expr->getType(); 13070 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13071 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13072 SE.getSignExtendExpr(Step, Ty), L, 13073 AR->getNoWrapFlags()); 13074 } 13075 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13076 } 13077 13078 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13079 const SCEV *Operand = visit(Expr->getOperand()); 13080 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13081 if (AR && AR->getLoop() == L && AR->isAffine()) { 13082 // This couldn't be folded because the operand didn't have the nsw 13083 // flag. Add the nssw flag as an assumption that we could make. 13084 const SCEV *Step = AR->getStepRecurrence(SE); 13085 Type *Ty = Expr->getType(); 13086 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13087 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13088 SE.getSignExtendExpr(Step, Ty), L, 13089 AR->getNoWrapFlags()); 13090 } 13091 return SE.getSignExtendExpr(Operand, Expr->getType()); 13092 } 13093 13094 private: 13095 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13096 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13097 SCEVUnionPredicate *Pred) 13098 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13099 13100 bool addOverflowAssumption(const SCEVPredicate *P) { 13101 if (!NewPreds) { 13102 // Check if we've already made this assumption. 13103 return Pred && Pred->implies(P); 13104 } 13105 NewPreds->insert(P); 13106 return true; 13107 } 13108 13109 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13110 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13111 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13112 return addOverflowAssumption(A); 13113 } 13114 13115 // If \p Expr represents a PHINode, we try to see if it can be represented 13116 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13117 // to add this predicate as a runtime overflow check, we return the AddRec. 13118 // If \p Expr does not meet these conditions (is not a PHI node, or we 13119 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13120 // return \p Expr. 13121 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13122 if (!isa<PHINode>(Expr->getValue())) 13123 return Expr; 13124 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13125 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13126 if (!PredicatedRewrite) 13127 return Expr; 13128 for (auto *P : PredicatedRewrite->second){ 13129 // Wrap predicates from outer loops are not supported. 13130 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13131 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 13132 if (L != AR->getLoop()) 13133 return Expr; 13134 } 13135 if (!addOverflowAssumption(P)) 13136 return Expr; 13137 } 13138 return PredicatedRewrite->first; 13139 } 13140 13141 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13142 SCEVUnionPredicate *Pred; 13143 const Loop *L; 13144 }; 13145 13146 } // end anonymous namespace 13147 13148 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13149 SCEVUnionPredicate &Preds) { 13150 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13151 } 13152 13153 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13154 const SCEV *S, const Loop *L, 13155 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13156 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13157 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13158 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13159 13160 if (!AddRec) 13161 return nullptr; 13162 13163 // Since the transformation was successful, we can now transfer the SCEV 13164 // predicates. 13165 for (auto *P : TransformPreds) 13166 Preds.insert(P); 13167 13168 return AddRec; 13169 } 13170 13171 /// SCEV predicates 13172 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13173 SCEVPredicateKind Kind) 13174 : FastID(ID), Kind(Kind) {} 13175 13176 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 13177 const SCEV *LHS, const SCEV *RHS) 13178 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 13179 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13180 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13181 } 13182 13183 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 13184 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 13185 13186 if (!Op) 13187 return false; 13188 13189 return Op->LHS == LHS && Op->RHS == RHS; 13190 } 13191 13192 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 13193 13194 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 13195 13196 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 13197 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13198 } 13199 13200 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13201 const SCEVAddRecExpr *AR, 13202 IncrementWrapFlags Flags) 13203 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13204 13205 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 13206 13207 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13208 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13209 13210 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13211 } 13212 13213 bool SCEVWrapPredicate::isAlwaysTrue() const { 13214 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13215 IncrementWrapFlags IFlags = Flags; 13216 13217 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13218 IFlags = clearFlags(IFlags, IncrementNSSW); 13219 13220 return IFlags == IncrementAnyWrap; 13221 } 13222 13223 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13224 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13225 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13226 OS << "<nusw>"; 13227 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13228 OS << "<nssw>"; 13229 OS << "\n"; 13230 } 13231 13232 SCEVWrapPredicate::IncrementWrapFlags 13233 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13234 ScalarEvolution &SE) { 13235 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13236 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13237 13238 // We can safely transfer the NSW flag as NSSW. 13239 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13240 ImpliedFlags = IncrementNSSW; 13241 13242 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13243 // If the increment is positive, the SCEV NUW flag will also imply the 13244 // WrapPredicate NUSW flag. 13245 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 13246 if (Step->getValue()->getValue().isNonNegative()) 13247 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 13248 } 13249 13250 return ImpliedFlags; 13251 } 13252 13253 /// Union predicates don't get cached so create a dummy set ID for it. 13254 SCEVUnionPredicate::SCEVUnionPredicate() 13255 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 13256 13257 bool SCEVUnionPredicate::isAlwaysTrue() const { 13258 return all_of(Preds, 13259 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 13260 } 13261 13262 ArrayRef<const SCEVPredicate *> 13263 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 13264 auto I = SCEVToPreds.find(Expr); 13265 if (I == SCEVToPreds.end()) 13266 return ArrayRef<const SCEVPredicate *>(); 13267 return I->second; 13268 } 13269 13270 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 13271 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 13272 return all_of(Set->Preds, 13273 [this](const SCEVPredicate *I) { return this->implies(I); }); 13274 13275 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 13276 if (ScevPredsIt == SCEVToPreds.end()) 13277 return false; 13278 auto &SCEVPreds = ScevPredsIt->second; 13279 13280 return any_of(SCEVPreds, 13281 [N](const SCEVPredicate *I) { return I->implies(N); }); 13282 } 13283 13284 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 13285 13286 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 13287 for (auto Pred : Preds) 13288 Pred->print(OS, Depth); 13289 } 13290 13291 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 13292 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 13293 for (auto Pred : Set->Preds) 13294 add(Pred); 13295 return; 13296 } 13297 13298 if (implies(N)) 13299 return; 13300 13301 const SCEV *Key = N->getExpr(); 13302 assert(Key && "Only SCEVUnionPredicate doesn't have an " 13303 " associated expression!"); 13304 13305 SCEVToPreds[Key].push_back(N); 13306 Preds.push_back(N); 13307 } 13308 13309 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 13310 Loop &L) 13311 : SE(SE), L(L) {} 13312 13313 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 13314 const SCEV *Expr = SE.getSCEV(V); 13315 RewriteEntry &Entry = RewriteMap[Expr]; 13316 13317 // If we already have an entry and the version matches, return it. 13318 if (Entry.second && Generation == Entry.first) 13319 return Entry.second; 13320 13321 // We found an entry but it's stale. Rewrite the stale entry 13322 // according to the current predicate. 13323 if (Entry.second) 13324 Expr = Entry.second; 13325 13326 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 13327 Entry = {Generation, NewSCEV}; 13328 13329 return NewSCEV; 13330 } 13331 13332 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 13333 if (!BackedgeCount) { 13334 SCEVUnionPredicate BackedgePred; 13335 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 13336 addPredicate(BackedgePred); 13337 } 13338 return BackedgeCount; 13339 } 13340 13341 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 13342 if (Preds.implies(&Pred)) 13343 return; 13344 Preds.add(&Pred); 13345 updateGeneration(); 13346 } 13347 13348 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 13349 return Preds; 13350 } 13351 13352 void PredicatedScalarEvolution::updateGeneration() { 13353 // If the generation number wrapped recompute everything. 13354 if (++Generation == 0) { 13355 for (auto &II : RewriteMap) { 13356 const SCEV *Rewritten = II.second.second; 13357 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 13358 } 13359 } 13360 } 13361 13362 void PredicatedScalarEvolution::setNoOverflow( 13363 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13364 const SCEV *Expr = getSCEV(V); 13365 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13366 13367 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 13368 13369 // Clear the statically implied flags. 13370 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 13371 addPredicate(*SE.getWrapPredicate(AR, Flags)); 13372 13373 auto II = FlagsMap.insert({V, Flags}); 13374 if (!II.second) 13375 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 13376 } 13377 13378 bool PredicatedScalarEvolution::hasNoOverflow( 13379 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 13380 const SCEV *Expr = getSCEV(V); 13381 const auto *AR = cast<SCEVAddRecExpr>(Expr); 13382 13383 Flags = SCEVWrapPredicate::clearFlags( 13384 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 13385 13386 auto II = FlagsMap.find(V); 13387 13388 if (II != FlagsMap.end()) 13389 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 13390 13391 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 13392 } 13393 13394 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 13395 const SCEV *Expr = this->getSCEV(V); 13396 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 13397 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 13398 13399 if (!New) 13400 return nullptr; 13401 13402 for (auto *P : NewPreds) 13403 Preds.add(P); 13404 13405 updateGeneration(); 13406 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 13407 return New; 13408 } 13409 13410 PredicatedScalarEvolution::PredicatedScalarEvolution( 13411 const PredicatedScalarEvolution &Init) 13412 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13413 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13414 for (auto I : Init.FlagsMap) 13415 FlagsMap.insert(I); 13416 } 13417 13418 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13419 // For each block. 13420 for (auto *BB : L.getBlocks()) 13421 for (auto &I : *BB) { 13422 if (!SE.isSCEVable(I.getType())) 13423 continue; 13424 13425 auto *Expr = SE.getSCEV(&I); 13426 auto II = RewriteMap.find(Expr); 13427 13428 if (II == RewriteMap.end()) 13429 continue; 13430 13431 // Don't print things that are not interesting. 13432 if (II->second.second == Expr) 13433 continue; 13434 13435 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13436 OS.indent(Depth + 2) << *Expr << "\n"; 13437 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13438 } 13439 } 13440 13441 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13442 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13443 // for URem with constant power-of-2 second operands. 13444 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13445 // 4, A / B becomes X / 8). 13446 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13447 const SCEV *&RHS) { 13448 // Try to match 'zext (trunc A to iB) to iY', which is used 13449 // for URem with constant power-of-2 second operands. Make sure the size of 13450 // the operand A matches the size of the whole expressions. 13451 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13452 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13453 LHS = Trunc->getOperand(); 13454 // Bail out if the type of the LHS is larger than the type of the 13455 // expression for now. 13456 if (getTypeSizeInBits(LHS->getType()) > 13457 getTypeSizeInBits(Expr->getType())) 13458 return false; 13459 if (LHS->getType() != Expr->getType()) 13460 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13461 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13462 << getTypeSizeInBits(Trunc->getType())); 13463 return true; 13464 } 13465 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13466 if (Add == nullptr || Add->getNumOperands() != 2) 13467 return false; 13468 13469 const SCEV *A = Add->getOperand(1); 13470 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13471 13472 if (Mul == nullptr) 13473 return false; 13474 13475 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13476 // (SomeExpr + (-(SomeExpr / B) * B)). 13477 if (Expr == getURemExpr(A, B)) { 13478 LHS = A; 13479 RHS = B; 13480 return true; 13481 } 13482 return false; 13483 }; 13484 13485 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13486 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13487 return MatchURemWithDivisor(Mul->getOperand(1)) || 13488 MatchURemWithDivisor(Mul->getOperand(2)); 13489 13490 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13491 if (Mul->getNumOperands() == 2) 13492 return MatchURemWithDivisor(Mul->getOperand(1)) || 13493 MatchURemWithDivisor(Mul->getOperand(0)) || 13494 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13495 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13496 return false; 13497 } 13498 13499 const SCEV * 13500 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13501 SmallVector<BasicBlock*, 16> ExitingBlocks; 13502 L->getExitingBlocks(ExitingBlocks); 13503 13504 // Form an expression for the maximum exit count possible for this loop. We 13505 // merge the max and exact information to approximate a version of 13506 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13507 SmallVector<const SCEV*, 4> ExitCounts; 13508 for (BasicBlock *ExitingBB : ExitingBlocks) { 13509 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13510 if (isa<SCEVCouldNotCompute>(ExitCount)) 13511 ExitCount = getExitCount(L, ExitingBB, 13512 ScalarEvolution::ConstantMaximum); 13513 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13514 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13515 "We should only have known counts for exiting blocks that " 13516 "dominate latch!"); 13517 ExitCounts.push_back(ExitCount); 13518 } 13519 } 13520 if (ExitCounts.empty()) 13521 return getCouldNotCompute(); 13522 return getUMinFromMismatchedTypes(ExitCounts); 13523 } 13524 13525 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13526 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13527 /// we cannot guarantee that the replacement is loop invariant in the loop of 13528 /// the AddRec. 13529 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13530 ValueToSCEVMapTy ⤅ 13531 13532 public: 13533 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13534 : SCEVRewriteVisitor(SE), Map(M) {} 13535 13536 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13537 13538 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13539 auto I = Map.find(Expr->getValue()); 13540 if (I == Map.end()) 13541 return Expr; 13542 return I->second; 13543 } 13544 }; 13545 13546 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13547 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13548 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13549 // If we have LHS == 0, check if LHS is computing a property of some unknown 13550 // SCEV %v which we can rewrite %v to express explicitly. 13551 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 13552 if (Predicate == CmpInst::ICMP_EQ && RHSC && 13553 RHSC->getValue()->isNullValue()) { 13554 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 13555 // explicitly express that. 13556 const SCEV *URemLHS = nullptr; 13557 const SCEV *URemRHS = nullptr; 13558 if (matchURem(LHS, URemLHS, URemRHS)) { 13559 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 13560 Value *V = LHSUnknown->getValue(); 13561 auto Multiple = 13562 getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS, 13563 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 13564 RewriteMap[V] = Multiple; 13565 return; 13566 } 13567 } 13568 } 13569 13570 if (!isa<SCEVUnknown>(LHS)) { 13571 std::swap(LHS, RHS); 13572 Predicate = CmpInst::getSwappedPredicate(Predicate); 13573 } 13574 13575 // For now, limit to conditions that provide information about unknown 13576 // expressions. 13577 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13578 if (!LHSUnknown) 13579 return; 13580 13581 // Check whether LHS has already been rewritten. In that case we want to 13582 // chain further rewrites onto the already rewritten value. 13583 auto I = RewriteMap.find(LHSUnknown->getValue()); 13584 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 13585 13586 // TODO: use information from more predicates. 13587 switch (Predicate) { 13588 case CmpInst::ICMP_ULT: 13589 if (!containsAddRecurrence(RHS)) 13590 RewriteMap[LHSUnknown->getValue()] = getUMinExpr( 13591 RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 13592 break; 13593 case CmpInst::ICMP_ULE: 13594 if (!containsAddRecurrence(RHS)) 13595 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(RewrittenLHS, RHS); 13596 break; 13597 case CmpInst::ICMP_UGT: 13598 if (!containsAddRecurrence(RHS)) 13599 RewriteMap[LHSUnknown->getValue()] = 13600 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 13601 break; 13602 case CmpInst::ICMP_UGE: 13603 if (!containsAddRecurrence(RHS)) 13604 RewriteMap[LHSUnknown->getValue()] = getUMaxExpr(RewrittenLHS, RHS); 13605 break; 13606 case CmpInst::ICMP_EQ: 13607 if (isa<SCEVConstant>(RHS)) 13608 RewriteMap[LHSUnknown->getValue()] = RHS; 13609 break; 13610 case CmpInst::ICMP_NE: 13611 if (isa<SCEVConstant>(RHS) && 13612 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13613 RewriteMap[LHSUnknown->getValue()] = 13614 getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 13615 break; 13616 default: 13617 break; 13618 } 13619 }; 13620 // Starting at the loop predecessor, climb up the predecessor chain, as long 13621 // as there are predecessors that can be found that have unique successors 13622 // leading to the original header. 13623 // TODO: share this logic with isLoopEntryGuardedByCond. 13624 ValueToSCEVMapTy RewriteMap; 13625 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13626 L->getLoopPredecessor(), L->getHeader()); 13627 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13628 13629 const BranchInst *LoopEntryPredicate = 13630 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13631 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13632 continue; 13633 13634 bool EnterIfTrue = LoopEntryPredicate->getSuccessor(0) == Pair.second; 13635 SmallVector<Value *, 8> Worklist; 13636 SmallPtrSet<Value *, 8> Visited; 13637 Worklist.push_back(LoopEntryPredicate->getCondition()); 13638 while (!Worklist.empty()) { 13639 Value *Cond = Worklist.pop_back_val(); 13640 if (!Visited.insert(Cond).second) 13641 continue; 13642 13643 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 13644 auto Predicate = 13645 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 13646 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13647 getSCEV(Cmp->getOperand(1)), RewriteMap); 13648 continue; 13649 } 13650 13651 Value *L, *R; 13652 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 13653 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 13654 Worklist.push_back(L); 13655 Worklist.push_back(R); 13656 } 13657 } 13658 } 13659 13660 // Also collect information from assumptions dominating the loop. 13661 for (auto &AssumeVH : AC.assumptions()) { 13662 if (!AssumeVH) 13663 continue; 13664 auto *AssumeI = cast<CallInst>(AssumeVH); 13665 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13666 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13667 continue; 13668 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13669 getSCEV(Cmp->getOperand(1)), RewriteMap); 13670 } 13671 13672 if (RewriteMap.empty()) 13673 return Expr; 13674 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13675 return Rewriter.visit(Expr); 13676 } 13677