1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionDivision.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 using namespace PatternMatch; 139 140 #define DEBUG_TYPE "scalar-evolution" 141 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 STATISTIC(NumFoundPhiSCCs, 149 "Number of found Phi-composed strongly connected components"); 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 static cl::opt<unsigned> MaxPhiSCCAnalysisSize( 237 "scalar-evolution-max-scc-analysis-depth", cl::Hidden, 238 cl::desc("Maximum amount of nodes to process while searching SCEVUnknown " 239 "Phi strongly connected components"), 240 cl::init(8)); 241 242 //===----------------------------------------------------------------------===// 243 // SCEV class definitions 244 //===----------------------------------------------------------------------===// 245 246 //===----------------------------------------------------------------------===// 247 // Implementation of the SCEV class. 248 // 249 250 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 251 LLVM_DUMP_METHOD void SCEV::dump() const { 252 print(dbgs()); 253 dbgs() << '\n'; 254 } 255 #endif 256 257 void SCEV::print(raw_ostream &OS) const { 258 switch (getSCEVType()) { 259 case scConstant: 260 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 261 return; 262 case scPtrToInt: { 263 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 264 const SCEV *Op = PtrToInt->getOperand(); 265 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 266 << *PtrToInt->getType() << ")"; 267 return; 268 } 269 case scTruncate: { 270 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 271 const SCEV *Op = Trunc->getOperand(); 272 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 273 << *Trunc->getType() << ")"; 274 return; 275 } 276 case scZeroExtend: { 277 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 278 const SCEV *Op = ZExt->getOperand(); 279 OS << "(zext " << *Op->getType() << " " << *Op << " to " 280 << *ZExt->getType() << ")"; 281 return; 282 } 283 case scSignExtend: { 284 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 285 const SCEV *Op = SExt->getOperand(); 286 OS << "(sext " << *Op->getType() << " " << *Op << " to " 287 << *SExt->getType() << ")"; 288 return; 289 } 290 case scAddRecExpr: { 291 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 292 OS << "{" << *AR->getOperand(0); 293 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 294 OS << ",+," << *AR->getOperand(i); 295 OS << "}<"; 296 if (AR->hasNoUnsignedWrap()) 297 OS << "nuw><"; 298 if (AR->hasNoSignedWrap()) 299 OS << "nsw><"; 300 if (AR->hasNoSelfWrap() && 301 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 302 OS << "nw><"; 303 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 304 OS << ">"; 305 return; 306 } 307 case scAddExpr: 308 case scMulExpr: 309 case scUMaxExpr: 310 case scSMaxExpr: 311 case scUMinExpr: 312 case scSMinExpr: 313 case scSequentialUMinExpr: { 314 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 315 const char *OpStr = nullptr; 316 switch (NAry->getSCEVType()) { 317 case scAddExpr: OpStr = " + "; break; 318 case scMulExpr: OpStr = " * "; break; 319 case scUMaxExpr: OpStr = " umax "; break; 320 case scSMaxExpr: OpStr = " smax "; break; 321 case scUMinExpr: 322 OpStr = " umin "; 323 break; 324 case scSMinExpr: 325 OpStr = " smin "; 326 break; 327 case scSequentialUMinExpr: 328 OpStr = " umin_seq "; 329 break; 330 default: 331 llvm_unreachable("There are no other nary expression types."); 332 } 333 OS << "("; 334 ListSeparator LS(OpStr); 335 for (const SCEV *Op : NAry->operands()) 336 OS << LS << *Op; 337 OS << ")"; 338 switch (NAry->getSCEVType()) { 339 case scAddExpr: 340 case scMulExpr: 341 if (NAry->hasNoUnsignedWrap()) 342 OS << "<nuw>"; 343 if (NAry->hasNoSignedWrap()) 344 OS << "<nsw>"; 345 break; 346 default: 347 // Nothing to print for other nary expressions. 348 break; 349 } 350 return; 351 } 352 case scUDivExpr: { 353 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 354 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 355 return; 356 } 357 case scUnknown: { 358 const SCEVUnknown *U = cast<SCEVUnknown>(this); 359 Type *AllocTy; 360 if (U->isSizeOf(AllocTy)) { 361 OS << "sizeof(" << *AllocTy << ")"; 362 return; 363 } 364 if (U->isAlignOf(AllocTy)) { 365 OS << "alignof(" << *AllocTy << ")"; 366 return; 367 } 368 369 Type *CTy; 370 Constant *FieldNo; 371 if (U->isOffsetOf(CTy, FieldNo)) { 372 OS << "offsetof(" << *CTy << ", "; 373 FieldNo->printAsOperand(OS, false); 374 OS << ")"; 375 return; 376 } 377 378 // Otherwise just print it normally. 379 U->getValue()->printAsOperand(OS, false); 380 return; 381 } 382 case scCouldNotCompute: 383 OS << "***COULDNOTCOMPUTE***"; 384 return; 385 } 386 llvm_unreachable("Unknown SCEV kind!"); 387 } 388 389 Type *SCEV::getType() const { 390 switch (getSCEVType()) { 391 case scConstant: 392 return cast<SCEVConstant>(this)->getType(); 393 case scPtrToInt: 394 case scTruncate: 395 case scZeroExtend: 396 case scSignExtend: 397 return cast<SCEVCastExpr>(this)->getType(); 398 case scAddRecExpr: 399 return cast<SCEVAddRecExpr>(this)->getType(); 400 case scMulExpr: 401 return cast<SCEVMulExpr>(this)->getType(); 402 case scUMaxExpr: 403 case scSMaxExpr: 404 case scUMinExpr: 405 case scSMinExpr: 406 return cast<SCEVMinMaxExpr>(this)->getType(); 407 case scSequentialUMinExpr: 408 return cast<SCEVSequentialMinMaxExpr>(this)->getType(); 409 case scAddExpr: 410 return cast<SCEVAddExpr>(this)->getType(); 411 case scUDivExpr: 412 return cast<SCEVUDivExpr>(this)->getType(); 413 case scUnknown: 414 return cast<SCEVUnknown>(this)->getType(); 415 case scCouldNotCompute: 416 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 417 } 418 llvm_unreachable("Unknown SCEV kind!"); 419 } 420 421 bool SCEV::isZero() const { 422 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 423 return SC->getValue()->isZero(); 424 return false; 425 } 426 427 bool SCEV::isOne() const { 428 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 429 return SC->getValue()->isOne(); 430 return false; 431 } 432 433 bool SCEV::isAllOnesValue() const { 434 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 435 return SC->getValue()->isMinusOne(); 436 return false; 437 } 438 439 bool SCEV::isNonConstantNegative() const { 440 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 441 if (!Mul) return false; 442 443 // If there is a constant factor, it will be first. 444 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 445 if (!SC) return false; 446 447 // Return true if the value is negative, this matches things like (-42 * V). 448 return SC->getAPInt().isNegative(); 449 } 450 451 SCEVCouldNotCompute::SCEVCouldNotCompute() : 452 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 453 454 bool SCEVCouldNotCompute::classof(const SCEV *S) { 455 return S->getSCEVType() == scCouldNotCompute; 456 } 457 458 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 459 FoldingSetNodeID ID; 460 ID.AddInteger(scConstant); 461 ID.AddPointer(V); 462 void *IP = nullptr; 463 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 464 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 465 UniqueSCEVs.InsertNode(S, IP); 466 return S; 467 } 468 469 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 470 return getConstant(ConstantInt::get(getContext(), Val)); 471 } 472 473 const SCEV * 474 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 475 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 476 return getConstant(ConstantInt::get(ITy, V, isSigned)); 477 } 478 479 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 480 const SCEV *op, Type *ty) 481 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 482 Operands[0] = op; 483 } 484 485 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 486 Type *ITy) 487 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 488 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 489 "Must be a non-bit-width-changing pointer-to-integer cast!"); 490 } 491 492 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 493 SCEVTypes SCEVTy, const SCEV *op, 494 Type *ty) 495 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 496 497 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 498 Type *ty) 499 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 500 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 501 "Cannot truncate non-integer value!"); 502 } 503 504 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 505 const SCEV *op, Type *ty) 506 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 507 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 508 "Cannot zero extend non-integer value!"); 509 } 510 511 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 512 const SCEV *op, Type *ty) 513 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 514 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 515 "Cannot sign extend non-integer value!"); 516 } 517 518 void SCEVUnknown::deleted() { 519 // Clear this SCEVUnknown from various maps. 520 SE->forgetMemoizedResults(this); 521 522 // Remove this SCEVUnknown from the uniquing map. 523 SE->UniqueSCEVs.RemoveNode(this); 524 525 // Release the value. 526 setValPtr(nullptr); 527 } 528 529 void SCEVUnknown::allUsesReplacedWith(Value *New) { 530 // Remove this SCEVUnknown from the uniquing map. 531 SE->UniqueSCEVs.RemoveNode(this); 532 533 // Update this SCEVUnknown to point to the new value. This is needed 534 // because there may still be outstanding SCEVs which still point to 535 // this SCEVUnknown. 536 setValPtr(New); 537 } 538 539 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 540 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 541 if (VCE->getOpcode() == Instruction::PtrToInt) 542 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 543 if (CE->getOpcode() == Instruction::GetElementPtr && 544 CE->getOperand(0)->isNullValue() && 545 CE->getNumOperands() == 2) 546 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 547 if (CI->isOne()) { 548 AllocTy = cast<GEPOperator>(CE)->getSourceElementType(); 549 return true; 550 } 551 552 return false; 553 } 554 555 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 556 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 557 if (VCE->getOpcode() == Instruction::PtrToInt) 558 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 559 if (CE->getOpcode() == Instruction::GetElementPtr && 560 CE->getOperand(0)->isNullValue()) { 561 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 562 if (StructType *STy = dyn_cast<StructType>(Ty)) 563 if (!STy->isPacked() && 564 CE->getNumOperands() == 3 && 565 CE->getOperand(1)->isNullValue()) { 566 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 567 if (CI->isOne() && 568 STy->getNumElements() == 2 && 569 STy->getElementType(0)->isIntegerTy(1)) { 570 AllocTy = STy->getElementType(1); 571 return true; 572 } 573 } 574 } 575 576 return false; 577 } 578 579 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 580 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 581 if (VCE->getOpcode() == Instruction::PtrToInt) 582 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 583 if (CE->getOpcode() == Instruction::GetElementPtr && 584 CE->getNumOperands() == 3 && 585 CE->getOperand(0)->isNullValue() && 586 CE->getOperand(1)->isNullValue()) { 587 Type *Ty = cast<GEPOperator>(CE)->getSourceElementType(); 588 // Ignore vector types here so that ScalarEvolutionExpander doesn't 589 // emit getelementptrs that index into vectors. 590 if (Ty->isStructTy() || Ty->isArrayTy()) { 591 CTy = Ty; 592 FieldNo = CE->getOperand(2); 593 return true; 594 } 595 } 596 597 return false; 598 } 599 600 //===----------------------------------------------------------------------===// 601 // SCEV Utilities 602 //===----------------------------------------------------------------------===// 603 604 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 605 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 606 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 607 /// have been previously deemed to be "equally complex" by this routine. It is 608 /// intended to avoid exponential time complexity in cases like: 609 /// 610 /// %a = f(%x, %y) 611 /// %b = f(%a, %a) 612 /// %c = f(%b, %b) 613 /// 614 /// %d = f(%x, %y) 615 /// %e = f(%d, %d) 616 /// %f = f(%e, %e) 617 /// 618 /// CompareValueComplexity(%f, %c) 619 /// 620 /// Since we do not continue running this routine on expression trees once we 621 /// have seen unequal values, there is no need to track them in the cache. 622 static int 623 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 624 const LoopInfo *const LI, Value *LV, Value *RV, 625 unsigned Depth) { 626 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 627 return 0; 628 629 // Order pointer values after integer values. This helps SCEVExpander form 630 // GEPs. 631 bool LIsPointer = LV->getType()->isPointerTy(), 632 RIsPointer = RV->getType()->isPointerTy(); 633 if (LIsPointer != RIsPointer) 634 return (int)LIsPointer - (int)RIsPointer; 635 636 // Compare getValueID values. 637 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 638 if (LID != RID) 639 return (int)LID - (int)RID; 640 641 // Sort arguments by their position. 642 if (const auto *LA = dyn_cast<Argument>(LV)) { 643 const auto *RA = cast<Argument>(RV); 644 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 645 return (int)LArgNo - (int)RArgNo; 646 } 647 648 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 649 const auto *RGV = cast<GlobalValue>(RV); 650 651 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 652 auto LT = GV->getLinkage(); 653 return !(GlobalValue::isPrivateLinkage(LT) || 654 GlobalValue::isInternalLinkage(LT)); 655 }; 656 657 // Use the names to distinguish the two values, but only if the 658 // names are semantically important. 659 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 660 return LGV->getName().compare(RGV->getName()); 661 } 662 663 // For instructions, compare their loop depth, and their operand count. This 664 // is pretty loose. 665 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 666 const auto *RInst = cast<Instruction>(RV); 667 668 // Compare loop depths. 669 const BasicBlock *LParent = LInst->getParent(), 670 *RParent = RInst->getParent(); 671 if (LParent != RParent) { 672 unsigned LDepth = LI->getLoopDepth(LParent), 673 RDepth = LI->getLoopDepth(RParent); 674 if (LDepth != RDepth) 675 return (int)LDepth - (int)RDepth; 676 } 677 678 // Compare the number of operands. 679 unsigned LNumOps = LInst->getNumOperands(), 680 RNumOps = RInst->getNumOperands(); 681 if (LNumOps != RNumOps) 682 return (int)LNumOps - (int)RNumOps; 683 684 for (unsigned Idx : seq(0u, LNumOps)) { 685 int Result = 686 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 687 RInst->getOperand(Idx), Depth + 1); 688 if (Result != 0) 689 return Result; 690 } 691 } 692 693 EqCacheValue.unionSets(LV, RV); 694 return 0; 695 } 696 697 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 698 // than RHS, respectively. A three-way result allows recursive comparisons to be 699 // more efficient. 700 // If the max analysis depth was reached, return None, assuming we do not know 701 // if they are equivalent for sure. 702 static Optional<int> 703 CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV, 704 EquivalenceClasses<const Value *> &EqCacheValue, 705 const LoopInfo *const LI, const SCEV *LHS, 706 const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) { 707 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 708 if (LHS == RHS) 709 return 0; 710 711 // Primarily, sort the SCEVs by their getSCEVType(). 712 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 713 if (LType != RType) 714 return (int)LType - (int)RType; 715 716 if (EqCacheSCEV.isEquivalent(LHS, RHS)) 717 return 0; 718 719 if (Depth > MaxSCEVCompareDepth) 720 return None; 721 722 // Aside from the getSCEVType() ordering, the particular ordering 723 // isn't very important except that it's beneficial to be consistent, 724 // so that (a + b) and (b + a) don't end up as different expressions. 725 switch (LType) { 726 case scUnknown: { 727 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 728 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 729 730 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 731 RU->getValue(), Depth + 1); 732 if (X == 0) 733 EqCacheSCEV.unionSets(LHS, RHS); 734 return X; 735 } 736 737 case scConstant: { 738 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 739 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 740 741 // Compare constant values. 742 const APInt &LA = LC->getAPInt(); 743 const APInt &RA = RC->getAPInt(); 744 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 745 if (LBitWidth != RBitWidth) 746 return (int)LBitWidth - (int)RBitWidth; 747 return LA.ult(RA) ? -1 : 1; 748 } 749 750 case scAddRecExpr: { 751 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 752 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 753 754 // There is always a dominance between two recs that are used by one SCEV, 755 // so we can safely sort recs by loop header dominance. We require such 756 // order in getAddExpr. 757 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 758 if (LLoop != RLoop) { 759 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 760 assert(LHead != RHead && "Two loops share the same header?"); 761 if (DT.dominates(LHead, RHead)) 762 return 1; 763 else 764 assert(DT.dominates(RHead, LHead) && 765 "No dominance between recurrences used by one SCEV?"); 766 return -1; 767 } 768 769 // Addrec complexity grows with operand count. 770 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 771 if (LNumOps != RNumOps) 772 return (int)LNumOps - (int)RNumOps; 773 774 // Lexicographically compare. 775 for (unsigned i = 0; i != LNumOps; ++i) { 776 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 777 LA->getOperand(i), RA->getOperand(i), DT, 778 Depth + 1); 779 if (X != 0) 780 return X; 781 } 782 EqCacheSCEV.unionSets(LHS, RHS); 783 return 0; 784 } 785 786 case scAddExpr: 787 case scMulExpr: 788 case scSMaxExpr: 789 case scUMaxExpr: 790 case scSMinExpr: 791 case scUMinExpr: 792 case scSequentialUMinExpr: { 793 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 794 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 795 796 // Lexicographically compare n-ary expressions. 797 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 798 if (LNumOps != RNumOps) 799 return (int)LNumOps - (int)RNumOps; 800 801 for (unsigned i = 0; i != LNumOps; ++i) { 802 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 803 LC->getOperand(i), RC->getOperand(i), DT, 804 Depth + 1); 805 if (X != 0) 806 return X; 807 } 808 EqCacheSCEV.unionSets(LHS, RHS); 809 return 0; 810 } 811 812 case scUDivExpr: { 813 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 814 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 815 816 // Lexicographically compare udiv expressions. 817 auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 818 RC->getLHS(), DT, Depth + 1); 819 if (X != 0) 820 return X; 821 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 822 RC->getRHS(), DT, Depth + 1); 823 if (X == 0) 824 EqCacheSCEV.unionSets(LHS, RHS); 825 return X; 826 } 827 828 case scPtrToInt: 829 case scTruncate: 830 case scZeroExtend: 831 case scSignExtend: { 832 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 833 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 834 835 // Compare cast expressions by operand. 836 auto X = 837 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getOperand(), 838 RC->getOperand(), DT, Depth + 1); 839 if (X == 0) 840 EqCacheSCEV.unionSets(LHS, RHS); 841 return X; 842 } 843 844 case scCouldNotCompute: 845 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 846 } 847 llvm_unreachable("Unknown SCEV kind!"); 848 } 849 850 /// Given a list of SCEV objects, order them by their complexity, and group 851 /// objects of the same complexity together by value. When this routine is 852 /// finished, we know that any duplicates in the vector are consecutive and that 853 /// complexity is monotonically increasing. 854 /// 855 /// Note that we go take special precautions to ensure that we get deterministic 856 /// results from this routine. In other words, we don't want the results of 857 /// this to depend on where the addresses of various SCEV objects happened to 858 /// land in memory. 859 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 860 LoopInfo *LI, DominatorTree &DT) { 861 if (Ops.size() < 2) return; // Noop 862 863 EquivalenceClasses<const SCEV *> EqCacheSCEV; 864 EquivalenceClasses<const Value *> EqCacheValue; 865 866 // Whether LHS has provably less complexity than RHS. 867 auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) { 868 auto Complexity = 869 CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT); 870 return Complexity && *Complexity < 0; 871 }; 872 if (Ops.size() == 2) { 873 // This is the common case, which also happens to be trivially simple. 874 // Special case it. 875 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 876 if (IsLessComplex(RHS, LHS)) 877 std::swap(LHS, RHS); 878 return; 879 } 880 881 // Do the rough sort by complexity. 882 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 883 return IsLessComplex(LHS, RHS); 884 }); 885 886 // Now that we are sorted by complexity, group elements of the same 887 // complexity. Note that this is, at worst, N^2, but the vector is likely to 888 // be extremely short in practice. Note that we take this approach because we 889 // do not want to depend on the addresses of the objects we are grouping. 890 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 891 const SCEV *S = Ops[i]; 892 unsigned Complexity = S->getSCEVType(); 893 894 // If there are any objects of the same complexity and same value as this 895 // one, group them. 896 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 897 if (Ops[j] == S) { // Found a duplicate. 898 // Move it to immediately after i'th element. 899 std::swap(Ops[i+1], Ops[j]); 900 ++i; // no need to rescan it. 901 if (i == e-2) return; // Done! 902 } 903 } 904 } 905 } 906 907 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 908 /// least HugeExprThreshold nodes). 909 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 910 return any_of(Ops, [](const SCEV *S) { 911 return S->getExpressionSize() >= HugeExprThreshold; 912 }); 913 } 914 915 //===----------------------------------------------------------------------===// 916 // Simple SCEV method implementations 917 //===----------------------------------------------------------------------===// 918 919 /// Compute BC(It, K). The result has width W. Assume, K > 0. 920 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 921 ScalarEvolution &SE, 922 Type *ResultTy) { 923 // Handle the simplest case efficiently. 924 if (K == 1) 925 return SE.getTruncateOrZeroExtend(It, ResultTy); 926 927 // We are using the following formula for BC(It, K): 928 // 929 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 930 // 931 // Suppose, W is the bitwidth of the return value. We must be prepared for 932 // overflow. Hence, we must assure that the result of our computation is 933 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 934 // safe in modular arithmetic. 935 // 936 // However, this code doesn't use exactly that formula; the formula it uses 937 // is something like the following, where T is the number of factors of 2 in 938 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 939 // exponentiation: 940 // 941 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 942 // 943 // This formula is trivially equivalent to the previous formula. However, 944 // this formula can be implemented much more efficiently. The trick is that 945 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 946 // arithmetic. To do exact division in modular arithmetic, all we have 947 // to do is multiply by the inverse. Therefore, this step can be done at 948 // width W. 949 // 950 // The next issue is how to safely do the division by 2^T. The way this 951 // is done is by doing the multiplication step at a width of at least W + T 952 // bits. This way, the bottom W+T bits of the product are accurate. Then, 953 // when we perform the division by 2^T (which is equivalent to a right shift 954 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 955 // truncated out after the division by 2^T. 956 // 957 // In comparison to just directly using the first formula, this technique 958 // is much more efficient; using the first formula requires W * K bits, 959 // but this formula less than W + K bits. Also, the first formula requires 960 // a division step, whereas this formula only requires multiplies and shifts. 961 // 962 // It doesn't matter whether the subtraction step is done in the calculation 963 // width or the input iteration count's width; if the subtraction overflows, 964 // the result must be zero anyway. We prefer here to do it in the width of 965 // the induction variable because it helps a lot for certain cases; CodeGen 966 // isn't smart enough to ignore the overflow, which leads to much less 967 // efficient code if the width of the subtraction is wider than the native 968 // register width. 969 // 970 // (It's possible to not widen at all by pulling out factors of 2 before 971 // the multiplication; for example, K=2 can be calculated as 972 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 973 // extra arithmetic, so it's not an obvious win, and it gets 974 // much more complicated for K > 3.) 975 976 // Protection from insane SCEVs; this bound is conservative, 977 // but it probably doesn't matter. 978 if (K > 1000) 979 return SE.getCouldNotCompute(); 980 981 unsigned W = SE.getTypeSizeInBits(ResultTy); 982 983 // Calculate K! / 2^T and T; we divide out the factors of two before 984 // multiplying for calculating K! / 2^T to avoid overflow. 985 // Other overflow doesn't matter because we only care about the bottom 986 // W bits of the result. 987 APInt OddFactorial(W, 1); 988 unsigned T = 1; 989 for (unsigned i = 3; i <= K; ++i) { 990 APInt Mult(W, i); 991 unsigned TwoFactors = Mult.countTrailingZeros(); 992 T += TwoFactors; 993 Mult.lshrInPlace(TwoFactors); 994 OddFactorial *= Mult; 995 } 996 997 // We need at least W + T bits for the multiplication step 998 unsigned CalculationBits = W + T; 999 1000 // Calculate 2^T, at width T+W. 1001 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1002 1003 // Calculate the multiplicative inverse of K! / 2^T; 1004 // this multiplication factor will perform the exact division by 1005 // K! / 2^T. 1006 APInt Mod = APInt::getSignedMinValue(W+1); 1007 APInt MultiplyFactor = OddFactorial.zext(W+1); 1008 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1009 MultiplyFactor = MultiplyFactor.trunc(W); 1010 1011 // Calculate the product, at width T+W 1012 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1013 CalculationBits); 1014 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1015 for (unsigned i = 1; i != K; ++i) { 1016 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1017 Dividend = SE.getMulExpr(Dividend, 1018 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1019 } 1020 1021 // Divide by 2^T 1022 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1023 1024 // Truncate the result, and divide by K! / 2^T. 1025 1026 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1027 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1028 } 1029 1030 /// Return the value of this chain of recurrences at the specified iteration 1031 /// number. We can evaluate this recurrence by multiplying each element in the 1032 /// chain by the binomial coefficient corresponding to it. In other words, we 1033 /// can evaluate {A,+,B,+,C,+,D} as: 1034 /// 1035 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1036 /// 1037 /// where BC(It, k) stands for binomial coefficient. 1038 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1039 ScalarEvolution &SE) const { 1040 return evaluateAtIteration(makeArrayRef(op_begin(), op_end()), It, SE); 1041 } 1042 1043 const SCEV * 1044 SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands, 1045 const SCEV *It, ScalarEvolution &SE) { 1046 assert(Operands.size() > 0); 1047 const SCEV *Result = Operands[0]; 1048 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 1049 // The computation is correct in the face of overflow provided that the 1050 // multiplication is performed _after_ the evaluation of the binomial 1051 // coefficient. 1052 const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType()); 1053 if (isa<SCEVCouldNotCompute>(Coeff)) 1054 return Coeff; 1055 1056 Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff)); 1057 } 1058 return Result; 1059 } 1060 1061 //===----------------------------------------------------------------------===// 1062 // SCEV Expression folder implementations 1063 //===----------------------------------------------------------------------===// 1064 1065 const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op, 1066 unsigned Depth) { 1067 assert(Depth <= 1 && 1068 "getLosslessPtrToIntExpr() should self-recurse at most once."); 1069 1070 // We could be called with an integer-typed operands during SCEV rewrites. 1071 // Since the operand is an integer already, just perform zext/trunc/self cast. 1072 if (!Op->getType()->isPointerTy()) 1073 return Op; 1074 1075 // What would be an ID for such a SCEV cast expression? 1076 FoldingSetNodeID ID; 1077 ID.AddInteger(scPtrToInt); 1078 ID.AddPointer(Op); 1079 1080 void *IP = nullptr; 1081 1082 // Is there already an expression for such a cast? 1083 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1084 return S; 1085 1086 // It isn't legal for optimizations to construct new ptrtoint expressions 1087 // for non-integral pointers. 1088 if (getDataLayout().isNonIntegralPointerType(Op->getType())) 1089 return getCouldNotCompute(); 1090 1091 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1092 1093 // We can only trivially model ptrtoint if SCEV's effective (integer) type 1094 // is sufficiently wide to represent all possible pointer values. 1095 // We could theoretically teach SCEV to truncate wider pointers, but 1096 // that isn't implemented for now. 1097 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) != 1098 getDataLayout().getTypeSizeInBits(IntPtrTy)) 1099 return getCouldNotCompute(); 1100 1101 // If not, is this expression something we can't reduce any further? 1102 if (auto *U = dyn_cast<SCEVUnknown>(Op)) { 1103 // Perform some basic constant folding. If the operand of the ptr2int cast 1104 // is a null pointer, don't create a ptr2int SCEV expression (that will be 1105 // left as-is), but produce a zero constant. 1106 // NOTE: We could handle a more general case, but lack motivational cases. 1107 if (isa<ConstantPointerNull>(U->getValue())) 1108 return getZero(IntPtrTy); 1109 1110 // Create an explicit cast node. 1111 // We can reuse the existing insert position since if we get here, 1112 // we won't have made any changes which would invalidate it. 1113 SCEV *S = new (SCEVAllocator) 1114 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1115 UniqueSCEVs.InsertNode(S, IP); 1116 registerUser(S, Op); 1117 return S; 1118 } 1119 1120 assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for " 1121 "non-SCEVUnknown's."); 1122 1123 // Otherwise, we've got some expression that is more complex than just a 1124 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1125 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1126 // only, and the expressions must otherwise be integer-typed. 1127 // So sink the cast down to the SCEVUnknown's. 1128 1129 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1130 /// which computes a pointer-typed value, and rewrites the whole expression 1131 /// tree so that *all* the computations are done on integers, and the only 1132 /// pointer-typed operands in the expression are SCEVUnknown. 1133 class SCEVPtrToIntSinkingRewriter 1134 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1135 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1136 1137 public: 1138 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1139 1140 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1141 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1142 return Rewriter.visit(Scev); 1143 } 1144 1145 const SCEV *visit(const SCEV *S) { 1146 Type *STy = S->getType(); 1147 // If the expression is not pointer-typed, just keep it as-is. 1148 if (!STy->isPointerTy()) 1149 return S; 1150 // Else, recursively sink the cast down into it. 1151 return Base::visit(S); 1152 } 1153 1154 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1155 SmallVector<const SCEV *, 2> Operands; 1156 bool Changed = false; 1157 for (auto *Op : Expr->operands()) { 1158 Operands.push_back(visit(Op)); 1159 Changed |= Op != Operands.back(); 1160 } 1161 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1162 } 1163 1164 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1165 SmallVector<const SCEV *, 2> Operands; 1166 bool Changed = false; 1167 for (auto *Op : Expr->operands()) { 1168 Operands.push_back(visit(Op)); 1169 Changed |= Op != Operands.back(); 1170 } 1171 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1172 } 1173 1174 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1175 assert(Expr->getType()->isPointerTy() && 1176 "Should only reach pointer-typed SCEVUnknown's."); 1177 return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1); 1178 } 1179 }; 1180 1181 // And actually perform the cast sinking. 1182 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1183 assert(IntOp->getType()->isIntegerTy() && 1184 "We must have succeeded in sinking the cast, " 1185 "and ending up with an integer-typed expression!"); 1186 return IntOp; 1187 } 1188 1189 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) { 1190 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1191 1192 const SCEV *IntOp = getLosslessPtrToIntExpr(Op); 1193 if (isa<SCEVCouldNotCompute>(IntOp)) 1194 return IntOp; 1195 1196 return getTruncateOrZeroExtend(IntOp, Ty); 1197 } 1198 1199 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1200 unsigned Depth) { 1201 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1202 "This is not a truncating conversion!"); 1203 assert(isSCEVable(Ty) && 1204 "This is not a conversion to a SCEVable type!"); 1205 assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!"); 1206 Ty = getEffectiveSCEVType(Ty); 1207 1208 FoldingSetNodeID ID; 1209 ID.AddInteger(scTruncate); 1210 ID.AddPointer(Op); 1211 ID.AddPointer(Ty); 1212 void *IP = nullptr; 1213 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1214 1215 // Fold if the operand is constant. 1216 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1217 return getConstant( 1218 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1219 1220 // trunc(trunc(x)) --> trunc(x) 1221 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1222 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1223 1224 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1225 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1226 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1227 1228 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1229 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1230 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1231 1232 if (Depth > MaxCastDepth) { 1233 SCEV *S = 1234 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1235 UniqueSCEVs.InsertNode(S, IP); 1236 registerUser(S, Op); 1237 return S; 1238 } 1239 1240 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1241 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1242 // if after transforming we have at most one truncate, not counting truncates 1243 // that replace other casts. 1244 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1245 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1246 SmallVector<const SCEV *, 4> Operands; 1247 unsigned numTruncs = 0; 1248 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1249 ++i) { 1250 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1251 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1252 isa<SCEVTruncateExpr>(S)) 1253 numTruncs++; 1254 Operands.push_back(S); 1255 } 1256 if (numTruncs < 2) { 1257 if (isa<SCEVAddExpr>(Op)) 1258 return getAddExpr(Operands); 1259 else if (isa<SCEVMulExpr>(Op)) 1260 return getMulExpr(Operands); 1261 else 1262 llvm_unreachable("Unexpected SCEV type for Op."); 1263 } 1264 // Although we checked in the beginning that ID is not in the cache, it is 1265 // possible that during recursion and different modification ID was inserted 1266 // into the cache. So if we find it, just return it. 1267 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1268 return S; 1269 } 1270 1271 // If the input value is a chrec scev, truncate the chrec's operands. 1272 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1273 SmallVector<const SCEV *, 4> Operands; 1274 for (const SCEV *Op : AddRec->operands()) 1275 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1276 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1277 } 1278 1279 // Return zero if truncating to known zeros. 1280 uint32_t MinTrailingZeros = GetMinTrailingZeros(Op); 1281 if (MinTrailingZeros >= getTypeSizeInBits(Ty)) 1282 return getZero(Ty); 1283 1284 // The cast wasn't folded; create an explicit cast node. We can reuse 1285 // the existing insert position since if we get here, we won't have 1286 // made any changes which would invalidate it. 1287 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1288 Op, Ty); 1289 UniqueSCEVs.InsertNode(S, IP); 1290 registerUser(S, Op); 1291 return S; 1292 } 1293 1294 // Get the limit of a recurrence such that incrementing by Step cannot cause 1295 // signed overflow as long as the value of the recurrence within the 1296 // loop does not exceed this limit before incrementing. 1297 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1298 ICmpInst::Predicate *Pred, 1299 ScalarEvolution *SE) { 1300 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1301 if (SE->isKnownPositive(Step)) { 1302 *Pred = ICmpInst::ICMP_SLT; 1303 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1304 SE->getSignedRangeMax(Step)); 1305 } 1306 if (SE->isKnownNegative(Step)) { 1307 *Pred = ICmpInst::ICMP_SGT; 1308 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1309 SE->getSignedRangeMin(Step)); 1310 } 1311 return nullptr; 1312 } 1313 1314 // Get the limit of a recurrence such that incrementing by Step cannot cause 1315 // unsigned overflow as long as the value of the recurrence within the loop does 1316 // not exceed this limit before incrementing. 1317 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1318 ICmpInst::Predicate *Pred, 1319 ScalarEvolution *SE) { 1320 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1321 *Pred = ICmpInst::ICMP_ULT; 1322 1323 return SE->getConstant(APInt::getMinValue(BitWidth) - 1324 SE->getUnsignedRangeMax(Step)); 1325 } 1326 1327 namespace { 1328 1329 struct ExtendOpTraitsBase { 1330 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1331 unsigned); 1332 }; 1333 1334 // Used to make code generic over signed and unsigned overflow. 1335 template <typename ExtendOp> struct ExtendOpTraits { 1336 // Members present: 1337 // 1338 // static const SCEV::NoWrapFlags WrapType; 1339 // 1340 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1341 // 1342 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1343 // ICmpInst::Predicate *Pred, 1344 // ScalarEvolution *SE); 1345 }; 1346 1347 template <> 1348 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1349 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1350 1351 static const GetExtendExprTy GetExtendExpr; 1352 1353 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1354 ICmpInst::Predicate *Pred, 1355 ScalarEvolution *SE) { 1356 return getSignedOverflowLimitForStep(Step, Pred, SE); 1357 } 1358 }; 1359 1360 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1361 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1362 1363 template <> 1364 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1365 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1366 1367 static const GetExtendExprTy GetExtendExpr; 1368 1369 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1370 ICmpInst::Predicate *Pred, 1371 ScalarEvolution *SE) { 1372 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1373 } 1374 }; 1375 1376 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1377 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1378 1379 } // end anonymous namespace 1380 1381 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1382 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1383 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1384 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1385 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1386 // expression "Step + sext/zext(PreIncAR)" is congruent with 1387 // "sext/zext(PostIncAR)" 1388 template <typename ExtendOpTy> 1389 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1390 ScalarEvolution *SE, unsigned Depth) { 1391 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1392 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1393 1394 const Loop *L = AR->getLoop(); 1395 const SCEV *Start = AR->getStart(); 1396 const SCEV *Step = AR->getStepRecurrence(*SE); 1397 1398 // Check for a simple looking step prior to loop entry. 1399 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1400 if (!SA) 1401 return nullptr; 1402 1403 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1404 // subtraction is expensive. For this purpose, perform a quick and dirty 1405 // difference, by checking for Step in the operand list. 1406 SmallVector<const SCEV *, 4> DiffOps; 1407 for (const SCEV *Op : SA->operands()) 1408 if (Op != Step) 1409 DiffOps.push_back(Op); 1410 1411 if (DiffOps.size() == SA->getNumOperands()) 1412 return nullptr; 1413 1414 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1415 // `Step`: 1416 1417 // 1. NSW/NUW flags on the step increment. 1418 auto PreStartFlags = 1419 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1420 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1421 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1422 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1423 1424 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1425 // "S+X does not sign/unsign-overflow". 1426 // 1427 1428 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1429 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1430 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1431 return PreStart; 1432 1433 // 2. Direct overflow check on the step operation's expression. 1434 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1435 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1436 const SCEV *OperandExtendedStart = 1437 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1438 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1439 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1440 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1441 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1442 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1443 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1444 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType); 1445 } 1446 return PreStart; 1447 } 1448 1449 // 3. Loop precondition. 1450 ICmpInst::Predicate Pred; 1451 const SCEV *OverflowLimit = 1452 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1453 1454 if (OverflowLimit && 1455 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1456 return PreStart; 1457 1458 return nullptr; 1459 } 1460 1461 // Get the normalized zero or sign extended expression for this AddRec's Start. 1462 template <typename ExtendOpTy> 1463 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1464 ScalarEvolution *SE, 1465 unsigned Depth) { 1466 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1467 1468 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1469 if (!PreStart) 1470 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1471 1472 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1473 Depth), 1474 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1475 } 1476 1477 // Try to prove away overflow by looking at "nearby" add recurrences. A 1478 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1479 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1480 // 1481 // Formally: 1482 // 1483 // {S,+,X} == {S-T,+,X} + T 1484 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1485 // 1486 // If ({S-T,+,X} + T) does not overflow ... (1) 1487 // 1488 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1489 // 1490 // If {S-T,+,X} does not overflow ... (2) 1491 // 1492 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1493 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1494 // 1495 // If (S-T)+T does not overflow ... (3) 1496 // 1497 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1498 // == {Ext(S),+,Ext(X)} == LHS 1499 // 1500 // Thus, if (1), (2) and (3) are true for some T, then 1501 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1502 // 1503 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1504 // does not overflow" restricted to the 0th iteration. Therefore we only need 1505 // to check for (1) and (2). 1506 // 1507 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1508 // is `Delta` (defined below). 1509 template <typename ExtendOpTy> 1510 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1511 const SCEV *Step, 1512 const Loop *L) { 1513 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1514 1515 // We restrict `Start` to a constant to prevent SCEV from spending too much 1516 // time here. It is correct (but more expensive) to continue with a 1517 // non-constant `Start` and do a general SCEV subtraction to compute 1518 // `PreStart` below. 1519 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1520 if (!StartC) 1521 return false; 1522 1523 APInt StartAI = StartC->getAPInt(); 1524 1525 for (unsigned Delta : {-2, -1, 1, 2}) { 1526 const SCEV *PreStart = getConstant(StartAI - Delta); 1527 1528 FoldingSetNodeID ID; 1529 ID.AddInteger(scAddRecExpr); 1530 ID.AddPointer(PreStart); 1531 ID.AddPointer(Step); 1532 ID.AddPointer(L); 1533 void *IP = nullptr; 1534 const auto *PreAR = 1535 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1536 1537 // Give up if we don't already have the add recurrence we need because 1538 // actually constructing an add recurrence is relatively expensive. 1539 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1540 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1541 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1542 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1543 DeltaS, &Pred, this); 1544 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1545 return true; 1546 } 1547 } 1548 1549 return false; 1550 } 1551 1552 // Finds an integer D for an expression (C + x + y + ...) such that the top 1553 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1554 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1555 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1556 // the (C + x + y + ...) expression is \p WholeAddExpr. 1557 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1558 const SCEVConstant *ConstantTerm, 1559 const SCEVAddExpr *WholeAddExpr) { 1560 const APInt &C = ConstantTerm->getAPInt(); 1561 const unsigned BitWidth = C.getBitWidth(); 1562 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1563 uint32_t TZ = BitWidth; 1564 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1565 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1566 if (TZ) { 1567 // Set D to be as many least significant bits of C as possible while still 1568 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1569 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1570 } 1571 return APInt(BitWidth, 0); 1572 } 1573 1574 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1575 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1576 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1577 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1578 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1579 const APInt &ConstantStart, 1580 const SCEV *Step) { 1581 const unsigned BitWidth = ConstantStart.getBitWidth(); 1582 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1583 if (TZ) 1584 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1585 : ConstantStart; 1586 return APInt(BitWidth, 0); 1587 } 1588 1589 const SCEV * 1590 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1591 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1592 "This is not an extending conversion!"); 1593 assert(isSCEVable(Ty) && 1594 "This is not a conversion to a SCEVable type!"); 1595 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1596 Ty = getEffectiveSCEVType(Ty); 1597 1598 // Fold if the operand is constant. 1599 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1600 return getConstant( 1601 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1602 1603 // zext(zext(x)) --> zext(x) 1604 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1605 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1606 1607 // Before doing any expensive analysis, check to see if we've already 1608 // computed a SCEV for this Op and Ty. 1609 FoldingSetNodeID ID; 1610 ID.AddInteger(scZeroExtend); 1611 ID.AddPointer(Op); 1612 ID.AddPointer(Ty); 1613 void *IP = nullptr; 1614 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1615 if (Depth > MaxCastDepth) { 1616 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1617 Op, Ty); 1618 UniqueSCEVs.InsertNode(S, IP); 1619 registerUser(S, Op); 1620 return S; 1621 } 1622 1623 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1624 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1625 // It's possible the bits taken off by the truncate were all zero bits. If 1626 // so, we should be able to simplify this further. 1627 const SCEV *X = ST->getOperand(); 1628 ConstantRange CR = getUnsignedRange(X); 1629 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1630 unsigned NewBits = getTypeSizeInBits(Ty); 1631 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1632 CR.zextOrTrunc(NewBits))) 1633 return getTruncateOrZeroExtend(X, Ty, Depth); 1634 } 1635 1636 // If the input value is a chrec scev, and we can prove that the value 1637 // did not overflow the old, smaller, value, we can zero extend all of the 1638 // operands (often constants). This allows analysis of something like 1639 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1640 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1641 if (AR->isAffine()) { 1642 const SCEV *Start = AR->getStart(); 1643 const SCEV *Step = AR->getStepRecurrence(*this); 1644 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1645 const Loop *L = AR->getLoop(); 1646 1647 if (!AR->hasNoUnsignedWrap()) { 1648 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1649 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1650 } 1651 1652 // If we have special knowledge that this addrec won't overflow, 1653 // we don't need to do any further analysis. 1654 if (AR->hasNoUnsignedWrap()) 1655 return getAddRecExpr( 1656 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1657 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1658 1659 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1660 // Note that this serves two purposes: It filters out loops that are 1661 // simply not analyzable, and it covers the case where this code is 1662 // being called from within backedge-taken count analysis, such that 1663 // attempting to ask for the backedge-taken count would likely result 1664 // in infinite recursion. In the later case, the analysis code will 1665 // cope with a conservative value, and it will take care to purge 1666 // that value once it has finished. 1667 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1668 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1669 // Manually compute the final value for AR, checking for overflow. 1670 1671 // Check whether the backedge-taken count can be losslessly casted to 1672 // the addrec's type. The count is always unsigned. 1673 const SCEV *CastedMaxBECount = 1674 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1675 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1676 CastedMaxBECount, MaxBECount->getType(), Depth); 1677 if (MaxBECount == RecastedMaxBECount) { 1678 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1679 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1680 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1681 SCEV::FlagAnyWrap, Depth + 1); 1682 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1683 SCEV::FlagAnyWrap, 1684 Depth + 1), 1685 WideTy, Depth + 1); 1686 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1687 const SCEV *WideMaxBECount = 1688 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1689 const SCEV *OperandExtendedAdd = 1690 getAddExpr(WideStart, 1691 getMulExpr(WideMaxBECount, 1692 getZeroExtendExpr(Step, WideTy, Depth + 1), 1693 SCEV::FlagAnyWrap, Depth + 1), 1694 SCEV::FlagAnyWrap, Depth + 1); 1695 if (ZAdd == OperandExtendedAdd) { 1696 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1697 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1698 // Return the expression with the addrec on the outside. 1699 return getAddRecExpr( 1700 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1701 Depth + 1), 1702 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1703 AR->getNoWrapFlags()); 1704 } 1705 // Similar to above, only this time treat the step value as signed. 1706 // This covers loops that count down. 1707 OperandExtendedAdd = 1708 getAddExpr(WideStart, 1709 getMulExpr(WideMaxBECount, 1710 getSignExtendExpr(Step, WideTy, Depth + 1), 1711 SCEV::FlagAnyWrap, Depth + 1), 1712 SCEV::FlagAnyWrap, Depth + 1); 1713 if (ZAdd == OperandExtendedAdd) { 1714 // Cache knowledge of AR NW, which is propagated to this AddRec. 1715 // Negative step causes unsigned wrap, but it still can't self-wrap. 1716 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1717 // Return the expression with the addrec on the outside. 1718 return getAddRecExpr( 1719 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1720 Depth + 1), 1721 getSignExtendExpr(Step, Ty, Depth + 1), L, 1722 AR->getNoWrapFlags()); 1723 } 1724 } 1725 } 1726 1727 // Normally, in the cases we can prove no-overflow via a 1728 // backedge guarding condition, we can also compute a backedge 1729 // taken count for the loop. The exceptions are assumptions and 1730 // guards present in the loop -- SCEV is not great at exploiting 1731 // these to compute max backedge taken counts, but can still use 1732 // these to prove lack of overflow. Use this fact to avoid 1733 // doing extra work that may not pay off. 1734 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1735 !AC.assumptions().empty()) { 1736 1737 auto NewFlags = proveNoUnsignedWrapViaInduction(AR); 1738 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1739 if (AR->hasNoUnsignedWrap()) { 1740 // Same as nuw case above - duplicated here to avoid a compile time 1741 // issue. It's not clear that the order of checks does matter, but 1742 // it's one of two issue possible causes for a change which was 1743 // reverted. Be conservative for the moment. 1744 return getAddRecExpr( 1745 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1746 Depth + 1), 1747 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1748 AR->getNoWrapFlags()); 1749 } 1750 1751 // For a negative step, we can extend the operands iff doing so only 1752 // traverses values in the range zext([0,UINT_MAX]). 1753 if (isKnownNegative(Step)) { 1754 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1755 getSignedRangeMin(Step)); 1756 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1757 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1758 // Cache knowledge of AR NW, which is propagated to this 1759 // AddRec. Negative step causes unsigned wrap, but it 1760 // still can't self-wrap. 1761 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 1762 // Return the expression with the addrec on the outside. 1763 return getAddRecExpr( 1764 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1765 Depth + 1), 1766 getSignExtendExpr(Step, Ty, Depth + 1), L, 1767 AR->getNoWrapFlags()); 1768 } 1769 } 1770 } 1771 1772 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1773 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1774 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1775 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1776 const APInt &C = SC->getAPInt(); 1777 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1778 if (D != 0) { 1779 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1780 const SCEV *SResidual = 1781 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1782 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1783 return getAddExpr(SZExtD, SZExtR, 1784 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1785 Depth + 1); 1786 } 1787 } 1788 1789 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1790 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW); 1791 return getAddRecExpr( 1792 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1793 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1794 } 1795 } 1796 1797 // zext(A % B) --> zext(A) % zext(B) 1798 { 1799 const SCEV *LHS; 1800 const SCEV *RHS; 1801 if (matchURem(Op, LHS, RHS)) 1802 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1803 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1804 } 1805 1806 // zext(A / B) --> zext(A) / zext(B). 1807 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1808 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1809 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1810 1811 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1812 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1813 if (SA->hasNoUnsignedWrap()) { 1814 // If the addition does not unsign overflow then we can, by definition, 1815 // commute the zero extension with the addition operation. 1816 SmallVector<const SCEV *, 4> Ops; 1817 for (const auto *Op : SA->operands()) 1818 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1819 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1820 } 1821 1822 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1823 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1824 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1825 // 1826 // Often address arithmetics contain expressions like 1827 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1828 // This transformation is useful while proving that such expressions are 1829 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1830 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1831 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1832 if (D != 0) { 1833 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1834 const SCEV *SResidual = 1835 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1836 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1837 return getAddExpr(SZExtD, SZExtR, 1838 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1839 Depth + 1); 1840 } 1841 } 1842 } 1843 1844 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1845 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1846 if (SM->hasNoUnsignedWrap()) { 1847 // If the multiply does not unsign overflow then we can, by definition, 1848 // commute the zero extension with the multiply operation. 1849 SmallVector<const SCEV *, 4> Ops; 1850 for (const auto *Op : SM->operands()) 1851 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1852 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1853 } 1854 1855 // zext(2^K * (trunc X to iN)) to iM -> 1856 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1857 // 1858 // Proof: 1859 // 1860 // zext(2^K * (trunc X to iN)) to iM 1861 // = zext((trunc X to iN) << K) to iM 1862 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1863 // (because shl removes the top K bits) 1864 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1865 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1866 // 1867 if (SM->getNumOperands() == 2) 1868 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1869 if (MulLHS->getAPInt().isPowerOf2()) 1870 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1871 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1872 MulLHS->getAPInt().logBase2(); 1873 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1874 return getMulExpr( 1875 getZeroExtendExpr(MulLHS, Ty), 1876 getZeroExtendExpr( 1877 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1878 SCEV::FlagNUW, Depth + 1); 1879 } 1880 } 1881 1882 // The cast wasn't folded; create an explicit cast node. 1883 // Recompute the insert position, as it may have been invalidated. 1884 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1885 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1886 Op, Ty); 1887 UniqueSCEVs.InsertNode(S, IP); 1888 registerUser(S, Op); 1889 return S; 1890 } 1891 1892 const SCEV * 1893 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1894 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1895 "This is not an extending conversion!"); 1896 assert(isSCEVable(Ty) && 1897 "This is not a conversion to a SCEVable type!"); 1898 assert(!Op->getType()->isPointerTy() && "Can't extend pointer!"); 1899 Ty = getEffectiveSCEVType(Ty); 1900 1901 // Fold if the operand is constant. 1902 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1903 return getConstant( 1904 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1905 1906 // sext(sext(x)) --> sext(x) 1907 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1908 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1909 1910 // sext(zext(x)) --> zext(x) 1911 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1912 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1913 1914 // Before doing any expensive analysis, check to see if we've already 1915 // computed a SCEV for this Op and Ty. 1916 FoldingSetNodeID ID; 1917 ID.AddInteger(scSignExtend); 1918 ID.AddPointer(Op); 1919 ID.AddPointer(Ty); 1920 void *IP = nullptr; 1921 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1922 // Limit recursion depth. 1923 if (Depth > MaxCastDepth) { 1924 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1925 Op, Ty); 1926 UniqueSCEVs.InsertNode(S, IP); 1927 registerUser(S, Op); 1928 return S; 1929 } 1930 1931 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1932 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1933 // It's possible the bits taken off by the truncate were all sign bits. If 1934 // so, we should be able to simplify this further. 1935 const SCEV *X = ST->getOperand(); 1936 ConstantRange CR = getSignedRange(X); 1937 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1938 unsigned NewBits = getTypeSizeInBits(Ty); 1939 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1940 CR.sextOrTrunc(NewBits))) 1941 return getTruncateOrSignExtend(X, Ty, Depth); 1942 } 1943 1944 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1945 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1946 if (SA->hasNoSignedWrap()) { 1947 // If the addition does not sign overflow then we can, by definition, 1948 // commute the sign extension with the addition operation. 1949 SmallVector<const SCEV *, 4> Ops; 1950 for (const auto *Op : SA->operands()) 1951 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1952 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1953 } 1954 1955 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1956 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1957 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1958 // 1959 // For instance, this will bring two seemingly different expressions: 1960 // 1 + sext(5 + 20 * %x + 24 * %y) and 1961 // sext(6 + 20 * %x + 24 * %y) 1962 // to the same form: 1963 // 2 + sext(4 + 20 * %x + 24 * %y) 1964 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1965 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1966 if (D != 0) { 1967 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1968 const SCEV *SResidual = 1969 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1970 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1971 return getAddExpr(SSExtD, SSExtR, 1972 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1973 Depth + 1); 1974 } 1975 } 1976 } 1977 // If the input value is a chrec scev, and we can prove that the value 1978 // did not overflow the old, smaller, value, we can sign extend all of the 1979 // operands (often constants). This allows analysis of something like 1980 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1981 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1982 if (AR->isAffine()) { 1983 const SCEV *Start = AR->getStart(); 1984 const SCEV *Step = AR->getStepRecurrence(*this); 1985 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1986 const Loop *L = AR->getLoop(); 1987 1988 if (!AR->hasNoSignedWrap()) { 1989 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1990 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 1991 } 1992 1993 // If we have special knowledge that this addrec won't overflow, 1994 // we don't need to do any further analysis. 1995 if (AR->hasNoSignedWrap()) 1996 return getAddRecExpr( 1997 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1998 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1999 2000 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2001 // Note that this serves two purposes: It filters out loops that are 2002 // simply not analyzable, and it covers the case where this code is 2003 // being called from within backedge-taken count analysis, such that 2004 // attempting to ask for the backedge-taken count would likely result 2005 // in infinite recursion. In the later case, the analysis code will 2006 // cope with a conservative value, and it will take care to purge 2007 // that value once it has finished. 2008 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2009 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2010 // Manually compute the final value for AR, checking for 2011 // overflow. 2012 2013 // Check whether the backedge-taken count can be losslessly casted to 2014 // the addrec's type. The count is always unsigned. 2015 const SCEV *CastedMaxBECount = 2016 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2017 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2018 CastedMaxBECount, MaxBECount->getType(), Depth); 2019 if (MaxBECount == RecastedMaxBECount) { 2020 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2021 // Check whether Start+Step*MaxBECount has no signed overflow. 2022 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2023 SCEV::FlagAnyWrap, Depth + 1); 2024 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2025 SCEV::FlagAnyWrap, 2026 Depth + 1), 2027 WideTy, Depth + 1); 2028 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2029 const SCEV *WideMaxBECount = 2030 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2031 const SCEV *OperandExtendedAdd = 2032 getAddExpr(WideStart, 2033 getMulExpr(WideMaxBECount, 2034 getSignExtendExpr(Step, WideTy, Depth + 1), 2035 SCEV::FlagAnyWrap, Depth + 1), 2036 SCEV::FlagAnyWrap, Depth + 1); 2037 if (SAdd == OperandExtendedAdd) { 2038 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2039 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2040 // Return the expression with the addrec on the outside. 2041 return getAddRecExpr( 2042 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2043 Depth + 1), 2044 getSignExtendExpr(Step, Ty, Depth + 1), L, 2045 AR->getNoWrapFlags()); 2046 } 2047 // Similar to above, only this time treat the step value as unsigned. 2048 // This covers loops that count up with an unsigned step. 2049 OperandExtendedAdd = 2050 getAddExpr(WideStart, 2051 getMulExpr(WideMaxBECount, 2052 getZeroExtendExpr(Step, WideTy, Depth + 1), 2053 SCEV::FlagAnyWrap, Depth + 1), 2054 SCEV::FlagAnyWrap, Depth + 1); 2055 if (SAdd == OperandExtendedAdd) { 2056 // If AR wraps around then 2057 // 2058 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2059 // => SAdd != OperandExtendedAdd 2060 // 2061 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2062 // (SAdd == OperandExtendedAdd => AR is NW) 2063 2064 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW); 2065 2066 // Return the expression with the addrec on the outside. 2067 return getAddRecExpr( 2068 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2069 Depth + 1), 2070 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2071 AR->getNoWrapFlags()); 2072 } 2073 } 2074 } 2075 2076 auto NewFlags = proveNoSignedWrapViaInduction(AR); 2077 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags); 2078 if (AR->hasNoSignedWrap()) { 2079 // Same as nsw case above - duplicated here to avoid a compile time 2080 // issue. It's not clear that the order of checks does matter, but 2081 // it's one of two issue possible causes for a change which was 2082 // reverted. Be conservative for the moment. 2083 return getAddRecExpr( 2084 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2085 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2086 } 2087 2088 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2089 // if D + (C - D + Step * n) could be proven to not signed wrap 2090 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2091 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2092 const APInt &C = SC->getAPInt(); 2093 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2094 if (D != 0) { 2095 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2096 const SCEV *SResidual = 2097 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2098 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2099 return getAddExpr(SSExtD, SSExtR, 2100 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2101 Depth + 1); 2102 } 2103 } 2104 2105 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2106 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW); 2107 return getAddRecExpr( 2108 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2109 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2110 } 2111 } 2112 2113 // If the input value is provably positive and we could not simplify 2114 // away the sext build a zext instead. 2115 if (isKnownNonNegative(Op)) 2116 return getZeroExtendExpr(Op, Ty, Depth + 1); 2117 2118 // The cast wasn't folded; create an explicit cast node. 2119 // Recompute the insert position, as it may have been invalidated. 2120 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2121 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2122 Op, Ty); 2123 UniqueSCEVs.InsertNode(S, IP); 2124 registerUser(S, { Op }); 2125 return S; 2126 } 2127 2128 const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op, 2129 Type *Ty) { 2130 switch (Kind) { 2131 case scTruncate: 2132 return getTruncateExpr(Op, Ty); 2133 case scZeroExtend: 2134 return getZeroExtendExpr(Op, Ty); 2135 case scSignExtend: 2136 return getSignExtendExpr(Op, Ty); 2137 case scPtrToInt: 2138 return getPtrToIntExpr(Op, Ty); 2139 default: 2140 llvm_unreachable("Not a SCEV cast expression!"); 2141 } 2142 } 2143 2144 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2145 /// unspecified bits out to the given type. 2146 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2147 Type *Ty) { 2148 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2149 "This is not an extending conversion!"); 2150 assert(isSCEVable(Ty) && 2151 "This is not a conversion to a SCEVable type!"); 2152 Ty = getEffectiveSCEVType(Ty); 2153 2154 // Sign-extend negative constants. 2155 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2156 if (SC->getAPInt().isNegative()) 2157 return getSignExtendExpr(Op, Ty); 2158 2159 // Peel off a truncate cast. 2160 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2161 const SCEV *NewOp = T->getOperand(); 2162 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2163 return getAnyExtendExpr(NewOp, Ty); 2164 return getTruncateOrNoop(NewOp, Ty); 2165 } 2166 2167 // Next try a zext cast. If the cast is folded, use it. 2168 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2169 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2170 return ZExt; 2171 2172 // Next try a sext cast. If the cast is folded, use it. 2173 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2174 if (!isa<SCEVSignExtendExpr>(SExt)) 2175 return SExt; 2176 2177 // Force the cast to be folded into the operands of an addrec. 2178 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2179 SmallVector<const SCEV *, 4> Ops; 2180 for (const SCEV *Op : AR->operands()) 2181 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2182 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2183 } 2184 2185 // If the expression is obviously signed, use the sext cast value. 2186 if (isa<SCEVSMaxExpr>(Op)) 2187 return SExt; 2188 2189 // Absent any other information, use the zext cast value. 2190 return ZExt; 2191 } 2192 2193 /// Process the given Ops list, which is a list of operands to be added under 2194 /// the given scale, update the given map. This is a helper function for 2195 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2196 /// that would form an add expression like this: 2197 /// 2198 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2199 /// 2200 /// where A and B are constants, update the map with these values: 2201 /// 2202 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2203 /// 2204 /// and add 13 + A*B*29 to AccumulatedConstant. 2205 /// This will allow getAddRecExpr to produce this: 2206 /// 2207 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2208 /// 2209 /// This form often exposes folding opportunities that are hidden in 2210 /// the original operand list. 2211 /// 2212 /// Return true iff it appears that any interesting folding opportunities 2213 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2214 /// the common case where no interesting opportunities are present, and 2215 /// is also used as a check to avoid infinite recursion. 2216 static bool 2217 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2218 SmallVectorImpl<const SCEV *> &NewOps, 2219 APInt &AccumulatedConstant, 2220 const SCEV *const *Ops, size_t NumOperands, 2221 const APInt &Scale, 2222 ScalarEvolution &SE) { 2223 bool Interesting = false; 2224 2225 // Iterate over the add operands. They are sorted, with constants first. 2226 unsigned i = 0; 2227 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2228 ++i; 2229 // Pull a buried constant out to the outside. 2230 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2231 Interesting = true; 2232 AccumulatedConstant += Scale * C->getAPInt(); 2233 } 2234 2235 // Next comes everything else. We're especially interested in multiplies 2236 // here, but they're in the middle, so just visit the rest with one loop. 2237 for (; i != NumOperands; ++i) { 2238 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2239 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2240 APInt NewScale = 2241 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2242 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2243 // A multiplication of a constant with another add; recurse. 2244 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2245 Interesting |= 2246 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2247 Add->op_begin(), Add->getNumOperands(), 2248 NewScale, SE); 2249 } else { 2250 // A multiplication of a constant with some other value. Update 2251 // the map. 2252 SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands())); 2253 const SCEV *Key = SE.getMulExpr(MulOps); 2254 auto Pair = M.insert({Key, NewScale}); 2255 if (Pair.second) { 2256 NewOps.push_back(Pair.first->first); 2257 } else { 2258 Pair.first->second += NewScale; 2259 // The map already had an entry for this value, which may indicate 2260 // a folding opportunity. 2261 Interesting = true; 2262 } 2263 } 2264 } else { 2265 // An ordinary operand. Update the map. 2266 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2267 M.insert({Ops[i], Scale}); 2268 if (Pair.second) { 2269 NewOps.push_back(Pair.first->first); 2270 } else { 2271 Pair.first->second += Scale; 2272 // The map already had an entry for this value, which may indicate 2273 // a folding opportunity. 2274 Interesting = true; 2275 } 2276 } 2277 } 2278 2279 return Interesting; 2280 } 2281 2282 bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, 2283 const SCEV *LHS, const SCEV *RHS) { 2284 const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *, 2285 SCEV::NoWrapFlags, unsigned); 2286 switch (BinOp) { 2287 default: 2288 llvm_unreachable("Unsupported binary op"); 2289 case Instruction::Add: 2290 Operation = &ScalarEvolution::getAddExpr; 2291 break; 2292 case Instruction::Sub: 2293 Operation = &ScalarEvolution::getMinusSCEV; 2294 break; 2295 case Instruction::Mul: 2296 Operation = &ScalarEvolution::getMulExpr; 2297 break; 2298 } 2299 2300 const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) = 2301 Signed ? &ScalarEvolution::getSignExtendExpr 2302 : &ScalarEvolution::getZeroExtendExpr; 2303 2304 // Check ext(LHS op RHS) == ext(LHS) op ext(RHS) 2305 auto *NarrowTy = cast<IntegerType>(LHS->getType()); 2306 auto *WideTy = 2307 IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2); 2308 2309 const SCEV *A = (this->*Extension)( 2310 (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0); 2311 const SCEV *B = (this->*Operation)((this->*Extension)(LHS, WideTy, 0), 2312 (this->*Extension)(RHS, WideTy, 0), 2313 SCEV::FlagAnyWrap, 0); 2314 return A == B; 2315 } 2316 2317 std::pair<SCEV::NoWrapFlags, bool /*Deduced*/> 2318 ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp( 2319 const OverflowingBinaryOperator *OBO) { 2320 SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap; 2321 2322 if (OBO->hasNoUnsignedWrap()) 2323 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2324 if (OBO->hasNoSignedWrap()) 2325 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2326 2327 bool Deduced = false; 2328 2329 if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap()) 2330 return {Flags, Deduced}; 2331 2332 if (OBO->getOpcode() != Instruction::Add && 2333 OBO->getOpcode() != Instruction::Sub && 2334 OBO->getOpcode() != Instruction::Mul) 2335 return {Flags, Deduced}; 2336 2337 const SCEV *LHS = getSCEV(OBO->getOperand(0)); 2338 const SCEV *RHS = getSCEV(OBO->getOperand(1)); 2339 2340 if (!OBO->hasNoUnsignedWrap() && 2341 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2342 /* Signed */ false, LHS, RHS)) { 2343 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2344 Deduced = true; 2345 } 2346 2347 if (!OBO->hasNoSignedWrap() && 2348 willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(), 2349 /* Signed */ true, LHS, RHS)) { 2350 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2351 Deduced = true; 2352 } 2353 2354 return {Flags, Deduced}; 2355 } 2356 2357 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2358 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2359 // can't-overflow flags for the operation if possible. 2360 static SCEV::NoWrapFlags 2361 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2362 const ArrayRef<const SCEV *> Ops, 2363 SCEV::NoWrapFlags Flags) { 2364 using namespace std::placeholders; 2365 2366 using OBO = OverflowingBinaryOperator; 2367 2368 bool CanAnalyze = 2369 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2370 (void)CanAnalyze; 2371 assert(CanAnalyze && "don't call from other places!"); 2372 2373 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2374 SCEV::NoWrapFlags SignOrUnsignWrap = 2375 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2376 2377 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2378 auto IsKnownNonNegative = [&](const SCEV *S) { 2379 return SE->isKnownNonNegative(S); 2380 }; 2381 2382 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2383 Flags = 2384 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2385 2386 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2387 2388 if (SignOrUnsignWrap != SignOrUnsignMask && 2389 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2390 isa<SCEVConstant>(Ops[0])) { 2391 2392 auto Opcode = [&] { 2393 switch (Type) { 2394 case scAddExpr: 2395 return Instruction::Add; 2396 case scMulExpr: 2397 return Instruction::Mul; 2398 default: 2399 llvm_unreachable("Unexpected SCEV op."); 2400 } 2401 }(); 2402 2403 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2404 2405 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2406 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2407 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2408 Opcode, C, OBO::NoSignedWrap); 2409 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2410 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2411 } 2412 2413 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2414 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2415 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2416 Opcode, C, OBO::NoUnsignedWrap); 2417 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2418 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2419 } 2420 } 2421 2422 // <0,+,nonnegative><nw> is also nuw 2423 // TODO: Add corresponding nsw case 2424 if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) && 2425 !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && 2426 Ops[0]->isZero() && IsKnownNonNegative(Ops[1])) 2427 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2428 2429 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW 2430 if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && 2431 Ops.size() == 2) { 2432 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0])) 2433 if (UDiv->getOperand(1) == Ops[1]) 2434 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2435 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1])) 2436 if (UDiv->getOperand(1) == Ops[0]) 2437 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2438 } 2439 2440 return Flags; 2441 } 2442 2443 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2444 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2445 } 2446 2447 /// Get a canonical add expression, or something simpler if possible. 2448 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2449 SCEV::NoWrapFlags OrigFlags, 2450 unsigned Depth) { 2451 assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2452 "only nuw or nsw allowed"); 2453 assert(!Ops.empty() && "Cannot get empty add!"); 2454 if (Ops.size() == 1) return Ops[0]; 2455 #ifndef NDEBUG 2456 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2457 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2458 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2459 "SCEVAddExpr operand types don't match!"); 2460 unsigned NumPtrs = count_if( 2461 Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); }); 2462 assert(NumPtrs <= 1 && "add has at most one pointer operand"); 2463 #endif 2464 2465 // Sort by complexity, this groups all similar expression types together. 2466 GroupByComplexity(Ops, &LI, DT); 2467 2468 // If there are any constants, fold them together. 2469 unsigned Idx = 0; 2470 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2471 ++Idx; 2472 assert(Idx < Ops.size()); 2473 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2474 // We found two constants, fold them together! 2475 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2476 if (Ops.size() == 2) return Ops[0]; 2477 Ops.erase(Ops.begin()+1); // Erase the folded element 2478 LHSC = cast<SCEVConstant>(Ops[0]); 2479 } 2480 2481 // If we are left with a constant zero being added, strip it off. 2482 if (LHSC->getValue()->isZero()) { 2483 Ops.erase(Ops.begin()); 2484 --Idx; 2485 } 2486 2487 if (Ops.size() == 1) return Ops[0]; 2488 } 2489 2490 // Delay expensive flag strengthening until necessary. 2491 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 2492 return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags); 2493 }; 2494 2495 // Limit recursion calls depth. 2496 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2497 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2498 2499 if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) { 2500 // Don't strengthen flags if we have no new information. 2501 SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S); 2502 if (Add->getNoWrapFlags(OrigFlags) != OrigFlags) 2503 Add->setNoWrapFlags(ComputeFlags(Ops)); 2504 return S; 2505 } 2506 2507 // Okay, check to see if the same value occurs in the operand list more than 2508 // once. If so, merge them together into an multiply expression. Since we 2509 // sorted the list, these values are required to be adjacent. 2510 Type *Ty = Ops[0]->getType(); 2511 bool FoundMatch = false; 2512 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2513 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2514 // Scan ahead to count how many equal operands there are. 2515 unsigned Count = 2; 2516 while (i+Count != e && Ops[i+Count] == Ops[i]) 2517 ++Count; 2518 // Merge the values into a multiply. 2519 const SCEV *Scale = getConstant(Ty, Count); 2520 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2521 if (Ops.size() == Count) 2522 return Mul; 2523 Ops[i] = Mul; 2524 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2525 --i; e -= Count - 1; 2526 FoundMatch = true; 2527 } 2528 if (FoundMatch) 2529 return getAddExpr(Ops, OrigFlags, Depth + 1); 2530 2531 // Check for truncates. If all the operands are truncated from the same 2532 // type, see if factoring out the truncate would permit the result to be 2533 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2534 // if the contents of the resulting outer trunc fold to something simple. 2535 auto FindTruncSrcType = [&]() -> Type * { 2536 // We're ultimately looking to fold an addrec of truncs and muls of only 2537 // constants and truncs, so if we find any other types of SCEV 2538 // as operands of the addrec then we bail and return nullptr here. 2539 // Otherwise, we return the type of the operand of a trunc that we find. 2540 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2541 return T->getOperand()->getType(); 2542 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2543 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2544 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2545 return T->getOperand()->getType(); 2546 } 2547 return nullptr; 2548 }; 2549 if (auto *SrcType = FindTruncSrcType()) { 2550 SmallVector<const SCEV *, 8> LargeOps; 2551 bool Ok = true; 2552 // Check all the operands to see if they can be represented in the 2553 // source type of the truncate. 2554 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2555 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2556 if (T->getOperand()->getType() != SrcType) { 2557 Ok = false; 2558 break; 2559 } 2560 LargeOps.push_back(T->getOperand()); 2561 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2562 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2563 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2564 SmallVector<const SCEV *, 8> LargeMulOps; 2565 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2566 if (const SCEVTruncateExpr *T = 2567 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2568 if (T->getOperand()->getType() != SrcType) { 2569 Ok = false; 2570 break; 2571 } 2572 LargeMulOps.push_back(T->getOperand()); 2573 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2574 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2575 } else { 2576 Ok = false; 2577 break; 2578 } 2579 } 2580 if (Ok) 2581 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2582 } else { 2583 Ok = false; 2584 break; 2585 } 2586 } 2587 if (Ok) { 2588 // Evaluate the expression in the larger type. 2589 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2590 // If it folds to something simple, use it. Otherwise, don't. 2591 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2592 return getTruncateExpr(Fold, Ty); 2593 } 2594 } 2595 2596 if (Ops.size() == 2) { 2597 // Check if we have an expression of the form ((X + C1) - C2), where C1 and 2598 // C2 can be folded in a way that allows retaining wrapping flags of (X + 2599 // C1). 2600 const SCEV *A = Ops[0]; 2601 const SCEV *B = Ops[1]; 2602 auto *AddExpr = dyn_cast<SCEVAddExpr>(B); 2603 auto *C = dyn_cast<SCEVConstant>(A); 2604 if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) { 2605 auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt(); 2606 auto C2 = C->getAPInt(); 2607 SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap; 2608 2609 APInt ConstAdd = C1 + C2; 2610 auto AddFlags = AddExpr->getNoWrapFlags(); 2611 // Adding a smaller constant is NUW if the original AddExpr was NUW. 2612 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) && 2613 ConstAdd.ule(C1)) { 2614 PreservedFlags = 2615 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW); 2616 } 2617 2618 // Adding a constant with the same sign and small magnitude is NSW, if the 2619 // original AddExpr was NSW. 2620 if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) && 2621 C1.isSignBitSet() == ConstAdd.isSignBitSet() && 2622 ConstAdd.abs().ule(C1.abs())) { 2623 PreservedFlags = 2624 ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW); 2625 } 2626 2627 if (PreservedFlags != SCEV::FlagAnyWrap) { 2628 SmallVector<const SCEV *, 4> NewOps(AddExpr->operands()); 2629 NewOps[0] = getConstant(ConstAdd); 2630 return getAddExpr(NewOps, PreservedFlags); 2631 } 2632 } 2633 } 2634 2635 // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y) 2636 if (Ops.size() == 2) { 2637 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]); 2638 if (Mul && Mul->getNumOperands() == 2 && 2639 Mul->getOperand(0)->isAllOnesValue()) { 2640 const SCEV *X; 2641 const SCEV *Y; 2642 if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) { 2643 return getMulExpr(Y, getUDivExpr(X, Y)); 2644 } 2645 } 2646 } 2647 2648 // Skip past any other cast SCEVs. 2649 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2650 ++Idx; 2651 2652 // If there are add operands they would be next. 2653 if (Idx < Ops.size()) { 2654 bool DeletedAdd = false; 2655 // If the original flags and all inlined SCEVAddExprs are NUW, use the 2656 // common NUW flag for expression after inlining. Other flags cannot be 2657 // preserved, because they may depend on the original order of operations. 2658 SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW); 2659 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2660 if (Ops.size() > AddOpsInlineThreshold || 2661 Add->getNumOperands() > AddOpsInlineThreshold) 2662 break; 2663 // If we have an add, expand the add operands onto the end of the operands 2664 // list. 2665 Ops.erase(Ops.begin()+Idx); 2666 Ops.append(Add->op_begin(), Add->op_end()); 2667 DeletedAdd = true; 2668 CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags()); 2669 } 2670 2671 // If we deleted at least one add, we added operands to the end of the list, 2672 // and they are not necessarily sorted. Recurse to resort and resimplify 2673 // any operands we just acquired. 2674 if (DeletedAdd) 2675 return getAddExpr(Ops, CommonFlags, Depth + 1); 2676 } 2677 2678 // Skip over the add expression until we get to a multiply. 2679 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2680 ++Idx; 2681 2682 // Check to see if there are any folding opportunities present with 2683 // operands multiplied by constant values. 2684 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2685 uint64_t BitWidth = getTypeSizeInBits(Ty); 2686 DenseMap<const SCEV *, APInt> M; 2687 SmallVector<const SCEV *, 8> NewOps; 2688 APInt AccumulatedConstant(BitWidth, 0); 2689 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2690 Ops.data(), Ops.size(), 2691 APInt(BitWidth, 1), *this)) { 2692 struct APIntCompare { 2693 bool operator()(const APInt &LHS, const APInt &RHS) const { 2694 return LHS.ult(RHS); 2695 } 2696 }; 2697 2698 // Some interesting folding opportunity is present, so its worthwhile to 2699 // re-generate the operands list. Group the operands by constant scale, 2700 // to avoid multiplying by the same constant scale multiple times. 2701 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2702 for (const SCEV *NewOp : NewOps) 2703 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2704 // Re-generate the operands list. 2705 Ops.clear(); 2706 if (AccumulatedConstant != 0) 2707 Ops.push_back(getConstant(AccumulatedConstant)); 2708 for (auto &MulOp : MulOpLists) { 2709 if (MulOp.first == 1) { 2710 Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1)); 2711 } else if (MulOp.first != 0) { 2712 Ops.push_back(getMulExpr( 2713 getConstant(MulOp.first), 2714 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2715 SCEV::FlagAnyWrap, Depth + 1)); 2716 } 2717 } 2718 if (Ops.empty()) 2719 return getZero(Ty); 2720 if (Ops.size() == 1) 2721 return Ops[0]; 2722 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2723 } 2724 } 2725 2726 // If we are adding something to a multiply expression, make sure the 2727 // something is not already an operand of the multiply. If so, merge it into 2728 // the multiply. 2729 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2730 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2731 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2732 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2733 if (isa<SCEVConstant>(MulOpSCEV)) 2734 continue; 2735 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2736 if (MulOpSCEV == Ops[AddOp]) { 2737 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2738 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2739 if (Mul->getNumOperands() != 2) { 2740 // If the multiply has more than two operands, we must get the 2741 // Y*Z term. 2742 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2743 Mul->op_begin()+MulOp); 2744 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2745 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2746 } 2747 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2748 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2749 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2750 SCEV::FlagAnyWrap, Depth + 1); 2751 if (Ops.size() == 2) return OuterMul; 2752 if (AddOp < Idx) { 2753 Ops.erase(Ops.begin()+AddOp); 2754 Ops.erase(Ops.begin()+Idx-1); 2755 } else { 2756 Ops.erase(Ops.begin()+Idx); 2757 Ops.erase(Ops.begin()+AddOp-1); 2758 } 2759 Ops.push_back(OuterMul); 2760 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2761 } 2762 2763 // Check this multiply against other multiplies being added together. 2764 for (unsigned OtherMulIdx = Idx+1; 2765 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2766 ++OtherMulIdx) { 2767 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2768 // If MulOp occurs in OtherMul, we can fold the two multiplies 2769 // together. 2770 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2771 OMulOp != e; ++OMulOp) 2772 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2773 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2774 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2775 if (Mul->getNumOperands() != 2) { 2776 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2777 Mul->op_begin()+MulOp); 2778 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2779 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2780 } 2781 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2782 if (OtherMul->getNumOperands() != 2) { 2783 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2784 OtherMul->op_begin()+OMulOp); 2785 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2786 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2787 } 2788 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2789 const SCEV *InnerMulSum = 2790 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2791 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2792 SCEV::FlagAnyWrap, Depth + 1); 2793 if (Ops.size() == 2) return OuterMul; 2794 Ops.erase(Ops.begin()+Idx); 2795 Ops.erase(Ops.begin()+OtherMulIdx-1); 2796 Ops.push_back(OuterMul); 2797 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2798 } 2799 } 2800 } 2801 } 2802 2803 // If there are any add recurrences in the operands list, see if any other 2804 // added values are loop invariant. If so, we can fold them into the 2805 // recurrence. 2806 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2807 ++Idx; 2808 2809 // Scan over all recurrences, trying to fold loop invariants into them. 2810 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2811 // Scan all of the other operands to this add and add them to the vector if 2812 // they are loop invariant w.r.t. the recurrence. 2813 SmallVector<const SCEV *, 8> LIOps; 2814 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2815 const Loop *AddRecLoop = AddRec->getLoop(); 2816 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2817 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2818 LIOps.push_back(Ops[i]); 2819 Ops.erase(Ops.begin()+i); 2820 --i; --e; 2821 } 2822 2823 // If we found some loop invariants, fold them into the recurrence. 2824 if (!LIOps.empty()) { 2825 // Compute nowrap flags for the addition of the loop-invariant ops and 2826 // the addrec. Temporarily push it as an operand for that purpose. These 2827 // flags are valid in the scope of the addrec only. 2828 LIOps.push_back(AddRec); 2829 SCEV::NoWrapFlags Flags = ComputeFlags(LIOps); 2830 LIOps.pop_back(); 2831 2832 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2833 LIOps.push_back(AddRec->getStart()); 2834 2835 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2836 2837 // It is not in general safe to propagate flags valid on an add within 2838 // the addrec scope to one outside it. We must prove that the inner 2839 // scope is guaranteed to execute if the outer one does to be able to 2840 // safely propagate. We know the program is undefined if poison is 2841 // produced on the inner scoped addrec. We also know that *for this use* 2842 // the outer scoped add can't overflow (because of the flags we just 2843 // computed for the inner scoped add) without the program being undefined. 2844 // Proving that entry to the outer scope neccesitates entry to the inner 2845 // scope, thus proves the program undefined if the flags would be violated 2846 // in the outer scope. 2847 SCEV::NoWrapFlags AddFlags = Flags; 2848 if (AddFlags != SCEV::FlagAnyWrap) { 2849 auto *DefI = getDefiningScopeBound(LIOps); 2850 auto *ReachI = &*AddRecLoop->getHeader()->begin(); 2851 if (!isGuaranteedToTransferExecutionTo(DefI, ReachI)) 2852 AddFlags = SCEV::FlagAnyWrap; 2853 } 2854 AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1); 2855 2856 // Build the new addrec. Propagate the NUW and NSW flags if both the 2857 // outer add and the inner addrec are guaranteed to have no overflow. 2858 // Always propagate NW. 2859 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2860 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2861 2862 // If all of the other operands were loop invariant, we are done. 2863 if (Ops.size() == 1) return NewRec; 2864 2865 // Otherwise, add the folded AddRec by the non-invariant parts. 2866 for (unsigned i = 0;; ++i) 2867 if (Ops[i] == AddRec) { 2868 Ops[i] = NewRec; 2869 break; 2870 } 2871 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2872 } 2873 2874 // Okay, if there weren't any loop invariants to be folded, check to see if 2875 // there are multiple AddRec's with the same loop induction variable being 2876 // added together. If so, we can fold them. 2877 for (unsigned OtherIdx = Idx+1; 2878 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2879 ++OtherIdx) { 2880 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2881 // so that the 1st found AddRecExpr is dominated by all others. 2882 assert(DT.dominates( 2883 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2884 AddRec->getLoop()->getHeader()) && 2885 "AddRecExprs are not sorted in reverse dominance order?"); 2886 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2887 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2888 SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands()); 2889 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2890 ++OtherIdx) { 2891 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2892 if (OtherAddRec->getLoop() == AddRecLoop) { 2893 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2894 i != e; ++i) { 2895 if (i >= AddRecOps.size()) { 2896 AddRecOps.append(OtherAddRec->op_begin()+i, 2897 OtherAddRec->op_end()); 2898 break; 2899 } 2900 SmallVector<const SCEV *, 2> TwoOps = { 2901 AddRecOps[i], OtherAddRec->getOperand(i)}; 2902 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2903 } 2904 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2905 } 2906 } 2907 // Step size has changed, so we cannot guarantee no self-wraparound. 2908 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2909 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2910 } 2911 } 2912 2913 // Otherwise couldn't fold anything into this recurrence. Move onto the 2914 // next one. 2915 } 2916 2917 // Okay, it looks like we really DO need an add expr. Check to see if we 2918 // already have one, otherwise create a new one. 2919 return getOrCreateAddExpr(Ops, ComputeFlags(Ops)); 2920 } 2921 2922 const SCEV * 2923 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2924 SCEV::NoWrapFlags Flags) { 2925 FoldingSetNodeID ID; 2926 ID.AddInteger(scAddExpr); 2927 for (const SCEV *Op : Ops) 2928 ID.AddPointer(Op); 2929 void *IP = nullptr; 2930 SCEVAddExpr *S = 2931 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2932 if (!S) { 2933 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2934 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2935 S = new (SCEVAllocator) 2936 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2937 UniqueSCEVs.InsertNode(S, IP); 2938 registerUser(S, Ops); 2939 } 2940 S->setNoWrapFlags(Flags); 2941 return S; 2942 } 2943 2944 const SCEV * 2945 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2946 const Loop *L, SCEV::NoWrapFlags Flags) { 2947 FoldingSetNodeID ID; 2948 ID.AddInteger(scAddRecExpr); 2949 for (const SCEV *Op : Ops) 2950 ID.AddPointer(Op); 2951 ID.AddPointer(L); 2952 void *IP = nullptr; 2953 SCEVAddRecExpr *S = 2954 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2955 if (!S) { 2956 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2957 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2958 S = new (SCEVAllocator) 2959 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2960 UniqueSCEVs.InsertNode(S, IP); 2961 LoopUsers[L].push_back(S); 2962 registerUser(S, Ops); 2963 } 2964 setNoWrapFlags(S, Flags); 2965 return S; 2966 } 2967 2968 const SCEV * 2969 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2970 SCEV::NoWrapFlags Flags) { 2971 FoldingSetNodeID ID; 2972 ID.AddInteger(scMulExpr); 2973 for (const SCEV *Op : Ops) 2974 ID.AddPointer(Op); 2975 void *IP = nullptr; 2976 SCEVMulExpr *S = 2977 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2978 if (!S) { 2979 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2980 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2981 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2982 O, Ops.size()); 2983 UniqueSCEVs.InsertNode(S, IP); 2984 registerUser(S, Ops); 2985 } 2986 S->setNoWrapFlags(Flags); 2987 return S; 2988 } 2989 2990 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2991 uint64_t k = i*j; 2992 if (j > 1 && k / j != i) Overflow = true; 2993 return k; 2994 } 2995 2996 /// Compute the result of "n choose k", the binomial coefficient. If an 2997 /// intermediate computation overflows, Overflow will be set and the return will 2998 /// be garbage. Overflow is not cleared on absence of overflow. 2999 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 3000 // We use the multiplicative formula: 3001 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 3002 // At each iteration, we take the n-th term of the numeral and divide by the 3003 // (k-n)th term of the denominator. This division will always produce an 3004 // integral result, and helps reduce the chance of overflow in the 3005 // intermediate computations. However, we can still overflow even when the 3006 // final result would fit. 3007 3008 if (n == 0 || n == k) return 1; 3009 if (k > n) return 0; 3010 3011 if (k > n/2) 3012 k = n-k; 3013 3014 uint64_t r = 1; 3015 for (uint64_t i = 1; i <= k; ++i) { 3016 r = umul_ov(r, n-(i-1), Overflow); 3017 r /= i; 3018 } 3019 return r; 3020 } 3021 3022 /// Determine if any of the operands in this SCEV are a constant or if 3023 /// any of the add or multiply expressions in this SCEV contain a constant. 3024 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 3025 struct FindConstantInAddMulChain { 3026 bool FoundConstant = false; 3027 3028 bool follow(const SCEV *S) { 3029 FoundConstant |= isa<SCEVConstant>(S); 3030 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 3031 } 3032 3033 bool isDone() const { 3034 return FoundConstant; 3035 } 3036 }; 3037 3038 FindConstantInAddMulChain F; 3039 SCEVTraversal<FindConstantInAddMulChain> ST(F); 3040 ST.visitAll(StartExpr); 3041 return F.FoundConstant; 3042 } 3043 3044 /// Get a canonical multiply expression, or something simpler if possible. 3045 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 3046 SCEV::NoWrapFlags OrigFlags, 3047 unsigned Depth) { 3048 assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) && 3049 "only nuw or nsw allowed"); 3050 assert(!Ops.empty() && "Cannot get empty mul!"); 3051 if (Ops.size() == 1) return Ops[0]; 3052 #ifndef NDEBUG 3053 Type *ETy = Ops[0]->getType(); 3054 assert(!ETy->isPointerTy()); 3055 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3056 assert(Ops[i]->getType() == ETy && 3057 "SCEVMulExpr operand types don't match!"); 3058 #endif 3059 3060 // Sort by complexity, this groups all similar expression types together. 3061 GroupByComplexity(Ops, &LI, DT); 3062 3063 // If there are any constants, fold them together. 3064 unsigned Idx = 0; 3065 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3066 ++Idx; 3067 assert(Idx < Ops.size()); 3068 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3069 // We found two constants, fold them together! 3070 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 3071 if (Ops.size() == 2) return Ops[0]; 3072 Ops.erase(Ops.begin()+1); // Erase the folded element 3073 LHSC = cast<SCEVConstant>(Ops[0]); 3074 } 3075 3076 // If we have a multiply of zero, it will always be zero. 3077 if (LHSC->getValue()->isZero()) 3078 return LHSC; 3079 3080 // If we are left with a constant one being multiplied, strip it off. 3081 if (LHSC->getValue()->isOne()) { 3082 Ops.erase(Ops.begin()); 3083 --Idx; 3084 } 3085 3086 if (Ops.size() == 1) 3087 return Ops[0]; 3088 } 3089 3090 // Delay expensive flag strengthening until necessary. 3091 auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) { 3092 return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags); 3093 }; 3094 3095 // Limit recursion calls depth. 3096 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 3097 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3098 3099 if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) { 3100 // Don't strengthen flags if we have no new information. 3101 SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S); 3102 if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags) 3103 Mul->setNoWrapFlags(ComputeFlags(Ops)); 3104 return S; 3105 } 3106 3107 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3108 if (Ops.size() == 2) { 3109 // C1*(C2+V) -> C1*C2 + C1*V 3110 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 3111 // If any of Add's ops are Adds or Muls with a constant, apply this 3112 // transformation as well. 3113 // 3114 // TODO: There are some cases where this transformation is not 3115 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 3116 // this transformation should be narrowed down. 3117 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 3118 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 3119 SCEV::FlagAnyWrap, Depth + 1), 3120 getMulExpr(LHSC, Add->getOperand(1), 3121 SCEV::FlagAnyWrap, Depth + 1), 3122 SCEV::FlagAnyWrap, Depth + 1); 3123 3124 if (Ops[0]->isAllOnesValue()) { 3125 // If we have a mul by -1 of an add, try distributing the -1 among the 3126 // add operands. 3127 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 3128 SmallVector<const SCEV *, 4> NewOps; 3129 bool AnyFolded = false; 3130 for (const SCEV *AddOp : Add->operands()) { 3131 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 3132 Depth + 1); 3133 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 3134 NewOps.push_back(Mul); 3135 } 3136 if (AnyFolded) 3137 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 3138 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 3139 // Negation preserves a recurrence's no self-wrap property. 3140 SmallVector<const SCEV *, 4> Operands; 3141 for (const SCEV *AddRecOp : AddRec->operands()) 3142 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3143 Depth + 1)); 3144 3145 return getAddRecExpr(Operands, AddRec->getLoop(), 3146 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3147 } 3148 } 3149 } 3150 } 3151 3152 // Skip over the add expression until we get to a multiply. 3153 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3154 ++Idx; 3155 3156 // If there are mul operands inline them all into this expression. 3157 if (Idx < Ops.size()) { 3158 bool DeletedMul = false; 3159 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3160 if (Ops.size() > MulOpsInlineThreshold) 3161 break; 3162 // If we have an mul, expand the mul operands onto the end of the 3163 // operands list. 3164 Ops.erase(Ops.begin()+Idx); 3165 Ops.append(Mul->op_begin(), Mul->op_end()); 3166 DeletedMul = true; 3167 } 3168 3169 // If we deleted at least one mul, we added operands to the end of the 3170 // list, and they are not necessarily sorted. Recurse to resort and 3171 // resimplify any operands we just acquired. 3172 if (DeletedMul) 3173 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3174 } 3175 3176 // If there are any add recurrences in the operands list, see if any other 3177 // added values are loop invariant. If so, we can fold them into the 3178 // recurrence. 3179 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3180 ++Idx; 3181 3182 // Scan over all recurrences, trying to fold loop invariants into them. 3183 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3184 // Scan all of the other operands to this mul and add them to the vector 3185 // if they are loop invariant w.r.t. the recurrence. 3186 SmallVector<const SCEV *, 8> LIOps; 3187 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3188 const Loop *AddRecLoop = AddRec->getLoop(); 3189 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3190 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3191 LIOps.push_back(Ops[i]); 3192 Ops.erase(Ops.begin()+i); 3193 --i; --e; 3194 } 3195 3196 // If we found some loop invariants, fold them into the recurrence. 3197 if (!LIOps.empty()) { 3198 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3199 SmallVector<const SCEV *, 4> NewOps; 3200 NewOps.reserve(AddRec->getNumOperands()); 3201 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3202 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3203 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3204 SCEV::FlagAnyWrap, Depth + 1)); 3205 3206 // Build the new addrec. Propagate the NUW and NSW flags if both the 3207 // outer mul and the inner addrec are guaranteed to have no overflow. 3208 // 3209 // No self-wrap cannot be guaranteed after changing the step size, but 3210 // will be inferred if either NUW or NSW is true. 3211 SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec}); 3212 const SCEV *NewRec = getAddRecExpr( 3213 NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags)); 3214 3215 // If all of the other operands were loop invariant, we are done. 3216 if (Ops.size() == 1) return NewRec; 3217 3218 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3219 for (unsigned i = 0;; ++i) 3220 if (Ops[i] == AddRec) { 3221 Ops[i] = NewRec; 3222 break; 3223 } 3224 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3225 } 3226 3227 // Okay, if there weren't any loop invariants to be folded, check to see 3228 // if there are multiple AddRec's with the same loop induction variable 3229 // being multiplied together. If so, we can fold them. 3230 3231 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3232 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3233 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3234 // ]]],+,...up to x=2n}. 3235 // Note that the arguments to choose() are always integers with values 3236 // known at compile time, never SCEV objects. 3237 // 3238 // The implementation avoids pointless extra computations when the two 3239 // addrec's are of different length (mathematically, it's equivalent to 3240 // an infinite stream of zeros on the right). 3241 bool OpsModified = false; 3242 for (unsigned OtherIdx = Idx+1; 3243 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3244 ++OtherIdx) { 3245 const SCEVAddRecExpr *OtherAddRec = 3246 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3247 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3248 continue; 3249 3250 // Limit max number of arguments to avoid creation of unreasonably big 3251 // SCEVAddRecs with very complex operands. 3252 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3253 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3254 continue; 3255 3256 bool Overflow = false; 3257 Type *Ty = AddRec->getType(); 3258 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3259 SmallVector<const SCEV*, 7> AddRecOps; 3260 for (int x = 0, xe = AddRec->getNumOperands() + 3261 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3262 SmallVector <const SCEV *, 7> SumOps; 3263 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3264 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3265 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3266 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3267 z < ze && !Overflow; ++z) { 3268 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3269 uint64_t Coeff; 3270 if (LargerThan64Bits) 3271 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3272 else 3273 Coeff = Coeff1*Coeff2; 3274 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3275 const SCEV *Term1 = AddRec->getOperand(y-z); 3276 const SCEV *Term2 = OtherAddRec->getOperand(z); 3277 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3278 SCEV::FlagAnyWrap, Depth + 1)); 3279 } 3280 } 3281 if (SumOps.empty()) 3282 SumOps.push_back(getZero(Ty)); 3283 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3284 } 3285 if (!Overflow) { 3286 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3287 SCEV::FlagAnyWrap); 3288 if (Ops.size() == 2) return NewAddRec; 3289 Ops[Idx] = NewAddRec; 3290 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3291 OpsModified = true; 3292 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3293 if (!AddRec) 3294 break; 3295 } 3296 } 3297 if (OpsModified) 3298 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3299 3300 // Otherwise couldn't fold anything into this recurrence. Move onto the 3301 // next one. 3302 } 3303 3304 // Okay, it looks like we really DO need an mul expr. Check to see if we 3305 // already have one, otherwise create a new one. 3306 return getOrCreateMulExpr(Ops, ComputeFlags(Ops)); 3307 } 3308 3309 /// Represents an unsigned remainder expression based on unsigned division. 3310 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3311 const SCEV *RHS) { 3312 assert(getEffectiveSCEVType(LHS->getType()) == 3313 getEffectiveSCEVType(RHS->getType()) && 3314 "SCEVURemExpr operand types don't match!"); 3315 3316 // Short-circuit easy cases 3317 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3318 // If constant is one, the result is trivial 3319 if (RHSC->getValue()->isOne()) 3320 return getZero(LHS->getType()); // X urem 1 --> 0 3321 3322 // If constant is a power of two, fold into a zext(trunc(LHS)). 3323 if (RHSC->getAPInt().isPowerOf2()) { 3324 Type *FullTy = LHS->getType(); 3325 Type *TruncTy = 3326 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3327 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3328 } 3329 } 3330 3331 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3332 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3333 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3334 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3335 } 3336 3337 /// Get a canonical unsigned division expression, or something simpler if 3338 /// possible. 3339 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3340 const SCEV *RHS) { 3341 assert(!LHS->getType()->isPointerTy() && 3342 "SCEVUDivExpr operand can't be pointer!"); 3343 assert(LHS->getType() == RHS->getType() && 3344 "SCEVUDivExpr operand types don't match!"); 3345 3346 FoldingSetNodeID ID; 3347 ID.AddInteger(scUDivExpr); 3348 ID.AddPointer(LHS); 3349 ID.AddPointer(RHS); 3350 void *IP = nullptr; 3351 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3352 return S; 3353 3354 // 0 udiv Y == 0 3355 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) 3356 if (LHSC->getValue()->isZero()) 3357 return LHS; 3358 3359 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3360 if (RHSC->getValue()->isOne()) 3361 return LHS; // X udiv 1 --> x 3362 // If the denominator is zero, the result of the udiv is undefined. Don't 3363 // try to analyze it, because the resolution chosen here may differ from 3364 // the resolution chosen in other parts of the compiler. 3365 if (!RHSC->getValue()->isZero()) { 3366 // Determine if the division can be folded into the operands of 3367 // its operands. 3368 // TODO: Generalize this to non-constants by using known-bits information. 3369 Type *Ty = LHS->getType(); 3370 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3371 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3372 // For non-power-of-two values, effectively round the value up to the 3373 // nearest power of two. 3374 if (!RHSC->getAPInt().isPowerOf2()) 3375 ++MaxShiftAmt; 3376 IntegerType *ExtTy = 3377 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3378 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3379 if (const SCEVConstant *Step = 3380 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3381 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3382 const APInt &StepInt = Step->getAPInt(); 3383 const APInt &DivInt = RHSC->getAPInt(); 3384 if (!StepInt.urem(DivInt) && 3385 getZeroExtendExpr(AR, ExtTy) == 3386 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3387 getZeroExtendExpr(Step, ExtTy), 3388 AR->getLoop(), SCEV::FlagAnyWrap)) { 3389 SmallVector<const SCEV *, 4> Operands; 3390 for (const SCEV *Op : AR->operands()) 3391 Operands.push_back(getUDivExpr(Op, RHS)); 3392 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3393 } 3394 /// Get a canonical UDivExpr for a recurrence. 3395 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3396 // We can currently only fold X%N if X is constant. 3397 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3398 if (StartC && !DivInt.urem(StepInt) && 3399 getZeroExtendExpr(AR, ExtTy) == 3400 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3401 getZeroExtendExpr(Step, ExtTy), 3402 AR->getLoop(), SCEV::FlagAnyWrap)) { 3403 const APInt &StartInt = StartC->getAPInt(); 3404 const APInt &StartRem = StartInt.urem(StepInt); 3405 if (StartRem != 0) { 3406 const SCEV *NewLHS = 3407 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3408 AR->getLoop(), SCEV::FlagNW); 3409 if (LHS != NewLHS) { 3410 LHS = NewLHS; 3411 3412 // Reset the ID to include the new LHS, and check if it is 3413 // already cached. 3414 ID.clear(); 3415 ID.AddInteger(scUDivExpr); 3416 ID.AddPointer(LHS); 3417 ID.AddPointer(RHS); 3418 IP = nullptr; 3419 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3420 return S; 3421 } 3422 } 3423 } 3424 } 3425 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3426 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3427 SmallVector<const SCEV *, 4> Operands; 3428 for (const SCEV *Op : M->operands()) 3429 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3430 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3431 // Find an operand that's safely divisible. 3432 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3433 const SCEV *Op = M->getOperand(i); 3434 const SCEV *Div = getUDivExpr(Op, RHSC); 3435 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3436 Operands = SmallVector<const SCEV *, 4>(M->operands()); 3437 Operands[i] = Div; 3438 return getMulExpr(Operands); 3439 } 3440 } 3441 } 3442 3443 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3444 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3445 if (auto *DivisorConstant = 3446 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3447 bool Overflow = false; 3448 APInt NewRHS = 3449 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3450 if (Overflow) { 3451 return getConstant(RHSC->getType(), 0, false); 3452 } 3453 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3454 } 3455 } 3456 3457 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3458 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3459 SmallVector<const SCEV *, 4> Operands; 3460 for (const SCEV *Op : A->operands()) 3461 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3462 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3463 Operands.clear(); 3464 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3465 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3466 if (isa<SCEVUDivExpr>(Op) || 3467 getMulExpr(Op, RHS) != A->getOperand(i)) 3468 break; 3469 Operands.push_back(Op); 3470 } 3471 if (Operands.size() == A->getNumOperands()) 3472 return getAddExpr(Operands); 3473 } 3474 } 3475 3476 // Fold if both operands are constant. 3477 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3478 Constant *LHSCV = LHSC->getValue(); 3479 Constant *RHSCV = RHSC->getValue(); 3480 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3481 RHSCV))); 3482 } 3483 } 3484 } 3485 3486 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3487 // changes). Make sure we get a new one. 3488 IP = nullptr; 3489 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3490 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3491 LHS, RHS); 3492 UniqueSCEVs.InsertNode(S, IP); 3493 registerUser(S, {LHS, RHS}); 3494 return S; 3495 } 3496 3497 APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3498 APInt A = C1->getAPInt().abs(); 3499 APInt B = C2->getAPInt().abs(); 3500 uint32_t ABW = A.getBitWidth(); 3501 uint32_t BBW = B.getBitWidth(); 3502 3503 if (ABW > BBW) 3504 B = B.zext(ABW); 3505 else if (ABW < BBW) 3506 A = A.zext(BBW); 3507 3508 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3509 } 3510 3511 /// Get a canonical unsigned division expression, or something simpler if 3512 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3513 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3514 /// it's not exact because the udiv may be clearing bits. 3515 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3516 const SCEV *RHS) { 3517 // TODO: we could try to find factors in all sorts of things, but for now we 3518 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3519 // end of this file for inspiration. 3520 3521 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3522 if (!Mul || !Mul->hasNoUnsignedWrap()) 3523 return getUDivExpr(LHS, RHS); 3524 3525 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3526 // If the mulexpr multiplies by a constant, then that constant must be the 3527 // first element of the mulexpr. 3528 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3529 if (LHSCst == RHSCst) { 3530 SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands())); 3531 return getMulExpr(Operands); 3532 } 3533 3534 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3535 // that there's a factor provided by one of the other terms. We need to 3536 // check. 3537 APInt Factor = gcd(LHSCst, RHSCst); 3538 if (!Factor.isIntN(1)) { 3539 LHSCst = 3540 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3541 RHSCst = 3542 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3543 SmallVector<const SCEV *, 2> Operands; 3544 Operands.push_back(LHSCst); 3545 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3546 LHS = getMulExpr(Operands); 3547 RHS = RHSCst; 3548 Mul = dyn_cast<SCEVMulExpr>(LHS); 3549 if (!Mul) 3550 return getUDivExactExpr(LHS, RHS); 3551 } 3552 } 3553 } 3554 3555 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3556 if (Mul->getOperand(i) == RHS) { 3557 SmallVector<const SCEV *, 2> Operands; 3558 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3559 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3560 return getMulExpr(Operands); 3561 } 3562 } 3563 3564 return getUDivExpr(LHS, RHS); 3565 } 3566 3567 /// Get an add recurrence expression for the specified loop. Simplify the 3568 /// expression as much as possible. 3569 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3570 const Loop *L, 3571 SCEV::NoWrapFlags Flags) { 3572 SmallVector<const SCEV *, 4> Operands; 3573 Operands.push_back(Start); 3574 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3575 if (StepChrec->getLoop() == L) { 3576 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3577 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3578 } 3579 3580 Operands.push_back(Step); 3581 return getAddRecExpr(Operands, L, Flags); 3582 } 3583 3584 /// Get an add recurrence expression for the specified loop. Simplify the 3585 /// expression as much as possible. 3586 const SCEV * 3587 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3588 const Loop *L, SCEV::NoWrapFlags Flags) { 3589 if (Operands.size() == 1) return Operands[0]; 3590 #ifndef NDEBUG 3591 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3592 for (unsigned i = 1, e = Operands.size(); i != e; ++i) { 3593 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3594 "SCEVAddRecExpr operand types don't match!"); 3595 assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer"); 3596 } 3597 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3598 assert(isLoopInvariant(Operands[i], L) && 3599 "SCEVAddRecExpr operand is not loop-invariant!"); 3600 #endif 3601 3602 if (Operands.back()->isZero()) { 3603 Operands.pop_back(); 3604 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3605 } 3606 3607 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3608 // use that information to infer NUW and NSW flags. However, computing a 3609 // BE count requires calling getAddRecExpr, so we may not yet have a 3610 // meaningful BE count at this point (and if we don't, we'd be stuck 3611 // with a SCEVCouldNotCompute as the cached BE count). 3612 3613 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3614 3615 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3616 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3617 const Loop *NestedLoop = NestedAR->getLoop(); 3618 if (L->contains(NestedLoop) 3619 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3620 : (!NestedLoop->contains(L) && 3621 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3622 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands()); 3623 Operands[0] = NestedAR->getStart(); 3624 // AddRecs require their operands be loop-invariant with respect to their 3625 // loops. Don't perform this transformation if it would break this 3626 // requirement. 3627 bool AllInvariant = all_of( 3628 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3629 3630 if (AllInvariant) { 3631 // Create a recurrence for the outer loop with the same step size. 3632 // 3633 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3634 // inner recurrence has the same property. 3635 SCEV::NoWrapFlags OuterFlags = 3636 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3637 3638 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3639 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3640 return isLoopInvariant(Op, NestedLoop); 3641 }); 3642 3643 if (AllInvariant) { 3644 // Ok, both add recurrences are valid after the transformation. 3645 // 3646 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3647 // the outer recurrence has the same property. 3648 SCEV::NoWrapFlags InnerFlags = 3649 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3650 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3651 } 3652 } 3653 // Reset Operands to its original state. 3654 Operands[0] = NestedAR; 3655 } 3656 } 3657 3658 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3659 // already have one, otherwise create a new one. 3660 return getOrCreateAddRecExpr(Operands, L, Flags); 3661 } 3662 3663 const SCEV * 3664 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3665 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3666 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3667 // getSCEV(Base)->getType() has the same address space as Base->getType() 3668 // because SCEV::getType() preserves the address space. 3669 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3670 const bool AssumeInBoundsFlags = [&]() { 3671 if (!GEP->isInBounds()) 3672 return false; 3673 3674 // We'd like to propagate flags from the IR to the corresponding SCEV nodes, 3675 // but to do that, we have to ensure that said flag is valid in the entire 3676 // defined scope of the SCEV. 3677 auto *GEPI = dyn_cast<Instruction>(GEP); 3678 // TODO: non-instructions have global scope. We might be able to prove 3679 // some global scope cases 3680 return GEPI && isSCEVExprNeverPoison(GEPI); 3681 }(); 3682 3683 SCEV::NoWrapFlags OffsetWrap = 3684 AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3685 3686 Type *CurTy = GEP->getType(); 3687 bool FirstIter = true; 3688 SmallVector<const SCEV *, 4> Offsets; 3689 for (const SCEV *IndexExpr : IndexExprs) { 3690 // Compute the (potentially symbolic) offset in bytes for this index. 3691 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3692 // For a struct, add the member offset. 3693 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3694 unsigned FieldNo = Index->getZExtValue(); 3695 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3696 Offsets.push_back(FieldOffset); 3697 3698 // Update CurTy to the type of the field at Index. 3699 CurTy = STy->getTypeAtIndex(Index); 3700 } else { 3701 // Update CurTy to its element type. 3702 if (FirstIter) { 3703 assert(isa<PointerType>(CurTy) && 3704 "The first index of a GEP indexes a pointer"); 3705 CurTy = GEP->getSourceElementType(); 3706 FirstIter = false; 3707 } else { 3708 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3709 } 3710 // For an array, add the element offset, explicitly scaled. 3711 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3712 // Getelementptr indices are signed. 3713 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3714 3715 // Multiply the index by the element size to compute the element offset. 3716 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap); 3717 Offsets.push_back(LocalOffset); 3718 } 3719 } 3720 3721 // Handle degenerate case of GEP without offsets. 3722 if (Offsets.empty()) 3723 return BaseExpr; 3724 3725 // Add the offsets together, assuming nsw if inbounds. 3726 const SCEV *Offset = getAddExpr(Offsets, OffsetWrap); 3727 // Add the base address and the offset. We cannot use the nsw flag, as the 3728 // base address is unsigned. However, if we know that the offset is 3729 // non-negative, we can use nuw. 3730 SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset) 3731 ? SCEV::FlagNUW : SCEV::FlagAnyWrap; 3732 auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap); 3733 assert(BaseExpr->getType() == GEPExpr->getType() && 3734 "GEP should not change type mid-flight."); 3735 return GEPExpr; 3736 } 3737 3738 SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3739 ArrayRef<const SCEV *> Ops) { 3740 FoldingSetNodeID ID; 3741 ID.AddInteger(SCEVType); 3742 for (const SCEV *Op : Ops) 3743 ID.AddPointer(Op); 3744 void *IP = nullptr; 3745 return UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3746 } 3747 3748 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3749 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3750 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3751 } 3752 3753 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3754 SmallVectorImpl<const SCEV *> &Ops) { 3755 assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!"); 3756 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3757 if (Ops.size() == 1) return Ops[0]; 3758 #ifndef NDEBUG 3759 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3760 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 3761 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3762 "Operand types don't match!"); 3763 assert(Ops[0]->getType()->isPointerTy() == 3764 Ops[i]->getType()->isPointerTy() && 3765 "min/max should be consistently pointerish"); 3766 } 3767 #endif 3768 3769 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3770 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3771 3772 // Sort by complexity, this groups all similar expression types together. 3773 GroupByComplexity(Ops, &LI, DT); 3774 3775 // Check if we have created the same expression before. 3776 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) { 3777 return S; 3778 } 3779 3780 // If there are any constants, fold them together. 3781 unsigned Idx = 0; 3782 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3783 ++Idx; 3784 assert(Idx < Ops.size()); 3785 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3786 if (Kind == scSMaxExpr) 3787 return APIntOps::smax(LHS, RHS); 3788 else if (Kind == scSMinExpr) 3789 return APIntOps::smin(LHS, RHS); 3790 else if (Kind == scUMaxExpr) 3791 return APIntOps::umax(LHS, RHS); 3792 else if (Kind == scUMinExpr) 3793 return APIntOps::umin(LHS, RHS); 3794 llvm_unreachable("Unknown SCEV min/max opcode"); 3795 }; 3796 3797 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3798 // We found two constants, fold them together! 3799 ConstantInt *Fold = ConstantInt::get( 3800 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3801 Ops[0] = getConstant(Fold); 3802 Ops.erase(Ops.begin()+1); // Erase the folded element 3803 if (Ops.size() == 1) return Ops[0]; 3804 LHSC = cast<SCEVConstant>(Ops[0]); 3805 } 3806 3807 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3808 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3809 3810 if (IsMax ? IsMinV : IsMaxV) { 3811 // If we are left with a constant minimum(/maximum)-int, strip it off. 3812 Ops.erase(Ops.begin()); 3813 --Idx; 3814 } else if (IsMax ? IsMaxV : IsMinV) { 3815 // If we have a max(/min) with a constant maximum(/minimum)-int, 3816 // it will always be the extremum. 3817 return LHSC; 3818 } 3819 3820 if (Ops.size() == 1) return Ops[0]; 3821 } 3822 3823 // Find the first operation of the same kind 3824 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3825 ++Idx; 3826 3827 // Check to see if one of the operands is of the same kind. If so, expand its 3828 // operands onto our operand list, and recurse to simplify. 3829 if (Idx < Ops.size()) { 3830 bool DeletedAny = false; 3831 while (Ops[Idx]->getSCEVType() == Kind) { 3832 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3833 Ops.erase(Ops.begin()+Idx); 3834 Ops.append(SMME->op_begin(), SMME->op_end()); 3835 DeletedAny = true; 3836 } 3837 3838 if (DeletedAny) 3839 return getMinMaxExpr(Kind, Ops); 3840 } 3841 3842 // Okay, check to see if the same value occurs in the operand list twice. If 3843 // so, delete one. Since we sorted the list, these values are required to 3844 // be adjacent. 3845 llvm::CmpInst::Predicate GEPred = 3846 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3847 llvm::CmpInst::Predicate LEPred = 3848 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3849 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3850 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3851 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3852 if (Ops[i] == Ops[i + 1] || 3853 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3854 // X op Y op Y --> X op Y 3855 // X op Y --> X, if we know X, Y are ordered appropriately 3856 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3857 --i; 3858 --e; 3859 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3860 Ops[i + 1])) { 3861 // X op Y --> Y, if we know X, Y are ordered appropriately 3862 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3863 --i; 3864 --e; 3865 } 3866 } 3867 3868 if (Ops.size() == 1) return Ops[0]; 3869 3870 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3871 3872 // Okay, it looks like we really DO need an expr. Check to see if we 3873 // already have one, otherwise create a new one. 3874 FoldingSetNodeID ID; 3875 ID.AddInteger(Kind); 3876 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3877 ID.AddPointer(Ops[i]); 3878 void *IP = nullptr; 3879 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 3880 if (ExistingSCEV) 3881 return ExistingSCEV; 3882 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3883 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3884 SCEV *S = new (SCEVAllocator) 3885 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3886 3887 UniqueSCEVs.InsertNode(S, IP); 3888 registerUser(S, Ops); 3889 return S; 3890 } 3891 3892 namespace { 3893 3894 class SCEVSequentialMinMaxDeduplicatingVisitor final 3895 : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, 3896 Optional<const SCEV *>> { 3897 using RetVal = Optional<const SCEV *>; 3898 using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>; 3899 3900 ScalarEvolution &SE; 3901 const SCEVTypes RootKind; // Must be a sequential min/max expression. 3902 const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind. 3903 SmallPtrSet<const SCEV *, 16> SeenOps; 3904 3905 bool canRecurseInto(SCEVTypes Kind) const { 3906 // We can only recurse into the SCEV expression of the same effective type 3907 // as the type of our root SCEV expression. 3908 return RootKind == Kind || NonSequentialRootKind == Kind; 3909 }; 3910 3911 RetVal visitAnyMinMaxExpr(const SCEV *S) { 3912 assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) && 3913 "Only for min/max expressions."); 3914 SCEVTypes Kind = S->getSCEVType(); 3915 3916 if (!canRecurseInto(Kind)) 3917 return S; 3918 3919 auto *NAry = cast<SCEVNAryExpr>(S); 3920 SmallVector<const SCEV *> NewOps; 3921 bool Changed = 3922 visit(Kind, makeArrayRef(NAry->op_begin(), NAry->op_end()), NewOps); 3923 3924 if (!Changed) 3925 return S; 3926 if (NewOps.empty()) 3927 return None; 3928 3929 return isa<SCEVSequentialMinMaxExpr>(S) 3930 ? SE.getSequentialMinMaxExpr(Kind, NewOps) 3931 : SE.getMinMaxExpr(Kind, NewOps); 3932 } 3933 3934 RetVal visit(const SCEV *S) { 3935 // Has the whole operand been seen already? 3936 if (!SeenOps.insert(S).second) 3937 return None; 3938 return Base::visit(S); 3939 } 3940 3941 public: 3942 SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE, 3943 SCEVTypes RootKind) 3944 : SE(SE), RootKind(RootKind), 3945 NonSequentialRootKind( 3946 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType( 3947 RootKind)) {} 3948 3949 bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps, 3950 SmallVectorImpl<const SCEV *> &NewOps) { 3951 bool Changed = false; 3952 SmallVector<const SCEV *> Ops; 3953 Ops.reserve(OrigOps.size()); 3954 3955 for (const SCEV *Op : OrigOps) { 3956 RetVal NewOp = visit(Op); 3957 if (NewOp != Op) 3958 Changed = true; 3959 if (NewOp) 3960 Ops.emplace_back(*NewOp); 3961 } 3962 3963 if (Changed) 3964 NewOps = std::move(Ops); 3965 return Changed; 3966 } 3967 3968 RetVal visitConstant(const SCEVConstant *Constant) { return Constant; } 3969 3970 RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; } 3971 3972 RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; } 3973 3974 RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; } 3975 3976 RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; } 3977 3978 RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; } 3979 3980 RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; } 3981 3982 RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; } 3983 3984 RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 3985 3986 RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) { 3987 return visitAnyMinMaxExpr(Expr); 3988 } 3989 3990 RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) { 3991 return visitAnyMinMaxExpr(Expr); 3992 } 3993 3994 RetVal visitSMinExpr(const SCEVSMinExpr *Expr) { 3995 return visitAnyMinMaxExpr(Expr); 3996 } 3997 3998 RetVal visitUMinExpr(const SCEVUMinExpr *Expr) { 3999 return visitAnyMinMaxExpr(Expr); 4000 } 4001 4002 RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) { 4003 return visitAnyMinMaxExpr(Expr); 4004 } 4005 4006 RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; } 4007 4008 RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; } 4009 }; 4010 4011 } // namespace 4012 4013 const SCEV * 4014 ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind, 4015 SmallVectorImpl<const SCEV *> &Ops) { 4016 assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) && 4017 "Not a SCEVSequentialMinMaxExpr!"); 4018 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 4019 if (Ops.size() == 1) 4020 return Ops[0]; 4021 if (Ops.size() == 2 && 4022 any_of(Ops, [](const SCEV *Op) { return isa<SCEVConstant>(Op); })) 4023 return getMinMaxExpr( 4024 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind), 4025 Ops); 4026 #ifndef NDEBUG 4027 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 4028 for (unsigned i = 1, e = Ops.size(); i != e; ++i) { 4029 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 4030 "Operand types don't match!"); 4031 assert(Ops[0]->getType()->isPointerTy() == 4032 Ops[i]->getType()->isPointerTy() && 4033 "min/max should be consistently pointerish"); 4034 } 4035 #endif 4036 4037 // Note that SCEVSequentialMinMaxExpr is *NOT* commutative, 4038 // so we can *NOT* do any kind of sorting of the expressions! 4039 4040 // Check if we have created the same expression before. 4041 if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) 4042 return S; 4043 4044 // FIXME: there are *some* simplifications that we can do here. 4045 4046 // Keep only the first instance of an operand. 4047 { 4048 SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind); 4049 bool Changed = Deduplicator.visit(Kind, Ops, Ops); 4050 if (Changed) 4051 return getSequentialMinMaxExpr(Kind, Ops); 4052 } 4053 4054 // Check to see if one of the operands is of the same kind. If so, expand its 4055 // operands onto our operand list, and recurse to simplify. 4056 { 4057 unsigned Idx = 0; 4058 bool DeletedAny = false; 4059 while (Idx < Ops.size()) { 4060 if (Ops[Idx]->getSCEVType() != Kind) { 4061 ++Idx; 4062 continue; 4063 } 4064 const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]); 4065 Ops.erase(Ops.begin() + Idx); 4066 Ops.insert(Ops.begin() + Idx, SMME->op_begin(), SMME->op_end()); 4067 DeletedAny = true; 4068 } 4069 4070 if (DeletedAny) 4071 return getSequentialMinMaxExpr(Kind, Ops); 4072 } 4073 4074 // Okay, it looks like we really DO need an expr. Check to see if we 4075 // already have one, otherwise create a new one. 4076 FoldingSetNodeID ID; 4077 ID.AddInteger(Kind); 4078 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 4079 ID.AddPointer(Ops[i]); 4080 void *IP = nullptr; 4081 const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP); 4082 if (ExistingSCEV) 4083 return ExistingSCEV; 4084 4085 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 4086 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 4087 SCEV *S = new (SCEVAllocator) 4088 SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 4089 4090 UniqueSCEVs.InsertNode(S, IP); 4091 registerUser(S, Ops); 4092 return S; 4093 } 4094 4095 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4096 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4097 return getSMaxExpr(Ops); 4098 } 4099 4100 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4101 return getMinMaxExpr(scSMaxExpr, Ops); 4102 } 4103 4104 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 4105 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 4106 return getUMaxExpr(Ops); 4107 } 4108 4109 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 4110 return getMinMaxExpr(scUMaxExpr, Ops); 4111 } 4112 4113 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 4114 const SCEV *RHS) { 4115 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4116 return getSMinExpr(Ops); 4117 } 4118 4119 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 4120 return getMinMaxExpr(scSMinExpr, Ops); 4121 } 4122 4123 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS, 4124 bool Sequential) { 4125 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4126 return getUMinExpr(Ops, Sequential); 4127 } 4128 4129 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops, 4130 bool Sequential) { 4131 return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops) 4132 : getMinMaxExpr(scUMinExpr, Ops); 4133 } 4134 4135 const SCEV * 4136 ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy, 4137 ScalableVectorType *ScalableTy) { 4138 Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo()); 4139 Constant *One = ConstantInt::get(IntTy, 1); 4140 Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One); 4141 // Note that the expression we created is the final expression, we don't 4142 // want to simplify it any further Also, if we call a normal getSCEV(), 4143 // we'll end up in an endless recursion. So just create an SCEVUnknown. 4144 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 4145 } 4146 4147 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 4148 if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy)) 4149 return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy); 4150 // We can bypass creating a target-independent constant expression and then 4151 // folding it back into a ConstantInt. This is just a compile-time 4152 // optimization. 4153 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 4154 } 4155 4156 const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) { 4157 if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy)) 4158 return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy); 4159 // We can bypass creating a target-independent constant expression and then 4160 // folding it back into a ConstantInt. This is just a compile-time 4161 // optimization. 4162 return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy)); 4163 } 4164 4165 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 4166 StructType *STy, 4167 unsigned FieldNo) { 4168 // We can bypass creating a target-independent constant expression and then 4169 // folding it back into a ConstantInt. This is just a compile-time 4170 // optimization. 4171 return getConstant( 4172 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 4173 } 4174 4175 const SCEV *ScalarEvolution::getUnknown(Value *V) { 4176 // Don't attempt to do anything other than create a SCEVUnknown object 4177 // here. createSCEV only calls getUnknown after checking for all other 4178 // interesting possibilities, and any other code that calls getUnknown 4179 // is doing so in order to hide a value from SCEV canonicalization. 4180 4181 FoldingSetNodeID ID; 4182 ID.AddInteger(scUnknown); 4183 ID.AddPointer(V); 4184 void *IP = nullptr; 4185 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 4186 assert(cast<SCEVUnknown>(S)->getValue() == V && 4187 "Stale SCEVUnknown in uniquing map!"); 4188 return S; 4189 } 4190 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 4191 FirstUnknown); 4192 FirstUnknown = cast<SCEVUnknown>(S); 4193 UniqueSCEVs.InsertNode(S, IP); 4194 return S; 4195 } 4196 4197 //===----------------------------------------------------------------------===// 4198 // Basic SCEV Analysis and PHI Idiom Recognition Code 4199 // 4200 4201 /// Test if values of the given type are analyzable within the SCEV 4202 /// framework. This primarily includes integer types, and it can optionally 4203 /// include pointer types if the ScalarEvolution class has access to 4204 /// target-specific information. 4205 bool ScalarEvolution::isSCEVable(Type *Ty) const { 4206 // Integers and pointers are always SCEVable. 4207 return Ty->isIntOrPtrTy(); 4208 } 4209 4210 /// Return the size in bits of the specified type, for which isSCEVable must 4211 /// return true. 4212 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 4213 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4214 if (Ty->isPointerTy()) 4215 return getDataLayout().getIndexTypeSizeInBits(Ty); 4216 return getDataLayout().getTypeSizeInBits(Ty); 4217 } 4218 4219 /// Return a type with the same bitwidth as the given type and which represents 4220 /// how SCEV will treat the given type, for which isSCEVable must return 4221 /// true. For pointer types, this is the pointer index sized integer type. 4222 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 4223 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 4224 4225 if (Ty->isIntegerTy()) 4226 return Ty; 4227 4228 // The only other support type is pointer. 4229 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 4230 return getDataLayout().getIndexType(Ty); 4231 } 4232 4233 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 4234 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 4235 } 4236 4237 bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A, 4238 const SCEV *B) { 4239 /// For a valid use point to exist, the defining scope of one operand 4240 /// must dominate the other. 4241 bool PreciseA, PreciseB; 4242 auto *ScopeA = getDefiningScopeBound({A}, PreciseA); 4243 auto *ScopeB = getDefiningScopeBound({B}, PreciseB); 4244 if (!PreciseA || !PreciseB) 4245 // Can't tell. 4246 return false; 4247 return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) || 4248 DT.dominates(ScopeB, ScopeA); 4249 } 4250 4251 4252 const SCEV *ScalarEvolution::getCouldNotCompute() { 4253 return CouldNotCompute.get(); 4254 } 4255 4256 bool ScalarEvolution::checkValidity(const SCEV *S) const { 4257 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 4258 auto *SU = dyn_cast<SCEVUnknown>(S); 4259 return SU && SU->getValue() == nullptr; 4260 }); 4261 4262 return !ContainsNulls; 4263 } 4264 4265 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 4266 HasRecMapType::iterator I = HasRecMap.find(S); 4267 if (I != HasRecMap.end()) 4268 return I->second; 4269 4270 bool FoundAddRec = 4271 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 4272 HasRecMap.insert({S, FoundAddRec}); 4273 return FoundAddRec; 4274 } 4275 4276 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 4277 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 4278 /// offset I, then return {S', I}, else return {\p S, nullptr}. 4279 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 4280 const auto *Add = dyn_cast<SCEVAddExpr>(S); 4281 if (!Add) 4282 return {S, nullptr}; 4283 4284 if (Add->getNumOperands() != 2) 4285 return {S, nullptr}; 4286 4287 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 4288 if (!ConstOp) 4289 return {S, nullptr}; 4290 4291 return {Add->getOperand(1), ConstOp->getValue()}; 4292 } 4293 4294 /// Return the ValueOffsetPair set for \p S. \p S can be represented 4295 /// by the value and offset from any ValueOffsetPair in the set. 4296 ScalarEvolution::ValueOffsetPairSetVector * 4297 ScalarEvolution::getSCEVValues(const SCEV *S) { 4298 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 4299 if (SI == ExprValueMap.end()) 4300 return nullptr; 4301 #ifndef NDEBUG 4302 if (VerifySCEVMap) { 4303 // Check there is no dangling Value in the set returned. 4304 for (const auto &VE : SI->second) 4305 assert(ValueExprMap.count(VE.first)); 4306 } 4307 #endif 4308 return &SI->second; 4309 } 4310 4311 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 4312 /// cannot be used separately. eraseValueFromMap should be used to remove 4313 /// V from ValueExprMap and ExprValueMap at the same time. 4314 void ScalarEvolution::eraseValueFromMap(Value *V) { 4315 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4316 if (I != ValueExprMap.end()) { 4317 const SCEV *S = I->second; 4318 // Remove {V, 0} from the set of ExprValueMap[S] 4319 if (auto *SV = getSCEVValues(S)) 4320 SV->remove({V, nullptr}); 4321 4322 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 4323 const SCEV *Stripped; 4324 ConstantInt *Offset; 4325 std::tie(Stripped, Offset) = splitAddExpr(S); 4326 if (Offset != nullptr) { 4327 if (auto *SV = getSCEVValues(Stripped)) 4328 SV->remove({V, Offset}); 4329 } 4330 ValueExprMap.erase(V); 4331 } 4332 } 4333 4334 void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) { 4335 // A recursive query may have already computed the SCEV. It should be 4336 // equivalent, but may not necessarily be exactly the same, e.g. due to lazily 4337 // inferred nowrap flags. 4338 auto It = ValueExprMap.find_as(V); 4339 if (It == ValueExprMap.end()) { 4340 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4341 ExprValueMap[S].insert({V, nullptr}); 4342 } 4343 } 4344 4345 /// Return an existing SCEV if it exists, otherwise analyze the expression and 4346 /// create a new one. 4347 const SCEV *ScalarEvolution::getSCEV(Value *V) { 4348 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4349 4350 const SCEV *S = getExistingSCEV(V); 4351 if (S == nullptr) { 4352 S = createSCEV(V); 4353 // During PHI resolution, it is possible to create two SCEVs for the same 4354 // V, so it is needed to double check whether V->S is inserted into 4355 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 4356 std::pair<ValueExprMapType::iterator, bool> Pair = 4357 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 4358 if (Pair.second) { 4359 ExprValueMap[S].insert({V, nullptr}); 4360 4361 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 4362 // ExprValueMap. 4363 const SCEV *Stripped = S; 4364 ConstantInt *Offset = nullptr; 4365 std::tie(Stripped, Offset) = splitAddExpr(S); 4366 // If stripped is SCEVUnknown, don't bother to save 4367 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 4368 // increase the complexity of the expansion code. 4369 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 4370 // because it may generate add/sub instead of GEP in SCEV expansion. 4371 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 4372 !isa<GetElementPtrInst>(V)) 4373 ExprValueMap[Stripped].insert({V, Offset}); 4374 } 4375 } 4376 return S; 4377 } 4378 4379 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 4380 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 4381 4382 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 4383 if (I != ValueExprMap.end()) { 4384 const SCEV *S = I->second; 4385 assert(checkValidity(S) && 4386 "existing SCEV has not been properly invalidated"); 4387 return S; 4388 } 4389 return nullptr; 4390 } 4391 4392 /// Return a SCEV corresponding to -V = -1*V 4393 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 4394 SCEV::NoWrapFlags Flags) { 4395 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4396 return getConstant( 4397 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 4398 4399 Type *Ty = V->getType(); 4400 Ty = getEffectiveSCEVType(Ty); 4401 return getMulExpr(V, getMinusOne(Ty), Flags); 4402 } 4403 4404 /// If Expr computes ~A, return A else return nullptr 4405 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4406 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4407 if (!Add || Add->getNumOperands() != 2 || 4408 !Add->getOperand(0)->isAllOnesValue()) 4409 return nullptr; 4410 4411 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4412 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4413 !AddRHS->getOperand(0)->isAllOnesValue()) 4414 return nullptr; 4415 4416 return AddRHS->getOperand(1); 4417 } 4418 4419 /// Return a SCEV corresponding to ~V = -1-V 4420 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4421 assert(!V->getType()->isPointerTy() && "Can't negate pointer"); 4422 4423 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4424 return getConstant( 4425 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4426 4427 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4428 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4429 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4430 SmallVector<const SCEV *, 2> MatchedOperands; 4431 for (const SCEV *Operand : MME->operands()) { 4432 const SCEV *Matched = MatchNotExpr(Operand); 4433 if (!Matched) 4434 return (const SCEV *)nullptr; 4435 MatchedOperands.push_back(Matched); 4436 } 4437 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 4438 MatchedOperands); 4439 }; 4440 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4441 return Replaced; 4442 } 4443 4444 Type *Ty = V->getType(); 4445 Ty = getEffectiveSCEVType(Ty); 4446 return getMinusSCEV(getMinusOne(Ty), V); 4447 } 4448 4449 const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) { 4450 assert(P->getType()->isPointerTy()); 4451 4452 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) { 4453 // The base of an AddRec is the first operand. 4454 SmallVector<const SCEV *> Ops{AddRec->operands()}; 4455 Ops[0] = removePointerBase(Ops[0]); 4456 // Don't try to transfer nowrap flags for now. We could in some cases 4457 // (for example, if pointer operand of the AddRec is a SCEVUnknown). 4458 return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap); 4459 } 4460 if (auto *Add = dyn_cast<SCEVAddExpr>(P)) { 4461 // The base of an Add is the pointer operand. 4462 SmallVector<const SCEV *> Ops{Add->operands()}; 4463 const SCEV **PtrOp = nullptr; 4464 for (const SCEV *&AddOp : Ops) { 4465 if (AddOp->getType()->isPointerTy()) { 4466 assert(!PtrOp && "Cannot have multiple pointer ops"); 4467 PtrOp = &AddOp; 4468 } 4469 } 4470 *PtrOp = removePointerBase(*PtrOp); 4471 // Don't try to transfer nowrap flags for now. We could in some cases 4472 // (for example, if the pointer operand of the Add is a SCEVUnknown). 4473 return getAddExpr(Ops); 4474 } 4475 // Any other expression must be a pointer base. 4476 return getZero(P->getType()); 4477 } 4478 4479 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4480 SCEV::NoWrapFlags Flags, 4481 unsigned Depth) { 4482 // Fast path: X - X --> 0. 4483 if (LHS == RHS) 4484 return getZero(LHS->getType()); 4485 4486 // If we subtract two pointers with different pointer bases, bail. 4487 // Eventually, we're going to add an assertion to getMulExpr that we 4488 // can't multiply by a pointer. 4489 if (RHS->getType()->isPointerTy()) { 4490 if (!LHS->getType()->isPointerTy() || 4491 getPointerBase(LHS) != getPointerBase(RHS)) 4492 return getCouldNotCompute(); 4493 LHS = removePointerBase(LHS); 4494 RHS = removePointerBase(RHS); 4495 } 4496 4497 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4498 // makes it so that we cannot make much use of NUW. 4499 auto AddFlags = SCEV::FlagAnyWrap; 4500 const bool RHSIsNotMinSigned = 4501 !getSignedRangeMin(RHS).isMinSignedValue(); 4502 if (hasFlags(Flags, SCEV::FlagNSW)) { 4503 // Let M be the minimum representable signed value. Then (-1)*RHS 4504 // signed-wraps if and only if RHS is M. That can happen even for 4505 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4506 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4507 // (-1)*RHS, we need to prove that RHS != M. 4508 // 4509 // If LHS is non-negative and we know that LHS - RHS does not 4510 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4511 // either by proving that RHS > M or that LHS >= 0. 4512 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4513 AddFlags = SCEV::FlagNSW; 4514 } 4515 } 4516 4517 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4518 // RHS is NSW and LHS >= 0. 4519 // 4520 // The difficulty here is that the NSW flag may have been proven 4521 // relative to a loop that is to be found in a recurrence in LHS and 4522 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4523 // larger scope than intended. 4524 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4525 4526 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4527 } 4528 4529 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4530 unsigned Depth) { 4531 Type *SrcTy = V->getType(); 4532 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4533 "Cannot truncate or zero extend with non-integer arguments!"); 4534 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4535 return V; // No conversion 4536 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4537 return getTruncateExpr(V, Ty, Depth); 4538 return getZeroExtendExpr(V, Ty, Depth); 4539 } 4540 4541 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4542 unsigned Depth) { 4543 Type *SrcTy = V->getType(); 4544 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4545 "Cannot truncate or zero extend with non-integer arguments!"); 4546 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4547 return V; // No conversion 4548 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4549 return getTruncateExpr(V, Ty, Depth); 4550 return getSignExtendExpr(V, Ty, Depth); 4551 } 4552 4553 const SCEV * 4554 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4555 Type *SrcTy = V->getType(); 4556 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4557 "Cannot noop or zero extend with non-integer arguments!"); 4558 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4559 "getNoopOrZeroExtend cannot truncate!"); 4560 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4561 return V; // No conversion 4562 return getZeroExtendExpr(V, Ty); 4563 } 4564 4565 const SCEV * 4566 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4567 Type *SrcTy = V->getType(); 4568 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4569 "Cannot noop or sign extend with non-integer arguments!"); 4570 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4571 "getNoopOrSignExtend cannot truncate!"); 4572 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4573 return V; // No conversion 4574 return getSignExtendExpr(V, Ty); 4575 } 4576 4577 const SCEV * 4578 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4579 Type *SrcTy = V->getType(); 4580 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4581 "Cannot noop or any extend with non-integer arguments!"); 4582 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4583 "getNoopOrAnyExtend cannot truncate!"); 4584 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4585 return V; // No conversion 4586 return getAnyExtendExpr(V, Ty); 4587 } 4588 4589 const SCEV * 4590 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4591 Type *SrcTy = V->getType(); 4592 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4593 "Cannot truncate or noop with non-integer arguments!"); 4594 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4595 "getTruncateOrNoop cannot extend!"); 4596 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4597 return V; // No conversion 4598 return getTruncateExpr(V, Ty); 4599 } 4600 4601 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4602 const SCEV *RHS) { 4603 const SCEV *PromotedLHS = LHS; 4604 const SCEV *PromotedRHS = RHS; 4605 4606 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4607 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4608 else 4609 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4610 4611 return getUMaxExpr(PromotedLHS, PromotedRHS); 4612 } 4613 4614 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4615 const SCEV *RHS, 4616 bool Sequential) { 4617 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4618 return getUMinFromMismatchedTypes(Ops, Sequential); 4619 } 4620 4621 const SCEV * 4622 ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops, 4623 bool Sequential) { 4624 assert(!Ops.empty() && "At least one operand must be!"); 4625 // Trivial case. 4626 if (Ops.size() == 1) 4627 return Ops[0]; 4628 4629 // Find the max type first. 4630 Type *MaxType = nullptr; 4631 for (auto *S : Ops) 4632 if (MaxType) 4633 MaxType = getWiderType(MaxType, S->getType()); 4634 else 4635 MaxType = S->getType(); 4636 assert(MaxType && "Failed to find maximum type!"); 4637 4638 // Extend all ops to max type. 4639 SmallVector<const SCEV *, 2> PromotedOps; 4640 for (auto *S : Ops) 4641 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4642 4643 // Generate umin. 4644 return getUMinExpr(PromotedOps, Sequential); 4645 } 4646 4647 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4648 // A pointer operand may evaluate to a nonpointer expression, such as null. 4649 if (!V->getType()->isPointerTy()) 4650 return V; 4651 4652 while (true) { 4653 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 4654 V = AddRec->getStart(); 4655 } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) { 4656 const SCEV *PtrOp = nullptr; 4657 for (const SCEV *AddOp : Add->operands()) { 4658 if (AddOp->getType()->isPointerTy()) { 4659 assert(!PtrOp && "Cannot have multiple pointer ops"); 4660 PtrOp = AddOp; 4661 } 4662 } 4663 assert(PtrOp && "Must have pointer op"); 4664 V = PtrOp; 4665 } else // Not something we can look further into. 4666 return V; 4667 } 4668 } 4669 4670 /// Push users of the given Instruction onto the given Worklist. 4671 static void PushDefUseChildren(Instruction *I, 4672 SmallVectorImpl<Instruction *> &Worklist, 4673 SmallPtrSetImpl<Instruction *> &Visited) { 4674 // Push the def-use children onto the Worklist stack. 4675 for (User *U : I->users()) { 4676 auto *UserInsn = cast<Instruction>(U); 4677 if (Visited.insert(UserInsn).second) 4678 Worklist.push_back(UserInsn); 4679 } 4680 } 4681 4682 namespace { 4683 4684 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4685 /// expression in case its Loop is L. If it is not L then 4686 /// if IgnoreOtherLoops is true then use AddRec itself 4687 /// otherwise rewrite cannot be done. 4688 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4689 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4690 public: 4691 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4692 bool IgnoreOtherLoops = true) { 4693 SCEVInitRewriter Rewriter(L, SE); 4694 const SCEV *Result = Rewriter.visit(S); 4695 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4696 return SE.getCouldNotCompute(); 4697 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4698 ? SE.getCouldNotCompute() 4699 : Result; 4700 } 4701 4702 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4703 if (!SE.isLoopInvariant(Expr, L)) 4704 SeenLoopVariantSCEVUnknown = true; 4705 return Expr; 4706 } 4707 4708 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4709 // Only re-write AddRecExprs for this loop. 4710 if (Expr->getLoop() == L) 4711 return Expr->getStart(); 4712 SeenOtherLoops = true; 4713 return Expr; 4714 } 4715 4716 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4717 4718 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4719 4720 private: 4721 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4722 : SCEVRewriteVisitor(SE), L(L) {} 4723 4724 const Loop *L; 4725 bool SeenLoopVariantSCEVUnknown = false; 4726 bool SeenOtherLoops = false; 4727 }; 4728 4729 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4730 /// increment expression in case its Loop is L. If it is not L then 4731 /// use AddRec itself. 4732 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4733 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4734 public: 4735 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4736 SCEVPostIncRewriter Rewriter(L, SE); 4737 const SCEV *Result = Rewriter.visit(S); 4738 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4739 ? SE.getCouldNotCompute() 4740 : Result; 4741 } 4742 4743 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4744 if (!SE.isLoopInvariant(Expr, L)) 4745 SeenLoopVariantSCEVUnknown = true; 4746 return Expr; 4747 } 4748 4749 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4750 // Only re-write AddRecExprs for this loop. 4751 if (Expr->getLoop() == L) 4752 return Expr->getPostIncExpr(SE); 4753 SeenOtherLoops = true; 4754 return Expr; 4755 } 4756 4757 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4758 4759 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4760 4761 private: 4762 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4763 : SCEVRewriteVisitor(SE), L(L) {} 4764 4765 const Loop *L; 4766 bool SeenLoopVariantSCEVUnknown = false; 4767 bool SeenOtherLoops = false; 4768 }; 4769 4770 /// This class evaluates the compare condition by matching it against the 4771 /// condition of loop latch. If there is a match we assume a true value 4772 /// for the condition while building SCEV nodes. 4773 class SCEVBackedgeConditionFolder 4774 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4775 public: 4776 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4777 ScalarEvolution &SE) { 4778 bool IsPosBECond = false; 4779 Value *BECond = nullptr; 4780 if (BasicBlock *Latch = L->getLoopLatch()) { 4781 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4782 if (BI && BI->isConditional()) { 4783 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4784 "Both outgoing branches should not target same header!"); 4785 BECond = BI->getCondition(); 4786 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4787 } else { 4788 return S; 4789 } 4790 } 4791 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4792 return Rewriter.visit(S); 4793 } 4794 4795 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4796 const SCEV *Result = Expr; 4797 bool InvariantF = SE.isLoopInvariant(Expr, L); 4798 4799 if (!InvariantF) { 4800 Instruction *I = cast<Instruction>(Expr->getValue()); 4801 switch (I->getOpcode()) { 4802 case Instruction::Select: { 4803 SelectInst *SI = cast<SelectInst>(I); 4804 Optional<const SCEV *> Res = 4805 compareWithBackedgeCondition(SI->getCondition()); 4806 if (Res.hasValue()) { 4807 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4808 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4809 } 4810 break; 4811 } 4812 default: { 4813 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4814 if (Res.hasValue()) 4815 Result = Res.getValue(); 4816 break; 4817 } 4818 } 4819 } 4820 return Result; 4821 } 4822 4823 private: 4824 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4825 bool IsPosBECond, ScalarEvolution &SE) 4826 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4827 IsPositiveBECond(IsPosBECond) {} 4828 4829 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4830 4831 const Loop *L; 4832 /// Loop back condition. 4833 Value *BackedgeCond = nullptr; 4834 /// Set to true if loop back is on positive branch condition. 4835 bool IsPositiveBECond; 4836 }; 4837 4838 Optional<const SCEV *> 4839 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4840 4841 // If value matches the backedge condition for loop latch, 4842 // then return a constant evolution node based on loopback 4843 // branch taken. 4844 if (BackedgeCond == IC) 4845 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4846 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4847 return None; 4848 } 4849 4850 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4851 public: 4852 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4853 ScalarEvolution &SE) { 4854 SCEVShiftRewriter Rewriter(L, SE); 4855 const SCEV *Result = Rewriter.visit(S); 4856 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4857 } 4858 4859 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4860 // Only allow AddRecExprs for this loop. 4861 if (!SE.isLoopInvariant(Expr, L)) 4862 Valid = false; 4863 return Expr; 4864 } 4865 4866 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4867 if (Expr->getLoop() == L && Expr->isAffine()) 4868 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4869 Valid = false; 4870 return Expr; 4871 } 4872 4873 bool isValid() { return Valid; } 4874 4875 private: 4876 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4877 : SCEVRewriteVisitor(SE), L(L) {} 4878 4879 const Loop *L; 4880 bool Valid = true; 4881 }; 4882 4883 } // end anonymous namespace 4884 4885 SCEV::NoWrapFlags 4886 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4887 if (!AR->isAffine()) 4888 return SCEV::FlagAnyWrap; 4889 4890 using OBO = OverflowingBinaryOperator; 4891 4892 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4893 4894 if (!AR->hasNoSignedWrap()) { 4895 ConstantRange AddRecRange = getSignedRange(AR); 4896 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4897 4898 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4899 Instruction::Add, IncRange, OBO::NoSignedWrap); 4900 if (NSWRegion.contains(AddRecRange)) 4901 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4902 } 4903 4904 if (!AR->hasNoUnsignedWrap()) { 4905 ConstantRange AddRecRange = getUnsignedRange(AR); 4906 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4907 4908 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4909 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4910 if (NUWRegion.contains(AddRecRange)) 4911 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4912 } 4913 4914 return Result; 4915 } 4916 4917 SCEV::NoWrapFlags 4918 ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4919 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4920 4921 if (AR->hasNoSignedWrap()) 4922 return Result; 4923 4924 if (!AR->isAffine()) 4925 return Result; 4926 4927 const SCEV *Step = AR->getStepRecurrence(*this); 4928 const Loop *L = AR->getLoop(); 4929 4930 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4931 // Note that this serves two purposes: It filters out loops that are 4932 // simply not analyzable, and it covers the case where this code is 4933 // being called from within backedge-taken count analysis, such that 4934 // attempting to ask for the backedge-taken count would likely result 4935 // in infinite recursion. In the later case, the analysis code will 4936 // cope with a conservative value, and it will take care to purge 4937 // that value once it has finished. 4938 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4939 4940 // Normally, in the cases we can prove no-overflow via a 4941 // backedge guarding condition, we can also compute a backedge 4942 // taken count for the loop. The exceptions are assumptions and 4943 // guards present in the loop -- SCEV is not great at exploiting 4944 // these to compute max backedge taken counts, but can still use 4945 // these to prove lack of overflow. Use this fact to avoid 4946 // doing extra work that may not pay off. 4947 4948 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4949 AC.assumptions().empty()) 4950 return Result; 4951 4952 // If the backedge is guarded by a comparison with the pre-inc value the 4953 // addrec is safe. Also, if the entry is guarded by a comparison with the 4954 // start value and the backedge is guarded by a comparison with the post-inc 4955 // value, the addrec is safe. 4956 ICmpInst::Predicate Pred; 4957 const SCEV *OverflowLimit = 4958 getSignedOverflowLimitForStep(Step, &Pred, this); 4959 if (OverflowLimit && 4960 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 4961 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 4962 Result = setFlags(Result, SCEV::FlagNSW); 4963 } 4964 return Result; 4965 } 4966 SCEV::NoWrapFlags 4967 ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) { 4968 SCEV::NoWrapFlags Result = AR->getNoWrapFlags(); 4969 4970 if (AR->hasNoUnsignedWrap()) 4971 return Result; 4972 4973 if (!AR->isAffine()) 4974 return Result; 4975 4976 const SCEV *Step = AR->getStepRecurrence(*this); 4977 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 4978 const Loop *L = AR->getLoop(); 4979 4980 // Check whether the backedge-taken count is SCEVCouldNotCompute. 4981 // Note that this serves two purposes: It filters out loops that are 4982 // simply not analyzable, and it covers the case where this code is 4983 // being called from within backedge-taken count analysis, such that 4984 // attempting to ask for the backedge-taken count would likely result 4985 // in infinite recursion. In the later case, the analysis code will 4986 // cope with a conservative value, and it will take care to purge 4987 // that value once it has finished. 4988 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 4989 4990 // Normally, in the cases we can prove no-overflow via a 4991 // backedge guarding condition, we can also compute a backedge 4992 // taken count for the loop. The exceptions are assumptions and 4993 // guards present in the loop -- SCEV is not great at exploiting 4994 // these to compute max backedge taken counts, but can still use 4995 // these to prove lack of overflow. Use this fact to avoid 4996 // doing extra work that may not pay off. 4997 4998 if (isa<SCEVCouldNotCompute>(MaxBECount) && !HasGuards && 4999 AC.assumptions().empty()) 5000 return Result; 5001 5002 // If the backedge is guarded by a comparison with the pre-inc value the 5003 // addrec is safe. Also, if the entry is guarded by a comparison with the 5004 // start value and the backedge is guarded by a comparison with the post-inc 5005 // value, the addrec is safe. 5006 if (isKnownPositive(Step)) { 5007 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 5008 getUnsignedRangeMax(Step)); 5009 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 5010 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 5011 Result = setFlags(Result, SCEV::FlagNUW); 5012 } 5013 } 5014 5015 return Result; 5016 } 5017 5018 namespace { 5019 5020 /// Represents an abstract binary operation. This may exist as a 5021 /// normal instruction or constant expression, or may have been 5022 /// derived from an expression tree. 5023 struct BinaryOp { 5024 unsigned Opcode; 5025 Value *LHS; 5026 Value *RHS; 5027 bool IsNSW = false; 5028 bool IsNUW = false; 5029 5030 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 5031 /// constant expression. 5032 Operator *Op = nullptr; 5033 5034 explicit BinaryOp(Operator *Op) 5035 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 5036 Op(Op) { 5037 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 5038 IsNSW = OBO->hasNoSignedWrap(); 5039 IsNUW = OBO->hasNoUnsignedWrap(); 5040 } 5041 } 5042 5043 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 5044 bool IsNUW = false) 5045 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 5046 }; 5047 5048 } // end anonymous namespace 5049 5050 /// Try to map \p V into a BinaryOp, and return \c None on failure. 5051 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 5052 auto *Op = dyn_cast<Operator>(V); 5053 if (!Op) 5054 return None; 5055 5056 // Implementation detail: all the cleverness here should happen without 5057 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 5058 // SCEV expressions when possible, and we should not break that. 5059 5060 switch (Op->getOpcode()) { 5061 case Instruction::Add: 5062 case Instruction::Sub: 5063 case Instruction::Mul: 5064 case Instruction::UDiv: 5065 case Instruction::URem: 5066 case Instruction::And: 5067 case Instruction::Or: 5068 case Instruction::AShr: 5069 case Instruction::Shl: 5070 return BinaryOp(Op); 5071 5072 case Instruction::Xor: 5073 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 5074 // If the RHS of the xor is a signmask, then this is just an add. 5075 // Instcombine turns add of signmask into xor as a strength reduction step. 5076 if (RHSC->getValue().isSignMask()) 5077 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 5078 // Binary `xor` is a bit-wise `add`. 5079 if (V->getType()->isIntegerTy(1)) 5080 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 5081 return BinaryOp(Op); 5082 5083 case Instruction::LShr: 5084 // Turn logical shift right of a constant into a unsigned divide. 5085 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 5086 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 5087 5088 // If the shift count is not less than the bitwidth, the result of 5089 // the shift is undefined. Don't try to analyze it, because the 5090 // resolution chosen here may differ from the resolution chosen in 5091 // other parts of the compiler. 5092 if (SA->getValue().ult(BitWidth)) { 5093 Constant *X = 5094 ConstantInt::get(SA->getContext(), 5095 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 5096 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 5097 } 5098 } 5099 return BinaryOp(Op); 5100 5101 case Instruction::ExtractValue: { 5102 auto *EVI = cast<ExtractValueInst>(Op); 5103 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 5104 break; 5105 5106 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 5107 if (!WO) 5108 break; 5109 5110 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 5111 bool Signed = WO->isSigned(); 5112 // TODO: Should add nuw/nsw flags for mul as well. 5113 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 5114 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 5115 5116 // Now that we know that all uses of the arithmetic-result component of 5117 // CI are guarded by the overflow check, we can go ahead and pretend 5118 // that the arithmetic is non-overflowing. 5119 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 5120 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 5121 } 5122 5123 default: 5124 break; 5125 } 5126 5127 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 5128 // semantics as a Sub, return a binary sub expression. 5129 if (auto *II = dyn_cast<IntrinsicInst>(V)) 5130 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 5131 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 5132 5133 return None; 5134 } 5135 5136 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 5137 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 5138 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 5139 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 5140 /// follows one of the following patterns: 5141 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5142 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 5143 /// If the SCEV expression of \p Op conforms with one of the expected patterns 5144 /// we return the type of the truncation operation, and indicate whether the 5145 /// truncated type should be treated as signed/unsigned by setting 5146 /// \p Signed to true/false, respectively. 5147 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 5148 bool &Signed, ScalarEvolution &SE) { 5149 // The case where Op == SymbolicPHI (that is, with no type conversions on 5150 // the way) is handled by the regular add recurrence creating logic and 5151 // would have already been triggered in createAddRecForPHI. Reaching it here 5152 // means that createAddRecFromPHI had failed for this PHI before (e.g., 5153 // because one of the other operands of the SCEVAddExpr updating this PHI is 5154 // not invariant). 5155 // 5156 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 5157 // this case predicates that allow us to prove that Op == SymbolicPHI will 5158 // be added. 5159 if (Op == SymbolicPHI) 5160 return nullptr; 5161 5162 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 5163 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 5164 if (SourceBits != NewBits) 5165 return nullptr; 5166 5167 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 5168 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 5169 if (!SExt && !ZExt) 5170 return nullptr; 5171 const SCEVTruncateExpr *Trunc = 5172 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 5173 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 5174 if (!Trunc) 5175 return nullptr; 5176 const SCEV *X = Trunc->getOperand(); 5177 if (X != SymbolicPHI) 5178 return nullptr; 5179 Signed = SExt != nullptr; 5180 return Trunc->getType(); 5181 } 5182 5183 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 5184 if (!PN->getType()->isIntegerTy()) 5185 return nullptr; 5186 const Loop *L = LI.getLoopFor(PN->getParent()); 5187 if (!L || L->getHeader() != PN->getParent()) 5188 return nullptr; 5189 return L; 5190 } 5191 5192 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 5193 // computation that updates the phi follows the following pattern: 5194 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 5195 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 5196 // If so, try to see if it can be rewritten as an AddRecExpr under some 5197 // Predicates. If successful, return them as a pair. Also cache the results 5198 // of the analysis. 5199 // 5200 // Example usage scenario: 5201 // Say the Rewriter is called for the following SCEV: 5202 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5203 // where: 5204 // %X = phi i64 (%Start, %BEValue) 5205 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 5206 // and call this function with %SymbolicPHI = %X. 5207 // 5208 // The analysis will find that the value coming around the backedge has 5209 // the following SCEV: 5210 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 5211 // Upon concluding that this matches the desired pattern, the function 5212 // will return the pair {NewAddRec, SmallPredsVec} where: 5213 // NewAddRec = {%Start,+,%Step} 5214 // SmallPredsVec = {P1, P2, P3} as follows: 5215 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 5216 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 5217 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 5218 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 5219 // under the predicates {P1,P2,P3}. 5220 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 5221 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 5222 // 5223 // TODO's: 5224 // 5225 // 1) Extend the Induction descriptor to also support inductions that involve 5226 // casts: When needed (namely, when we are called in the context of the 5227 // vectorizer induction analysis), a Set of cast instructions will be 5228 // populated by this method, and provided back to isInductionPHI. This is 5229 // needed to allow the vectorizer to properly record them to be ignored by 5230 // the cost model and to avoid vectorizing them (otherwise these casts, 5231 // which are redundant under the runtime overflow checks, will be 5232 // vectorized, which can be costly). 5233 // 5234 // 2) Support additional induction/PHISCEV patterns: We also want to support 5235 // inductions where the sext-trunc / zext-trunc operations (partly) occur 5236 // after the induction update operation (the induction increment): 5237 // 5238 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 5239 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 5240 // 5241 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 5242 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 5243 // 5244 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 5245 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5246 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 5247 SmallVector<const SCEVPredicate *, 3> Predicates; 5248 5249 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 5250 // return an AddRec expression under some predicate. 5251 5252 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5253 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5254 assert(L && "Expecting an integer loop header phi"); 5255 5256 // The loop may have multiple entrances or multiple exits; we can analyze 5257 // this phi as an addrec if it has a unique entry value and a unique 5258 // backedge value. 5259 Value *BEValueV = nullptr, *StartValueV = nullptr; 5260 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5261 Value *V = PN->getIncomingValue(i); 5262 if (L->contains(PN->getIncomingBlock(i))) { 5263 if (!BEValueV) { 5264 BEValueV = V; 5265 } else if (BEValueV != V) { 5266 BEValueV = nullptr; 5267 break; 5268 } 5269 } else if (!StartValueV) { 5270 StartValueV = V; 5271 } else if (StartValueV != V) { 5272 StartValueV = nullptr; 5273 break; 5274 } 5275 } 5276 if (!BEValueV || !StartValueV) 5277 return None; 5278 5279 const SCEV *BEValue = getSCEV(BEValueV); 5280 5281 // If the value coming around the backedge is an add with the symbolic 5282 // value we just inserted, possibly with casts that we can ignore under 5283 // an appropriate runtime guard, then we found a simple induction variable! 5284 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 5285 if (!Add) 5286 return None; 5287 5288 // If there is a single occurrence of the symbolic value, possibly 5289 // casted, replace it with a recurrence. 5290 unsigned FoundIndex = Add->getNumOperands(); 5291 Type *TruncTy = nullptr; 5292 bool Signed; 5293 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5294 if ((TruncTy = 5295 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 5296 if (FoundIndex == e) { 5297 FoundIndex = i; 5298 break; 5299 } 5300 5301 if (FoundIndex == Add->getNumOperands()) 5302 return None; 5303 5304 // Create an add with everything but the specified operand. 5305 SmallVector<const SCEV *, 8> Ops; 5306 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5307 if (i != FoundIndex) 5308 Ops.push_back(Add->getOperand(i)); 5309 const SCEV *Accum = getAddExpr(Ops); 5310 5311 // The runtime checks will not be valid if the step amount is 5312 // varying inside the loop. 5313 if (!isLoopInvariant(Accum, L)) 5314 return None; 5315 5316 // *** Part2: Create the predicates 5317 5318 // Analysis was successful: we have a phi-with-cast pattern for which we 5319 // can return an AddRec expression under the following predicates: 5320 // 5321 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 5322 // fits within the truncated type (does not overflow) for i = 0 to n-1. 5323 // P2: An Equal predicate that guarantees that 5324 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 5325 // P3: An Equal predicate that guarantees that 5326 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 5327 // 5328 // As we next prove, the above predicates guarantee that: 5329 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 5330 // 5331 // 5332 // More formally, we want to prove that: 5333 // Expr(i+1) = Start + (i+1) * Accum 5334 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5335 // 5336 // Given that: 5337 // 1) Expr(0) = Start 5338 // 2) Expr(1) = Start + Accum 5339 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 5340 // 3) Induction hypothesis (step i): 5341 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 5342 // 5343 // Proof: 5344 // Expr(i+1) = 5345 // = Start + (i+1)*Accum 5346 // = (Start + i*Accum) + Accum 5347 // = Expr(i) + Accum 5348 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 5349 // :: from step i 5350 // 5351 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 5352 // 5353 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 5354 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 5355 // + Accum :: from P3 5356 // 5357 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 5358 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 5359 // 5360 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 5361 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 5362 // 5363 // By induction, the same applies to all iterations 1<=i<n: 5364 // 5365 5366 // Create a truncated addrec for which we will add a no overflow check (P1). 5367 const SCEV *StartVal = getSCEV(StartValueV); 5368 const SCEV *PHISCEV = 5369 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 5370 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 5371 5372 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 5373 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 5374 // will be constant. 5375 // 5376 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 5377 // add P1. 5378 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 5379 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 5380 Signed ? SCEVWrapPredicate::IncrementNSSW 5381 : SCEVWrapPredicate::IncrementNUSW; 5382 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 5383 Predicates.push_back(AddRecPred); 5384 } 5385 5386 // Create the Equal Predicates P2,P3: 5387 5388 // It is possible that the predicates P2 and/or P3 are computable at 5389 // compile time due to StartVal and/or Accum being constants. 5390 // If either one is, then we can check that now and escape if either P2 5391 // or P3 is false. 5392 5393 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 5394 // for each of StartVal and Accum 5395 auto getExtendedExpr = [&](const SCEV *Expr, 5396 bool CreateSignExtend) -> const SCEV * { 5397 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 5398 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 5399 const SCEV *ExtendedExpr = 5400 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 5401 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 5402 return ExtendedExpr; 5403 }; 5404 5405 // Given: 5406 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 5407 // = getExtendedExpr(Expr) 5408 // Determine whether the predicate P: Expr == ExtendedExpr 5409 // is known to be false at compile time 5410 auto PredIsKnownFalse = [&](const SCEV *Expr, 5411 const SCEV *ExtendedExpr) -> bool { 5412 return Expr != ExtendedExpr && 5413 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 5414 }; 5415 5416 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 5417 if (PredIsKnownFalse(StartVal, StartExtended)) { 5418 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 5419 return None; 5420 } 5421 5422 // The Step is always Signed (because the overflow checks are either 5423 // NSSW or NUSW) 5424 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 5425 if (PredIsKnownFalse(Accum, AccumExtended)) { 5426 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 5427 return None; 5428 } 5429 5430 auto AppendPredicate = [&](const SCEV *Expr, 5431 const SCEV *ExtendedExpr) -> void { 5432 if (Expr != ExtendedExpr && 5433 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 5434 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 5435 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 5436 Predicates.push_back(Pred); 5437 } 5438 }; 5439 5440 AppendPredicate(StartVal, StartExtended); 5441 AppendPredicate(Accum, AccumExtended); 5442 5443 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 5444 // which the casts had been folded away. The caller can rewrite SymbolicPHI 5445 // into NewAR if it will also add the runtime overflow checks specified in 5446 // Predicates. 5447 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 5448 5449 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 5450 std::make_pair(NewAR, Predicates); 5451 // Remember the result of the analysis for this SCEV at this locayyytion. 5452 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 5453 return PredRewrite; 5454 } 5455 5456 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5457 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 5458 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 5459 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 5460 if (!L) 5461 return None; 5462 5463 // Check to see if we already analyzed this PHI. 5464 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 5465 if (I != PredicatedSCEVRewrites.end()) { 5466 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 5467 I->second; 5468 // Analysis was done before and failed to create an AddRec: 5469 if (Rewrite.first == SymbolicPHI) 5470 return None; 5471 // Analysis was done before and succeeded to create an AddRec under 5472 // a predicate: 5473 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 5474 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 5475 return Rewrite; 5476 } 5477 5478 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 5479 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 5480 5481 // Record in the cache that the analysis failed 5482 if (!Rewrite) { 5483 SmallVector<const SCEVPredicate *, 3> Predicates; 5484 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 5485 return None; 5486 } 5487 5488 return Rewrite; 5489 } 5490 5491 // FIXME: This utility is currently required because the Rewriter currently 5492 // does not rewrite this expression: 5493 // {0, +, (sext ix (trunc iy to ix) to iy)} 5494 // into {0, +, %step}, 5495 // even when the following Equal predicate exists: 5496 // "%step == (sext ix (trunc iy to ix) to iy)". 5497 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 5498 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 5499 if (AR1 == AR2) 5500 return true; 5501 5502 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 5503 if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) && 5504 !Preds->implies(SE.getEqualPredicate(Expr2, Expr1))) 5505 return false; 5506 return true; 5507 }; 5508 5509 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 5510 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5511 return false; 5512 return true; 5513 } 5514 5515 /// A helper function for createAddRecFromPHI to handle simple cases. 5516 /// 5517 /// This function tries to find an AddRec expression for the simplest (yet most 5518 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5519 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5520 /// technique for finding the AddRec expression. 5521 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5522 Value *BEValueV, 5523 Value *StartValueV) { 5524 const Loop *L = LI.getLoopFor(PN->getParent()); 5525 assert(L && L->getHeader() == PN->getParent()); 5526 assert(BEValueV && StartValueV); 5527 5528 auto BO = MatchBinaryOp(BEValueV, DT); 5529 if (!BO) 5530 return nullptr; 5531 5532 if (BO->Opcode != Instruction::Add) 5533 return nullptr; 5534 5535 const SCEV *Accum = nullptr; 5536 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5537 Accum = getSCEV(BO->RHS); 5538 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5539 Accum = getSCEV(BO->LHS); 5540 5541 if (!Accum) 5542 return nullptr; 5543 5544 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5545 if (BO->IsNUW) 5546 Flags = setFlags(Flags, SCEV::FlagNUW); 5547 if (BO->IsNSW) 5548 Flags = setFlags(Flags, SCEV::FlagNSW); 5549 5550 const SCEV *StartVal = getSCEV(StartValueV); 5551 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5552 insertValueToMap(PN, PHISCEV); 5553 5554 // We can add Flags to the post-inc expression only if we 5555 // know that it is *undefined behavior* for BEValueV to 5556 // overflow. 5557 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) { 5558 assert(isLoopInvariant(Accum, L) && 5559 "Accum is defined outside L, but is not invariant?"); 5560 if (isAddRecNeverPoison(BEInst, L)) 5561 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5562 } 5563 5564 return PHISCEV; 5565 } 5566 5567 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5568 const Loop *L = LI.getLoopFor(PN->getParent()); 5569 if (!L || L->getHeader() != PN->getParent()) 5570 return nullptr; 5571 5572 // The loop may have multiple entrances or multiple exits; we can analyze 5573 // this phi as an addrec if it has a unique entry value and a unique 5574 // backedge value. 5575 Value *BEValueV = nullptr, *StartValueV = nullptr; 5576 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5577 Value *V = PN->getIncomingValue(i); 5578 if (L->contains(PN->getIncomingBlock(i))) { 5579 if (!BEValueV) { 5580 BEValueV = V; 5581 } else if (BEValueV != V) { 5582 BEValueV = nullptr; 5583 break; 5584 } 5585 } else if (!StartValueV) { 5586 StartValueV = V; 5587 } else if (StartValueV != V) { 5588 StartValueV = nullptr; 5589 break; 5590 } 5591 } 5592 if (!BEValueV || !StartValueV) 5593 return nullptr; 5594 5595 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5596 "PHI node already processed?"); 5597 5598 // First, try to find AddRec expression without creating a fictituos symbolic 5599 // value for PN. 5600 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5601 return S; 5602 5603 // Handle PHI node value symbolically. 5604 const SCEV *SymbolicName = getUnknown(PN); 5605 insertValueToMap(PN, SymbolicName); 5606 5607 // Using this symbolic name for the PHI, analyze the value coming around 5608 // the back-edge. 5609 const SCEV *BEValue = getSCEV(BEValueV); 5610 5611 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5612 // has a special value for the first iteration of the loop. 5613 5614 // If the value coming around the backedge is an add with the symbolic 5615 // value we just inserted, then we found a simple induction variable! 5616 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5617 // If there is a single occurrence of the symbolic value, replace it 5618 // with a recurrence. 5619 unsigned FoundIndex = Add->getNumOperands(); 5620 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5621 if (Add->getOperand(i) == SymbolicName) 5622 if (FoundIndex == e) { 5623 FoundIndex = i; 5624 break; 5625 } 5626 5627 if (FoundIndex != Add->getNumOperands()) { 5628 // Create an add with everything but the specified operand. 5629 SmallVector<const SCEV *, 8> Ops; 5630 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5631 if (i != FoundIndex) 5632 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5633 L, *this)); 5634 const SCEV *Accum = getAddExpr(Ops); 5635 5636 // This is not a valid addrec if the step amount is varying each 5637 // loop iteration, but is not itself an addrec in this loop. 5638 if (isLoopInvariant(Accum, L) || 5639 (isa<SCEVAddRecExpr>(Accum) && 5640 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5641 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5642 5643 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5644 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5645 if (BO->IsNUW) 5646 Flags = setFlags(Flags, SCEV::FlagNUW); 5647 if (BO->IsNSW) 5648 Flags = setFlags(Flags, SCEV::FlagNSW); 5649 } 5650 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5651 // If the increment is an inbounds GEP, then we know the address 5652 // space cannot be wrapped around. We cannot make any guarantee 5653 // about signed or unsigned overflow because pointers are 5654 // unsigned but we may have a negative index from the base 5655 // pointer. We can guarantee that no unsigned wrap occurs if the 5656 // indices form a positive value. 5657 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5658 Flags = setFlags(Flags, SCEV::FlagNW); 5659 5660 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5661 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5662 Flags = setFlags(Flags, SCEV::FlagNUW); 5663 } 5664 5665 // We cannot transfer nuw and nsw flags from subtraction 5666 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5667 // for instance. 5668 } 5669 5670 const SCEV *StartVal = getSCEV(StartValueV); 5671 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5672 5673 // Okay, for the entire analysis of this edge we assumed the PHI 5674 // to be symbolic. We now need to go back and purge all of the 5675 // entries for the scalars that use the symbolic expression. 5676 forgetMemoizedResults(SymbolicName); 5677 insertValueToMap(PN, PHISCEV); 5678 5679 // We can add Flags to the post-inc expression only if we 5680 // know that it is *undefined behavior* for BEValueV to 5681 // overflow. 5682 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5683 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5684 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5685 5686 return PHISCEV; 5687 } 5688 } 5689 } else { 5690 // Otherwise, this could be a loop like this: 5691 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5692 // In this case, j = {1,+,1} and BEValue is j. 5693 // Because the other in-value of i (0) fits the evolution of BEValue 5694 // i really is an addrec evolution. 5695 // 5696 // We can generalize this saying that i is the shifted value of BEValue 5697 // by one iteration: 5698 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5699 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5700 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5701 if (Shifted != getCouldNotCompute() && 5702 Start != getCouldNotCompute()) { 5703 const SCEV *StartVal = getSCEV(StartValueV); 5704 if (Start == StartVal) { 5705 // Okay, for the entire analysis of this edge we assumed the PHI 5706 // to be symbolic. We now need to go back and purge all of the 5707 // entries for the scalars that use the symbolic expression. 5708 forgetMemoizedResults(SymbolicName); 5709 insertValueToMap(PN, Shifted); 5710 return Shifted; 5711 } 5712 } 5713 } 5714 5715 // Remove the temporary PHI node SCEV that has been inserted while intending 5716 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5717 // as it will prevent later (possibly simpler) SCEV expressions to be added 5718 // to the ValueExprMap. 5719 eraseValueFromMap(PN); 5720 5721 return nullptr; 5722 } 5723 5724 // Checks if the SCEV S is available at BB. S is considered available at BB 5725 // if S can be materialized at BB without introducing a fault. 5726 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5727 BasicBlock *BB) { 5728 struct CheckAvailable { 5729 bool TraversalDone = false; 5730 bool Available = true; 5731 5732 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5733 BasicBlock *BB = nullptr; 5734 DominatorTree &DT; 5735 5736 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5737 : L(L), BB(BB), DT(DT) {} 5738 5739 bool setUnavailable() { 5740 TraversalDone = true; 5741 Available = false; 5742 return false; 5743 } 5744 5745 bool follow(const SCEV *S) { 5746 switch (S->getSCEVType()) { 5747 case scConstant: 5748 case scPtrToInt: 5749 case scTruncate: 5750 case scZeroExtend: 5751 case scSignExtend: 5752 case scAddExpr: 5753 case scMulExpr: 5754 case scUMaxExpr: 5755 case scSMaxExpr: 5756 case scUMinExpr: 5757 case scSMinExpr: 5758 case scSequentialUMinExpr: 5759 // These expressions are available if their operand(s) is/are. 5760 return true; 5761 5762 case scAddRecExpr: { 5763 // We allow add recurrences that are on the loop BB is in, or some 5764 // outer loop. This guarantees availability because the value of the 5765 // add recurrence at BB is simply the "current" value of the induction 5766 // variable. We can relax this in the future; for instance an add 5767 // recurrence on a sibling dominating loop is also available at BB. 5768 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5769 if (L && (ARLoop == L || ARLoop->contains(L))) 5770 return true; 5771 5772 return setUnavailable(); 5773 } 5774 5775 case scUnknown: { 5776 // For SCEVUnknown, we check for simple dominance. 5777 const auto *SU = cast<SCEVUnknown>(S); 5778 Value *V = SU->getValue(); 5779 5780 if (isa<Argument>(V)) 5781 return false; 5782 5783 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5784 return false; 5785 5786 return setUnavailable(); 5787 } 5788 5789 case scUDivExpr: 5790 case scCouldNotCompute: 5791 // We do not try to smart about these at all. 5792 return setUnavailable(); 5793 } 5794 llvm_unreachable("Unknown SCEV kind!"); 5795 } 5796 5797 bool isDone() { return TraversalDone; } 5798 }; 5799 5800 CheckAvailable CA(L, BB, DT); 5801 SCEVTraversal<CheckAvailable> ST(CA); 5802 5803 ST.visitAll(S); 5804 return CA.Available; 5805 } 5806 5807 // Try to match a control flow sequence that branches out at BI and merges back 5808 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5809 // match. 5810 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5811 Value *&C, Value *&LHS, Value *&RHS) { 5812 C = BI->getCondition(); 5813 5814 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5815 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5816 5817 if (!LeftEdge.isSingleEdge()) 5818 return false; 5819 5820 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5821 5822 Use &LeftUse = Merge->getOperandUse(0); 5823 Use &RightUse = Merge->getOperandUse(1); 5824 5825 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5826 LHS = LeftUse; 5827 RHS = RightUse; 5828 return true; 5829 } 5830 5831 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5832 LHS = RightUse; 5833 RHS = LeftUse; 5834 return true; 5835 } 5836 5837 return false; 5838 } 5839 5840 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5841 auto IsReachable = 5842 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5843 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5844 const Loop *L = LI.getLoopFor(PN->getParent()); 5845 5846 // We don't want to break LCSSA, even in a SCEV expression tree. 5847 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5848 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5849 return nullptr; 5850 5851 // Try to match 5852 // 5853 // br %cond, label %left, label %right 5854 // left: 5855 // br label %merge 5856 // right: 5857 // br label %merge 5858 // merge: 5859 // V = phi [ %x, %left ], [ %y, %right ] 5860 // 5861 // as "select %cond, %x, %y" 5862 5863 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5864 assert(IDom && "At least the entry block should dominate PN"); 5865 5866 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5867 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5868 5869 if (BI && BI->isConditional() && 5870 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5871 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5872 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5873 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5874 } 5875 5876 return nullptr; 5877 } 5878 5879 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5880 if (const SCEV *S = createAddRecFromPHI(PN)) 5881 return S; 5882 5883 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5884 return S; 5885 5886 // If the PHI has a single incoming value, follow that value, unless the 5887 // PHI's incoming blocks are in a different loop, in which case doing so 5888 // risks breaking LCSSA form. Instcombine would normally zap these, but 5889 // it doesn't have DominatorTree information, so it may miss cases. 5890 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5891 if (LI.replacementPreservesLCSSAForm(PN, V)) 5892 return getSCEV(V); 5893 5894 // If it's not a loop phi, we can't handle it yet. 5895 return getUnknown(PN); 5896 } 5897 5898 bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind, 5899 SCEVTypes RootKind) { 5900 struct FindClosure { 5901 const SCEV *OperandToFind; 5902 const SCEVTypes RootKind; // Must be a sequential min/max expression. 5903 const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind. 5904 5905 bool Found = false; 5906 5907 bool canRecurseInto(SCEVTypes Kind) const { 5908 // We can only recurse into the SCEV expression of the same effective type 5909 // as the type of our root SCEV expression, and into zero-extensions. 5910 return RootKind == Kind || NonSequentialRootKind == Kind || 5911 scZeroExtend == Kind; 5912 }; 5913 5914 FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind) 5915 : OperandToFind(OperandToFind), RootKind(RootKind), 5916 NonSequentialRootKind( 5917 SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType( 5918 RootKind)) {} 5919 5920 bool follow(const SCEV *S) { 5921 Found = S == OperandToFind; 5922 5923 return !isDone() && canRecurseInto(S->getSCEVType()); 5924 } 5925 5926 bool isDone() const { return Found; } 5927 }; 5928 5929 FindClosure FC(OperandToFind, RootKind); 5930 visitAll(Root, FC); 5931 return FC.Found; 5932 } 5933 5934 const SCEV *ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond( 5935 Instruction *I, ICmpInst *Cond, Value *TrueVal, Value *FalseVal) { 5936 // Try to match some simple smax or umax patterns. 5937 auto *ICI = Cond; 5938 5939 Value *LHS = ICI->getOperand(0); 5940 Value *RHS = ICI->getOperand(1); 5941 5942 switch (ICI->getPredicate()) { 5943 case ICmpInst::ICMP_SLT: 5944 case ICmpInst::ICMP_SLE: 5945 case ICmpInst::ICMP_ULT: 5946 case ICmpInst::ICMP_ULE: 5947 std::swap(LHS, RHS); 5948 LLVM_FALLTHROUGH; 5949 case ICmpInst::ICMP_SGT: 5950 case ICmpInst::ICMP_SGE: 5951 case ICmpInst::ICMP_UGT: 5952 case ICmpInst::ICMP_UGE: 5953 // a > b ? a+x : b+x -> max(a, b)+x 5954 // a > b ? b+x : a+x -> min(a, b)+x 5955 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5956 bool Signed = ICI->isSigned(); 5957 const SCEV *LA = getSCEV(TrueVal); 5958 const SCEV *RA = getSCEV(FalseVal); 5959 const SCEV *LS = getSCEV(LHS); 5960 const SCEV *RS = getSCEV(RHS); 5961 if (LA->getType()->isPointerTy()) { 5962 // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA. 5963 // Need to make sure we can't produce weird expressions involving 5964 // negated pointers. 5965 if (LA == LS && RA == RS) 5966 return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS); 5967 if (LA == RS && RA == LS) 5968 return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS); 5969 } 5970 auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * { 5971 if (Op->getType()->isPointerTy()) { 5972 Op = getLosslessPtrToIntExpr(Op); 5973 if (isa<SCEVCouldNotCompute>(Op)) 5974 return Op; 5975 } 5976 if (Signed) 5977 Op = getNoopOrSignExtend(Op, I->getType()); 5978 else 5979 Op = getNoopOrZeroExtend(Op, I->getType()); 5980 return Op; 5981 }; 5982 LS = CoerceOperand(LS); 5983 RS = CoerceOperand(RS); 5984 if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS)) 5985 break; 5986 const SCEV *LDiff = getMinusSCEV(LA, LS); 5987 const SCEV *RDiff = getMinusSCEV(RA, RS); 5988 if (LDiff == RDiff) 5989 return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS), 5990 LDiff); 5991 LDiff = getMinusSCEV(LA, RS); 5992 RDiff = getMinusSCEV(RA, LS); 5993 if (LDiff == RDiff) 5994 return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS), 5995 LDiff); 5996 } 5997 break; 5998 case ICmpInst::ICMP_NE: 5999 // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y 6000 std::swap(TrueVal, FalseVal); 6001 LLVM_FALLTHROUGH; 6002 case ICmpInst::ICMP_EQ: 6003 // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1 6004 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 6005 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 6006 const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 6007 const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y 6008 const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y 6009 const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x 6010 const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y 6011 if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1)) 6012 return getAddExpr(getUMaxExpr(X, C), Y); 6013 } 6014 // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...)) 6015 // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...)) 6016 // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...) 6017 // -> umin_seq(x, umin (..., umin_seq(...), ...)) 6018 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() && 6019 isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) { 6020 const SCEV *X = getSCEV(LHS); 6021 while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X)) 6022 X = ZExt->getOperand(); 6023 if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(I->getType())) { 6024 const SCEV *FalseValExpr = getSCEV(FalseVal); 6025 if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr)) 6026 return getUMinExpr(getNoopOrZeroExtend(X, I->getType()), FalseValExpr, 6027 /*Sequential=*/true); 6028 } 6029 } 6030 break; 6031 default: 6032 break; 6033 } 6034 6035 return getUnknown(I); 6036 } 6037 6038 const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq( 6039 Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) { 6040 // For now, only deal with i1-typed `select`s. 6041 if (!V->getType()->isIntegerTy(1) || !Cond->getType()->isIntegerTy(1) || 6042 !TrueVal->getType()->isIntegerTy(1) || 6043 !FalseVal->getType()->isIntegerTy(1)) 6044 return getUnknown(V); 6045 6046 // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0) 6047 // --> C + (umin_seq cond, x - C) 6048 // 6049 // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C)) 6050 // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0) 6051 // --> C + (umin_seq ~cond, x - C) 6052 if (isa<ConstantInt>(TrueVal) || isa<ConstantInt>(FalseVal)) { 6053 const SCEV *CondExpr = getSCEV(Cond); 6054 const SCEV *TrueExpr = getSCEV(TrueVal); 6055 const SCEV *FalseExpr = getSCEV(FalseVal); 6056 const SCEV *X, *C; 6057 if (isa<ConstantInt>(TrueVal)) { 6058 CondExpr = getNotSCEV(CondExpr); 6059 X = FalseExpr; 6060 C = TrueExpr; 6061 } else { 6062 X = TrueExpr; 6063 C = FalseExpr; 6064 } 6065 return getAddExpr( 6066 C, getUMinExpr(CondExpr, getMinusSCEV(X, C), /*Sequential=*/true)); 6067 } 6068 6069 return getUnknown(V); 6070 } 6071 6072 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond, 6073 Value *TrueVal, 6074 Value *FalseVal) { 6075 // Handle "constant" branch or select. This can occur for instance when a 6076 // loop pass transforms an inner loop and moves on to process the outer loop. 6077 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 6078 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 6079 6080 if (auto *I = dyn_cast<Instruction>(V)) { 6081 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) { 6082 const SCEV *S = createNodeForSelectOrPHIInstWithICmpInstCond( 6083 I, ICI, TrueVal, FalseVal); 6084 if (!isa<SCEVUnknown>(S)) 6085 return S; 6086 } 6087 } 6088 6089 return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal); 6090 } 6091 6092 /// Expand GEP instructions into add and multiply operations. This allows them 6093 /// to be analyzed by regular SCEV code. 6094 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 6095 // Don't attempt to analyze GEPs over unsized objects. 6096 if (!GEP->getSourceElementType()->isSized()) 6097 return getUnknown(GEP); 6098 6099 SmallVector<const SCEV *, 4> IndexExprs; 6100 for (Value *Index : GEP->indices()) 6101 IndexExprs.push_back(getSCEV(Index)); 6102 return getGEPExpr(GEP, IndexExprs); 6103 } 6104 6105 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 6106 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6107 return C->getAPInt().countTrailingZeros(); 6108 6109 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 6110 return GetMinTrailingZeros(I->getOperand()); 6111 6112 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 6113 return std::min(GetMinTrailingZeros(T->getOperand()), 6114 (uint32_t)getTypeSizeInBits(T->getType())); 6115 6116 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 6117 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6118 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6119 ? getTypeSizeInBits(E->getType()) 6120 : OpRes; 6121 } 6122 6123 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 6124 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 6125 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 6126 ? getTypeSizeInBits(E->getType()) 6127 : OpRes; 6128 } 6129 6130 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 6131 // The result is the min of all operands results. 6132 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6133 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6134 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6135 return MinOpRes; 6136 } 6137 6138 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 6139 // The result is the sum of all operands results. 6140 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 6141 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 6142 for (unsigned i = 1, e = M->getNumOperands(); 6143 SumOpRes != BitWidth && i != e; ++i) 6144 SumOpRes = 6145 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 6146 return SumOpRes; 6147 } 6148 6149 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 6150 // The result is the min of all operands results. 6151 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 6152 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 6153 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 6154 return MinOpRes; 6155 } 6156 6157 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 6158 // The result is the min of all operands results. 6159 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6160 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6161 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6162 return MinOpRes; 6163 } 6164 6165 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 6166 // The result is the min of all operands results. 6167 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 6168 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 6169 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 6170 return MinOpRes; 6171 } 6172 6173 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6174 // For a SCEVUnknown, ask ValueTracking. 6175 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 6176 return Known.countMinTrailingZeros(); 6177 } 6178 6179 // SCEVUDivExpr 6180 return 0; 6181 } 6182 6183 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 6184 auto I = MinTrailingZerosCache.find(S); 6185 if (I != MinTrailingZerosCache.end()) 6186 return I->second; 6187 6188 uint32_t Result = GetMinTrailingZerosImpl(S); 6189 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 6190 assert(InsertPair.second && "Should insert a new key"); 6191 return InsertPair.first->second; 6192 } 6193 6194 /// Helper method to assign a range to V from metadata present in the IR. 6195 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 6196 if (Instruction *I = dyn_cast<Instruction>(V)) 6197 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 6198 return getConstantRangeFromMetadata(*MD); 6199 6200 return None; 6201 } 6202 6203 void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec, 6204 SCEV::NoWrapFlags Flags) { 6205 if (AddRec->getNoWrapFlags(Flags) != Flags) { 6206 AddRec->setNoWrapFlags(Flags); 6207 UnsignedRanges.erase(AddRec); 6208 SignedRanges.erase(AddRec); 6209 } 6210 } 6211 6212 ConstantRange ScalarEvolution:: 6213 getRangeForUnknownRecurrence(const SCEVUnknown *U) { 6214 const DataLayout &DL = getDataLayout(); 6215 6216 unsigned BitWidth = getTypeSizeInBits(U->getType()); 6217 const ConstantRange FullSet(BitWidth, /*isFullSet=*/true); 6218 6219 // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then 6220 // use information about the trip count to improve our available range. Note 6221 // that the trip count independent cases are already handled by known bits. 6222 // WARNING: The definition of recurrence used here is subtly different than 6223 // the one used by AddRec (and thus most of this file). Step is allowed to 6224 // be arbitrarily loop varying here, where AddRec allows only loop invariant 6225 // and other addrecs in the same loop (for non-affine addrecs). The code 6226 // below intentionally handles the case where step is not loop invariant. 6227 auto *P = dyn_cast<PHINode>(U->getValue()); 6228 if (!P) 6229 return FullSet; 6230 6231 // Make sure that no Phi input comes from an unreachable block. Otherwise, 6232 // even the values that are not available in these blocks may come from them, 6233 // and this leads to false-positive recurrence test. 6234 for (auto *Pred : predecessors(P->getParent())) 6235 if (!DT.isReachableFromEntry(Pred)) 6236 return FullSet; 6237 6238 BinaryOperator *BO; 6239 Value *Start, *Step; 6240 if (!matchSimpleRecurrence(P, BO, Start, Step)) 6241 return FullSet; 6242 6243 // If we found a recurrence in reachable code, we must be in a loop. Note 6244 // that BO might be in some subloop of L, and that's completely okay. 6245 auto *L = LI.getLoopFor(P->getParent()); 6246 assert(L && L->getHeader() == P->getParent()); 6247 if (!L->contains(BO->getParent())) 6248 // NOTE: This bailout should be an assert instead. However, asserting 6249 // the condition here exposes a case where LoopFusion is querying SCEV 6250 // with malformed loop information during the midst of the transform. 6251 // There doesn't appear to be an obvious fix, so for the moment bailout 6252 // until the caller issue can be fixed. PR49566 tracks the bug. 6253 return FullSet; 6254 6255 // TODO: Extend to other opcodes such as mul, and div 6256 switch (BO->getOpcode()) { 6257 default: 6258 return FullSet; 6259 case Instruction::AShr: 6260 case Instruction::LShr: 6261 case Instruction::Shl: 6262 break; 6263 }; 6264 6265 if (BO->getOperand(0) != P) 6266 // TODO: Handle the power function forms some day. 6267 return FullSet; 6268 6269 unsigned TC = getSmallConstantMaxTripCount(L); 6270 if (!TC || TC >= BitWidth) 6271 return FullSet; 6272 6273 auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT); 6274 auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT); 6275 assert(KnownStart.getBitWidth() == BitWidth && 6276 KnownStep.getBitWidth() == BitWidth); 6277 6278 // Compute total shift amount, being careful of overflow and bitwidths. 6279 auto MaxShiftAmt = KnownStep.getMaxValue(); 6280 APInt TCAP(BitWidth, TC-1); 6281 bool Overflow = false; 6282 auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow); 6283 if (Overflow) 6284 return FullSet; 6285 6286 switch (BO->getOpcode()) { 6287 default: 6288 llvm_unreachable("filtered out above"); 6289 case Instruction::AShr: { 6290 // For each ashr, three cases: 6291 // shift = 0 => unchanged value 6292 // saturation => 0 or -1 6293 // other => a value closer to zero (of the same sign) 6294 // Thus, the end value is closer to zero than the start. 6295 auto KnownEnd = KnownBits::ashr(KnownStart, 6296 KnownBits::makeConstant(TotalShift)); 6297 if (KnownStart.isNonNegative()) 6298 // Analogous to lshr (simply not yet canonicalized) 6299 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6300 KnownStart.getMaxValue() + 1); 6301 if (KnownStart.isNegative()) 6302 // End >=u Start && End <=s Start 6303 return ConstantRange::getNonEmpty(KnownStart.getMinValue(), 6304 KnownEnd.getMaxValue() + 1); 6305 break; 6306 } 6307 case Instruction::LShr: { 6308 // For each lshr, three cases: 6309 // shift = 0 => unchanged value 6310 // saturation => 0 6311 // other => a smaller positive number 6312 // Thus, the low end of the unsigned range is the last value produced. 6313 auto KnownEnd = KnownBits::lshr(KnownStart, 6314 KnownBits::makeConstant(TotalShift)); 6315 return ConstantRange::getNonEmpty(KnownEnd.getMinValue(), 6316 KnownStart.getMaxValue() + 1); 6317 } 6318 case Instruction::Shl: { 6319 // Iff no bits are shifted out, value increases on every shift. 6320 auto KnownEnd = KnownBits::shl(KnownStart, 6321 KnownBits::makeConstant(TotalShift)); 6322 if (TotalShift.ult(KnownStart.countMinLeadingZeros())) 6323 return ConstantRange(KnownStart.getMinValue(), 6324 KnownEnd.getMaxValue() + 1); 6325 break; 6326 } 6327 }; 6328 return FullSet; 6329 } 6330 6331 /// Determine the range for a particular SCEV. If SignHint is 6332 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 6333 /// with a "cleaner" unsigned (resp. signed) representation. 6334 const ConstantRange & 6335 ScalarEvolution::getRangeRef(const SCEV *S, 6336 ScalarEvolution::RangeSignHint SignHint) { 6337 DenseMap<const SCEV *, ConstantRange> &Cache = 6338 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6339 : SignedRanges; 6340 ConstantRange::PreferredRangeType RangeType = 6341 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 6342 ? ConstantRange::Unsigned : ConstantRange::Signed; 6343 6344 // See if we've computed this range already. 6345 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 6346 if (I != Cache.end()) 6347 return I->second; 6348 6349 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 6350 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 6351 6352 unsigned BitWidth = getTypeSizeInBits(S->getType()); 6353 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 6354 using OBO = OverflowingBinaryOperator; 6355 6356 // If the value has known zeros, the maximum value will have those known zeros 6357 // as well. 6358 uint32_t TZ = GetMinTrailingZeros(S); 6359 if (TZ != 0) { 6360 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 6361 ConservativeResult = 6362 ConstantRange(APInt::getMinValue(BitWidth), 6363 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 6364 else 6365 ConservativeResult = ConstantRange( 6366 APInt::getSignedMinValue(BitWidth), 6367 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 6368 } 6369 6370 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 6371 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 6372 unsigned WrapType = OBO::AnyWrap; 6373 if (Add->hasNoSignedWrap()) 6374 WrapType |= OBO::NoSignedWrap; 6375 if (Add->hasNoUnsignedWrap()) 6376 WrapType |= OBO::NoUnsignedWrap; 6377 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 6378 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 6379 WrapType, RangeType); 6380 return setRange(Add, SignHint, 6381 ConservativeResult.intersectWith(X, RangeType)); 6382 } 6383 6384 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 6385 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 6386 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 6387 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 6388 return setRange(Mul, SignHint, 6389 ConservativeResult.intersectWith(X, RangeType)); 6390 } 6391 6392 if (isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) { 6393 Intrinsic::ID ID; 6394 switch (S->getSCEVType()) { 6395 case scUMaxExpr: 6396 ID = Intrinsic::umax; 6397 break; 6398 case scSMaxExpr: 6399 ID = Intrinsic::smax; 6400 break; 6401 case scUMinExpr: 6402 case scSequentialUMinExpr: 6403 ID = Intrinsic::umin; 6404 break; 6405 case scSMinExpr: 6406 ID = Intrinsic::smin; 6407 break; 6408 default: 6409 llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr."); 6410 } 6411 6412 const auto *NAry = cast<SCEVNAryExpr>(S); 6413 ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint); 6414 for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i) 6415 X = X.intrinsic(ID, {X, getRangeRef(NAry->getOperand(i), SignHint)}); 6416 return setRange(S, SignHint, 6417 ConservativeResult.intersectWith(X, RangeType)); 6418 } 6419 6420 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 6421 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 6422 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 6423 return setRange(UDiv, SignHint, 6424 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 6425 } 6426 6427 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 6428 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 6429 return setRange(ZExt, SignHint, 6430 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 6431 RangeType)); 6432 } 6433 6434 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 6435 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 6436 return setRange(SExt, SignHint, 6437 ConservativeResult.intersectWith(X.signExtend(BitWidth), 6438 RangeType)); 6439 } 6440 6441 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 6442 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 6443 return setRange(PtrToInt, SignHint, X); 6444 } 6445 6446 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 6447 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 6448 return setRange(Trunc, SignHint, 6449 ConservativeResult.intersectWith(X.truncate(BitWidth), 6450 RangeType)); 6451 } 6452 6453 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 6454 // If there's no unsigned wrap, the value will never be less than its 6455 // initial value. 6456 if (AddRec->hasNoUnsignedWrap()) { 6457 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 6458 if (!UnsignedMinValue.isZero()) 6459 ConservativeResult = ConservativeResult.intersectWith( 6460 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 6461 } 6462 6463 // If there's no signed wrap, and all the operands except initial value have 6464 // the same sign or zero, the value won't ever be: 6465 // 1: smaller than initial value if operands are non negative, 6466 // 2: bigger than initial value if operands are non positive. 6467 // For both cases, value can not cross signed min/max boundary. 6468 if (AddRec->hasNoSignedWrap()) { 6469 bool AllNonNeg = true; 6470 bool AllNonPos = true; 6471 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 6472 if (!isKnownNonNegative(AddRec->getOperand(i))) 6473 AllNonNeg = false; 6474 if (!isKnownNonPositive(AddRec->getOperand(i))) 6475 AllNonPos = false; 6476 } 6477 if (AllNonNeg) 6478 ConservativeResult = ConservativeResult.intersectWith( 6479 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 6480 APInt::getSignedMinValue(BitWidth)), 6481 RangeType); 6482 else if (AllNonPos) 6483 ConservativeResult = ConservativeResult.intersectWith( 6484 ConstantRange::getNonEmpty( 6485 APInt::getSignedMinValue(BitWidth), 6486 getSignedRangeMax(AddRec->getStart()) + 1), 6487 RangeType); 6488 } 6489 6490 // TODO: non-affine addrec 6491 if (AddRec->isAffine()) { 6492 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 6493 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 6494 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 6495 auto RangeFromAffine = getRangeForAffineAR( 6496 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6497 BitWidth); 6498 ConservativeResult = 6499 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 6500 6501 auto RangeFromFactoring = getRangeViaFactoring( 6502 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 6503 BitWidth); 6504 ConservativeResult = 6505 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 6506 } 6507 6508 // Now try symbolic BE count and more powerful methods. 6509 if (UseExpensiveRangeSharpening) { 6510 const SCEV *SymbolicMaxBECount = 6511 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 6512 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 6513 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6514 AddRec->hasNoSelfWrap()) { 6515 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 6516 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 6517 ConservativeResult = 6518 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 6519 } 6520 } 6521 } 6522 6523 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 6524 } 6525 6526 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 6527 6528 // Check if the IR explicitly contains !range metadata. 6529 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 6530 if (MDRange.hasValue()) 6531 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 6532 RangeType); 6533 6534 // Use facts about recurrences in the underlying IR. Note that add 6535 // recurrences are AddRecExprs and thus don't hit this path. This 6536 // primarily handles shift recurrences. 6537 auto CR = getRangeForUnknownRecurrence(U); 6538 ConservativeResult = ConservativeResult.intersectWith(CR); 6539 6540 // See if ValueTracking can give us a useful range. 6541 const DataLayout &DL = getDataLayout(); 6542 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6543 if (Known.getBitWidth() != BitWidth) 6544 Known = Known.zextOrTrunc(BitWidth); 6545 6546 // ValueTracking may be able to compute a tighter result for the number of 6547 // sign bits than for the value of those sign bits. 6548 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 6549 if (U->getType()->isPointerTy()) { 6550 // If the pointer size is larger than the index size type, this can cause 6551 // NS to be larger than BitWidth. So compensate for this. 6552 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 6553 int ptrIdxDiff = ptrSize - BitWidth; 6554 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 6555 NS -= ptrIdxDiff; 6556 } 6557 6558 if (NS > 1) { 6559 // If we know any of the sign bits, we know all of the sign bits. 6560 if (!Known.Zero.getHiBits(NS).isZero()) 6561 Known.Zero.setHighBits(NS); 6562 if (!Known.One.getHiBits(NS).isZero()) 6563 Known.One.setHighBits(NS); 6564 } 6565 6566 if (Known.getMinValue() != Known.getMaxValue() + 1) 6567 ConservativeResult = ConservativeResult.intersectWith( 6568 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 6569 RangeType); 6570 if (NS > 1) 6571 ConservativeResult = ConservativeResult.intersectWith( 6572 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 6573 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 6574 RangeType); 6575 6576 // A range of Phi is a subset of union of all ranges of its input. 6577 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) 6578 if (!PendingPhiRanges.count(Phi)) 6579 sharpenPhiSCCRange(Phi, ConservativeResult, SignHint); 6580 6581 return setRange(U, SignHint, std::move(ConservativeResult)); 6582 } 6583 6584 return setRange(S, SignHint, std::move(ConservativeResult)); 6585 } 6586 6587 bool ScalarEvolution::collectSCC(const PHINode *Phi, 6588 SmallVectorImpl<const PHINode *> &SCC) const { 6589 assert(SCC.empty() && "Precondition: SCC should be empty."); 6590 auto Bail = [&]() { 6591 SCC.clear(); 6592 SCC.push_back(Phi); 6593 return false; 6594 }; 6595 SmallPtrSet<const PHINode *, 4> Reachable; 6596 { 6597 // First, find all PHI nodes that are reachable from Phi. 6598 SmallVector<const PHINode *, 4> Worklist; 6599 Reachable.insert(Phi); 6600 Worklist.push_back(Phi); 6601 while (!Worklist.empty()) { 6602 if (Reachable.size() > MaxPhiSCCAnalysisSize) 6603 // Too many nodes to process. Assume that SCC is composed of Phi alone. 6604 return Bail(); 6605 auto *Curr = Worklist.pop_back_val(); 6606 for (auto &Op : Curr->operands()) { 6607 if (auto *PhiOp = dyn_cast<PHINode>(&*Op)) { 6608 if (PendingPhiRanges.count(PhiOp)) 6609 // Do not want to deal with this situation, so conservatively bail. 6610 return Bail(); 6611 if (Reachable.insert(PhiOp).second) 6612 Worklist.push_back(PhiOp); 6613 } 6614 } 6615 } 6616 } 6617 { 6618 // Out of reachable nodes, find those from which Phi is also reachable. This 6619 // defines a SCC. 6620 SmallVector<const PHINode *, 4> Worklist; 6621 SmallPtrSet<const PHINode *, 4> SCCSet; 6622 SCCSet.insert(Phi); 6623 SCC.push_back(Phi); 6624 Worklist.push_back(Phi); 6625 while (!Worklist.empty()) { 6626 auto *Curr = Worklist.pop_back_val(); 6627 for (auto *User : Curr->users()) 6628 if (auto *PN = dyn_cast<PHINode>(User)) 6629 if (Reachable.count(PN) && SCCSet.insert(PN).second) { 6630 Worklist.push_back(PN); 6631 SCC.push_back(PN); 6632 } 6633 } 6634 } 6635 return true; 6636 } 6637 6638 void 6639 ScalarEvolution::sharpenPhiSCCRange(const PHINode *Phi, 6640 ConstantRange &ConservativeResult, 6641 ScalarEvolution::RangeSignHint SignHint) { 6642 // Collect strongly connected component (further on - SCC ) composed of Phis. 6643 // Analyze all values that are incoming to this SCC (we call them roots). 6644 // All SCC elements have range that is not wider than union of ranges of 6645 // roots. 6646 SmallVector<const PHINode *, 8> SCC; 6647 if (collectSCC(Phi, SCC)) 6648 ++NumFoundPhiSCCs; 6649 6650 // Collect roots: inputs of SCC nodes that come from outside of SCC. 6651 SmallPtrSet<Value *, 4> Roots; 6652 const SmallPtrSet<const PHINode *, 8> SCCSet(SCC.begin(), SCC.end()); 6653 for (auto *PN : SCC) 6654 for (auto &Op : PN->operands()) { 6655 auto *PhiInput = dyn_cast<PHINode>(Op); 6656 if (!PhiInput || !SCCSet.count(PhiInput)) 6657 Roots.insert(Op); 6658 } 6659 6660 // Mark SCC elements as pending to avoid infinite recursion if there is a 6661 // cyclic dependency through some instruction that is not a PHI. 6662 for (auto *PN : SCC) { 6663 bool Inserted = PendingPhiRanges.insert(PN).second; 6664 assert(Inserted && "PHI is already pending?"); 6665 (void)Inserted; 6666 } 6667 6668 auto BitWidth = ConservativeResult.getBitWidth(); 6669 ConstantRange RangeFromRoots(BitWidth, /*isFullSet=*/false); 6670 for (auto *Root : Roots) { 6671 auto OpRange = getRangeRef(getSCEV(Root), SignHint); 6672 RangeFromRoots = RangeFromRoots.unionWith(OpRange); 6673 // No point to continue if we already have a full set. 6674 if (RangeFromRoots.isFullSet()) 6675 break; 6676 } 6677 ConstantRange::PreferredRangeType RangeType = 6678 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned 6679 : ConstantRange::Signed; 6680 ConservativeResult = 6681 ConservativeResult.intersectWith(RangeFromRoots, RangeType); 6682 6683 DenseMap<const SCEV *, ConstantRange> &Cache = 6684 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 6685 : SignedRanges; 6686 // Entire SCC has the same range. 6687 for (auto *PN : SCC) { 6688 bool Erased = PendingPhiRanges.erase(PN); 6689 assert(Erased && "Failed to erase Phi properly?"); 6690 (void)Erased; 6691 auto *PNSCEV = getSCEV(const_cast<PHINode *>(PN)); 6692 auto I = Cache.find(PNSCEV); 6693 if (I == Cache.end()) 6694 setRange(PNSCEV, SignHint, ConservativeResult); 6695 else { 6696 auto SharpenedRange = 6697 I->second.intersectWith(ConservativeResult, RangeType); 6698 setRange(PNSCEV, SignHint, SharpenedRange); 6699 } 6700 } 6701 } 6702 6703 // Given a StartRange, Step and MaxBECount for an expression compute a range of 6704 // values that the expression can take. Initially, the expression has a value 6705 // from StartRange and then is changed by Step up to MaxBECount times. Signed 6706 // argument defines if we treat Step as signed or unsigned. 6707 static ConstantRange getRangeForAffineARHelper(APInt Step, 6708 const ConstantRange &StartRange, 6709 const APInt &MaxBECount, 6710 unsigned BitWidth, bool Signed) { 6711 // If either Step or MaxBECount is 0, then the expression won't change, and we 6712 // just need to return the initial range. 6713 if (Step == 0 || MaxBECount == 0) 6714 return StartRange; 6715 6716 // If we don't know anything about the initial value (i.e. StartRange is 6717 // FullRange), then we don't know anything about the final range either. 6718 // Return FullRange. 6719 if (StartRange.isFullSet()) 6720 return ConstantRange::getFull(BitWidth); 6721 6722 // If Step is signed and negative, then we use its absolute value, but we also 6723 // note that we're moving in the opposite direction. 6724 bool Descending = Signed && Step.isNegative(); 6725 6726 if (Signed) 6727 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 6728 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 6729 // This equations hold true due to the well-defined wrap-around behavior of 6730 // APInt. 6731 Step = Step.abs(); 6732 6733 // Check if Offset is more than full span of BitWidth. If it is, the 6734 // expression is guaranteed to overflow. 6735 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 6736 return ConstantRange::getFull(BitWidth); 6737 6738 // Offset is by how much the expression can change. Checks above guarantee no 6739 // overflow here. 6740 APInt Offset = Step * MaxBECount; 6741 6742 // Minimum value of the final range will match the minimal value of StartRange 6743 // if the expression is increasing and will be decreased by Offset otherwise. 6744 // Maximum value of the final range will match the maximal value of StartRange 6745 // if the expression is decreasing and will be increased by Offset otherwise. 6746 APInt StartLower = StartRange.getLower(); 6747 APInt StartUpper = StartRange.getUpper() - 1; 6748 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 6749 : (StartUpper + std::move(Offset)); 6750 6751 // It's possible that the new minimum/maximum value will fall into the initial 6752 // range (due to wrap around). This means that the expression can take any 6753 // value in this bitwidth, and we have to return full range. 6754 if (StartRange.contains(MovedBoundary)) 6755 return ConstantRange::getFull(BitWidth); 6756 6757 APInt NewLower = 6758 Descending ? std::move(MovedBoundary) : std::move(StartLower); 6759 APInt NewUpper = 6760 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 6761 NewUpper += 1; 6762 6763 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 6764 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 6765 } 6766 6767 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 6768 const SCEV *Step, 6769 const SCEV *MaxBECount, 6770 unsigned BitWidth) { 6771 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 6772 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 6773 "Precondition!"); 6774 6775 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 6776 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 6777 6778 // First, consider step signed. 6779 ConstantRange StartSRange = getSignedRange(Start); 6780 ConstantRange StepSRange = getSignedRange(Step); 6781 6782 // If Step can be both positive and negative, we need to find ranges for the 6783 // maximum absolute step values in both directions and union them. 6784 ConstantRange SR = 6785 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 6786 MaxBECountValue, BitWidth, /* Signed = */ true); 6787 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 6788 StartSRange, MaxBECountValue, 6789 BitWidth, /* Signed = */ true)); 6790 6791 // Next, consider step unsigned. 6792 ConstantRange UR = getRangeForAffineARHelper( 6793 getUnsignedRangeMax(Step), getUnsignedRange(Start), 6794 MaxBECountValue, BitWidth, /* Signed = */ false); 6795 6796 // Finally, intersect signed and unsigned ranges. 6797 return SR.intersectWith(UR, ConstantRange::Smallest); 6798 } 6799 6800 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 6801 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 6802 ScalarEvolution::RangeSignHint SignHint) { 6803 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 6804 assert(AddRec->hasNoSelfWrap() && 6805 "This only works for non-self-wrapping AddRecs!"); 6806 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 6807 const SCEV *Step = AddRec->getStepRecurrence(*this); 6808 // Only deal with constant step to save compile time. 6809 if (!isa<SCEVConstant>(Step)) 6810 return ConstantRange::getFull(BitWidth); 6811 // Let's make sure that we can prove that we do not self-wrap during 6812 // MaxBECount iterations. We need this because MaxBECount is a maximum 6813 // iteration count estimate, and we might infer nw from some exit for which we 6814 // do not know max exit count (or any other side reasoning). 6815 // TODO: Turn into assert at some point. 6816 if (getTypeSizeInBits(MaxBECount->getType()) > 6817 getTypeSizeInBits(AddRec->getType())) 6818 return ConstantRange::getFull(BitWidth); 6819 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 6820 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 6821 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 6822 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 6823 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 6824 MaxItersWithoutWrap)) 6825 return ConstantRange::getFull(BitWidth); 6826 6827 ICmpInst::Predicate LEPred = 6828 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 6829 ICmpInst::Predicate GEPred = 6830 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 6831 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 6832 6833 // We know that there is no self-wrap. Let's take Start and End values and 6834 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 6835 // the iteration. They either lie inside the range [Min(Start, End), 6836 // Max(Start, End)] or outside it: 6837 // 6838 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 6839 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 6840 // 6841 // No self wrap flag guarantees that the intermediate values cannot be BOTH 6842 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 6843 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 6844 // Start <= End and step is positive, or Start >= End and step is negative. 6845 const SCEV *Start = AddRec->getStart(); 6846 ConstantRange StartRange = getRangeRef(Start, SignHint); 6847 ConstantRange EndRange = getRangeRef(End, SignHint); 6848 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 6849 // If they already cover full iteration space, we will know nothing useful 6850 // even if we prove what we want to prove. 6851 if (RangeBetween.isFullSet()) 6852 return RangeBetween; 6853 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 6854 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 6855 : RangeBetween.isWrappedSet(); 6856 if (IsWrappedSet) 6857 return ConstantRange::getFull(BitWidth); 6858 6859 if (isKnownPositive(Step) && 6860 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 6861 return RangeBetween; 6862 else if (isKnownNegative(Step) && 6863 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 6864 return RangeBetween; 6865 return ConstantRange::getFull(BitWidth); 6866 } 6867 6868 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 6869 const SCEV *Step, 6870 const SCEV *MaxBECount, 6871 unsigned BitWidth) { 6872 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 6873 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 6874 6875 struct SelectPattern { 6876 Value *Condition = nullptr; 6877 APInt TrueValue; 6878 APInt FalseValue; 6879 6880 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 6881 const SCEV *S) { 6882 Optional<unsigned> CastOp; 6883 APInt Offset(BitWidth, 0); 6884 6885 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 6886 "Should be!"); 6887 6888 // Peel off a constant offset: 6889 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 6890 // In the future we could consider being smarter here and handle 6891 // {Start+Step,+,Step} too. 6892 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 6893 return; 6894 6895 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 6896 S = SA->getOperand(1); 6897 } 6898 6899 // Peel off a cast operation 6900 if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) { 6901 CastOp = SCast->getSCEVType(); 6902 S = SCast->getOperand(); 6903 } 6904 6905 using namespace llvm::PatternMatch; 6906 6907 auto *SU = dyn_cast<SCEVUnknown>(S); 6908 const APInt *TrueVal, *FalseVal; 6909 if (!SU || 6910 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 6911 m_APInt(FalseVal)))) { 6912 Condition = nullptr; 6913 return; 6914 } 6915 6916 TrueValue = *TrueVal; 6917 FalseValue = *FalseVal; 6918 6919 // Re-apply the cast we peeled off earlier 6920 if (CastOp.hasValue()) 6921 switch (*CastOp) { 6922 default: 6923 llvm_unreachable("Unknown SCEV cast type!"); 6924 6925 case scTruncate: 6926 TrueValue = TrueValue.trunc(BitWidth); 6927 FalseValue = FalseValue.trunc(BitWidth); 6928 break; 6929 case scZeroExtend: 6930 TrueValue = TrueValue.zext(BitWidth); 6931 FalseValue = FalseValue.zext(BitWidth); 6932 break; 6933 case scSignExtend: 6934 TrueValue = TrueValue.sext(BitWidth); 6935 FalseValue = FalseValue.sext(BitWidth); 6936 break; 6937 } 6938 6939 // Re-apply the constant offset we peeled off earlier 6940 TrueValue += Offset; 6941 FalseValue += Offset; 6942 } 6943 6944 bool isRecognized() { return Condition != nullptr; } 6945 }; 6946 6947 SelectPattern StartPattern(*this, BitWidth, Start); 6948 if (!StartPattern.isRecognized()) 6949 return ConstantRange::getFull(BitWidth); 6950 6951 SelectPattern StepPattern(*this, BitWidth, Step); 6952 if (!StepPattern.isRecognized()) 6953 return ConstantRange::getFull(BitWidth); 6954 6955 if (StartPattern.Condition != StepPattern.Condition) { 6956 // We don't handle this case today; but we could, by considering four 6957 // possibilities below instead of two. I'm not sure if there are cases where 6958 // that will help over what getRange already does, though. 6959 return ConstantRange::getFull(BitWidth); 6960 } 6961 6962 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6963 // construct arbitrary general SCEV expressions here. This function is called 6964 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6965 // say) can end up caching a suboptimal value. 6966 6967 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6968 // C2352 and C2512 (otherwise it isn't needed). 6969 6970 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6971 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6972 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6973 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6974 6975 ConstantRange TrueRange = 6976 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6977 ConstantRange FalseRange = 6978 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6979 6980 return TrueRange.unionWith(FalseRange); 6981 } 6982 6983 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6984 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6985 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6986 6987 // Return early if there are no flags to propagate to the SCEV. 6988 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6989 if (BinOp->hasNoUnsignedWrap()) 6990 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6991 if (BinOp->hasNoSignedWrap()) 6992 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6993 if (Flags == SCEV::FlagAnyWrap) 6994 return SCEV::FlagAnyWrap; 6995 6996 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6997 } 6998 6999 const Instruction * 7000 ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) { 7001 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 7002 return &*AddRec->getLoop()->getHeader()->begin(); 7003 if (auto *U = dyn_cast<SCEVUnknown>(S)) 7004 if (auto *I = dyn_cast<Instruction>(U->getValue())) 7005 return I; 7006 return nullptr; 7007 } 7008 7009 /// Fills \p Ops with unique operands of \p S, if it has operands. If not, 7010 /// \p Ops remains unmodified. 7011 static void collectUniqueOps(const SCEV *S, 7012 SmallVectorImpl<const SCEV *> &Ops) { 7013 SmallPtrSet<const SCEV *, 4> Unique; 7014 auto InsertUnique = [&](const SCEV *S) { 7015 if (Unique.insert(S).second) 7016 Ops.push_back(S); 7017 }; 7018 if (auto *S2 = dyn_cast<SCEVCastExpr>(S)) 7019 for (auto *Op : S2->operands()) 7020 InsertUnique(Op); 7021 else if (auto *S2 = dyn_cast<SCEVNAryExpr>(S)) 7022 for (auto *Op : S2->operands()) 7023 InsertUnique(Op); 7024 else if (auto *S2 = dyn_cast<SCEVUDivExpr>(S)) 7025 for (auto *Op : S2->operands()) 7026 InsertUnique(Op); 7027 } 7028 7029 const Instruction * 7030 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops, 7031 bool &Precise) { 7032 Precise = true; 7033 // Do a bounded search of the def relation of the requested SCEVs. 7034 SmallSet<const SCEV *, 16> Visited; 7035 SmallVector<const SCEV *> Worklist; 7036 auto pushOp = [&](const SCEV *S) { 7037 if (!Visited.insert(S).second) 7038 return; 7039 // Threshold of 30 here is arbitrary. 7040 if (Visited.size() > 30) { 7041 Precise = false; 7042 return; 7043 } 7044 Worklist.push_back(S); 7045 }; 7046 7047 for (auto *S : Ops) 7048 pushOp(S); 7049 7050 const Instruction *Bound = nullptr; 7051 while (!Worklist.empty()) { 7052 auto *S = Worklist.pop_back_val(); 7053 if (auto *DefI = getNonTrivialDefiningScopeBound(S)) { 7054 if (!Bound || DT.dominates(Bound, DefI)) 7055 Bound = DefI; 7056 } else { 7057 SmallVector<const SCEV *, 4> Ops; 7058 collectUniqueOps(S, Ops); 7059 for (auto *Op : Ops) 7060 pushOp(Op); 7061 } 7062 } 7063 return Bound ? Bound : &*F.getEntryBlock().begin(); 7064 } 7065 7066 const Instruction * 7067 ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) { 7068 bool Discard; 7069 return getDefiningScopeBound(Ops, Discard); 7070 } 7071 7072 bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A, 7073 const Instruction *B) { 7074 if (A->getParent() == B->getParent() && 7075 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 7076 B->getIterator())) 7077 return true; 7078 7079 auto *BLoop = LI.getLoopFor(B->getParent()); 7080 if (BLoop && BLoop->getHeader() == B->getParent() && 7081 BLoop->getLoopPreheader() == A->getParent() && 7082 isGuaranteedToTransferExecutionToSuccessor(A->getIterator(), 7083 A->getParent()->end()) && 7084 isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(), 7085 B->getIterator())) 7086 return true; 7087 return false; 7088 } 7089 7090 7091 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 7092 // Only proceed if we can prove that I does not yield poison. 7093 if (!programUndefinedIfPoison(I)) 7094 return false; 7095 7096 // At this point we know that if I is executed, then it does not wrap 7097 // according to at least one of NSW or NUW. If I is not executed, then we do 7098 // not know if the calculation that I represents would wrap. Multiple 7099 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 7100 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 7101 // derived from other instructions that map to the same SCEV. We cannot make 7102 // that guarantee for cases where I is not executed. So we need to find a 7103 // upper bound on the defining scope for the SCEV, and prove that I is 7104 // executed every time we enter that scope. When the bounding scope is a 7105 // loop (the common case), this is equivalent to proving I executes on every 7106 // iteration of that loop. 7107 SmallVector<const SCEV *> SCEVOps; 7108 for (const Use &Op : I->operands()) { 7109 // I could be an extractvalue from a call to an overflow intrinsic. 7110 // TODO: We can do better here in some cases. 7111 if (isSCEVable(Op->getType())) 7112 SCEVOps.push_back(getSCEV(Op)); 7113 } 7114 auto *DefI = getDefiningScopeBound(SCEVOps); 7115 return isGuaranteedToTransferExecutionTo(DefI, I); 7116 } 7117 7118 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 7119 // If we know that \c I can never be poison period, then that's enough. 7120 if (isSCEVExprNeverPoison(I)) 7121 return true; 7122 7123 // For an add recurrence specifically, we assume that infinite loops without 7124 // side effects are undefined behavior, and then reason as follows: 7125 // 7126 // If the add recurrence is poison in any iteration, it is poison on all 7127 // future iterations (since incrementing poison yields poison). If the result 7128 // of the add recurrence is fed into the loop latch condition and the loop 7129 // does not contain any throws or exiting blocks other than the latch, we now 7130 // have the ability to "choose" whether the backedge is taken or not (by 7131 // choosing a sufficiently evil value for the poison feeding into the branch) 7132 // for every iteration including and after the one in which \p I first became 7133 // poison. There are two possibilities (let's call the iteration in which \p 7134 // I first became poison as K): 7135 // 7136 // 1. In the set of iterations including and after K, the loop body executes 7137 // no side effects. In this case executing the backege an infinte number 7138 // of times will yield undefined behavior. 7139 // 7140 // 2. In the set of iterations including and after K, the loop body executes 7141 // at least one side effect. In this case, that specific instance of side 7142 // effect is control dependent on poison, which also yields undefined 7143 // behavior. 7144 7145 auto *ExitingBB = L->getExitingBlock(); 7146 auto *LatchBB = L->getLoopLatch(); 7147 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 7148 return false; 7149 7150 SmallPtrSet<const Instruction *, 16> Pushed; 7151 SmallVector<const Instruction *, 8> PoisonStack; 7152 7153 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 7154 // things that are known to be poison under that assumption go on the 7155 // PoisonStack. 7156 Pushed.insert(I); 7157 PoisonStack.push_back(I); 7158 7159 bool LatchControlDependentOnPoison = false; 7160 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 7161 const Instruction *Poison = PoisonStack.pop_back_val(); 7162 7163 for (auto *PoisonUser : Poison->users()) { 7164 if (propagatesPoison(cast<Operator>(PoisonUser))) { 7165 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 7166 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 7167 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 7168 assert(BI->isConditional() && "Only possibility!"); 7169 if (BI->getParent() == LatchBB) { 7170 LatchControlDependentOnPoison = true; 7171 break; 7172 } 7173 } 7174 } 7175 } 7176 7177 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 7178 } 7179 7180 ScalarEvolution::LoopProperties 7181 ScalarEvolution::getLoopProperties(const Loop *L) { 7182 using LoopProperties = ScalarEvolution::LoopProperties; 7183 7184 auto Itr = LoopPropertiesCache.find(L); 7185 if (Itr == LoopPropertiesCache.end()) { 7186 auto HasSideEffects = [](Instruction *I) { 7187 if (auto *SI = dyn_cast<StoreInst>(I)) 7188 return !SI->isSimple(); 7189 7190 return I->mayThrow() || I->mayWriteToMemory(); 7191 }; 7192 7193 LoopProperties LP = {/* HasNoAbnormalExits */ true, 7194 /*HasNoSideEffects*/ true}; 7195 7196 for (auto *BB : L->getBlocks()) 7197 for (auto &I : *BB) { 7198 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 7199 LP.HasNoAbnormalExits = false; 7200 if (HasSideEffects(&I)) 7201 LP.HasNoSideEffects = false; 7202 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 7203 break; // We're already as pessimistic as we can get. 7204 } 7205 7206 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 7207 assert(InsertPair.second && "We just checked!"); 7208 Itr = InsertPair.first; 7209 } 7210 7211 return Itr->second; 7212 } 7213 7214 bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) { 7215 // A mustprogress loop without side effects must be finite. 7216 // TODO: The check used here is very conservative. It's only *specific* 7217 // side effects which are well defined in infinite loops. 7218 return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L)); 7219 } 7220 7221 const SCEV *ScalarEvolution::createSCEV(Value *V) { 7222 if (!isSCEVable(V->getType())) 7223 return getUnknown(V); 7224 7225 if (Instruction *I = dyn_cast<Instruction>(V)) { 7226 // Don't attempt to analyze instructions in blocks that aren't 7227 // reachable. Such instructions don't matter, and they aren't required 7228 // to obey basic rules for definitions dominating uses which this 7229 // analysis depends on. 7230 if (!DT.isReachableFromEntry(I->getParent())) 7231 return getUnknown(UndefValue::get(V->getType())); 7232 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 7233 return getConstant(CI); 7234 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 7235 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 7236 else if (!isa<ConstantExpr>(V)) 7237 return getUnknown(V); 7238 7239 Operator *U = cast<Operator>(V); 7240 if (auto BO = MatchBinaryOp(U, DT)) { 7241 switch (BO->Opcode) { 7242 case Instruction::Add: { 7243 // The simple thing to do would be to just call getSCEV on both operands 7244 // and call getAddExpr with the result. However if we're looking at a 7245 // bunch of things all added together, this can be quite inefficient, 7246 // because it leads to N-1 getAddExpr calls for N ultimate operands. 7247 // Instead, gather up all the operands and make a single getAddExpr call. 7248 // LLVM IR canonical form means we need only traverse the left operands. 7249 SmallVector<const SCEV *, 4> AddOps; 7250 do { 7251 if (BO->Op) { 7252 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7253 AddOps.push_back(OpSCEV); 7254 break; 7255 } 7256 7257 // If a NUW or NSW flag can be applied to the SCEV for this 7258 // addition, then compute the SCEV for this addition by itself 7259 // with a separate call to getAddExpr. We need to do that 7260 // instead of pushing the operands of the addition onto AddOps, 7261 // since the flags are only known to apply to this particular 7262 // addition - they may not apply to other additions that can be 7263 // formed with operands from AddOps. 7264 const SCEV *RHS = getSCEV(BO->RHS); 7265 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7266 if (Flags != SCEV::FlagAnyWrap) { 7267 const SCEV *LHS = getSCEV(BO->LHS); 7268 if (BO->Opcode == Instruction::Sub) 7269 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 7270 else 7271 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 7272 break; 7273 } 7274 } 7275 7276 if (BO->Opcode == Instruction::Sub) 7277 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 7278 else 7279 AddOps.push_back(getSCEV(BO->RHS)); 7280 7281 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7282 if (!NewBO || (NewBO->Opcode != Instruction::Add && 7283 NewBO->Opcode != Instruction::Sub)) { 7284 AddOps.push_back(getSCEV(BO->LHS)); 7285 break; 7286 } 7287 BO = NewBO; 7288 } while (true); 7289 7290 return getAddExpr(AddOps); 7291 } 7292 7293 case Instruction::Mul: { 7294 SmallVector<const SCEV *, 4> MulOps; 7295 do { 7296 if (BO->Op) { 7297 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 7298 MulOps.push_back(OpSCEV); 7299 break; 7300 } 7301 7302 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 7303 if (Flags != SCEV::FlagAnyWrap) { 7304 MulOps.push_back( 7305 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 7306 break; 7307 } 7308 } 7309 7310 MulOps.push_back(getSCEV(BO->RHS)); 7311 auto NewBO = MatchBinaryOp(BO->LHS, DT); 7312 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 7313 MulOps.push_back(getSCEV(BO->LHS)); 7314 break; 7315 } 7316 BO = NewBO; 7317 } while (true); 7318 7319 return getMulExpr(MulOps); 7320 } 7321 case Instruction::UDiv: 7322 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7323 case Instruction::URem: 7324 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7325 case Instruction::Sub: { 7326 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 7327 if (BO->Op) 7328 Flags = getNoWrapFlagsFromUB(BO->Op); 7329 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 7330 } 7331 case Instruction::And: 7332 // For an expression like x&255 that merely masks off the high bits, 7333 // use zext(trunc(x)) as the SCEV expression. 7334 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7335 if (CI->isZero()) 7336 return getSCEV(BO->RHS); 7337 if (CI->isMinusOne()) 7338 return getSCEV(BO->LHS); 7339 const APInt &A = CI->getValue(); 7340 7341 // Instcombine's ShrinkDemandedConstant may strip bits out of 7342 // constants, obscuring what would otherwise be a low-bits mask. 7343 // Use computeKnownBits to compute what ShrinkDemandedConstant 7344 // knew about to reconstruct a low-bits mask value. 7345 unsigned LZ = A.countLeadingZeros(); 7346 unsigned TZ = A.countTrailingZeros(); 7347 unsigned BitWidth = A.getBitWidth(); 7348 KnownBits Known(BitWidth); 7349 computeKnownBits(BO->LHS, Known, getDataLayout(), 7350 0, &AC, nullptr, &DT); 7351 7352 APInt EffectiveMask = 7353 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 7354 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 7355 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 7356 const SCEV *LHS = getSCEV(BO->LHS); 7357 const SCEV *ShiftedLHS = nullptr; 7358 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 7359 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 7360 // For an expression like (x * 8) & 8, simplify the multiply. 7361 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 7362 unsigned GCD = std::min(MulZeros, TZ); 7363 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 7364 SmallVector<const SCEV*, 4> MulOps; 7365 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 7366 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 7367 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 7368 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 7369 } 7370 } 7371 if (!ShiftedLHS) 7372 ShiftedLHS = getUDivExpr(LHS, MulCount); 7373 return getMulExpr( 7374 getZeroExtendExpr( 7375 getTruncateExpr(ShiftedLHS, 7376 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 7377 BO->LHS->getType()), 7378 MulCount); 7379 } 7380 } 7381 // Binary `and` is a bit-wise `umin`. 7382 if (BO->LHS->getType()->isIntegerTy(1)) 7383 return getUMinExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7384 break; 7385 7386 case Instruction::Or: 7387 // If the RHS of the Or is a constant, we may have something like: 7388 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 7389 // optimizations will transparently handle this case. 7390 // 7391 // In order for this transformation to be safe, the LHS must be of the 7392 // form X*(2^n) and the Or constant must be less than 2^n. 7393 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7394 const SCEV *LHS = getSCEV(BO->LHS); 7395 const APInt &CIVal = CI->getValue(); 7396 if (GetMinTrailingZeros(LHS) >= 7397 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 7398 // Build a plain add SCEV. 7399 return getAddExpr(LHS, getSCEV(CI), 7400 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 7401 } 7402 } 7403 // Binary `or` is a bit-wise `umax`. 7404 if (BO->LHS->getType()->isIntegerTy(1)) 7405 return getUMaxExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 7406 break; 7407 7408 case Instruction::Xor: 7409 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 7410 // If the RHS of xor is -1, then this is a not operation. 7411 if (CI->isMinusOne()) 7412 return getNotSCEV(getSCEV(BO->LHS)); 7413 7414 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 7415 // This is a variant of the check for xor with -1, and it handles 7416 // the case where instcombine has trimmed non-demanded bits out 7417 // of an xor with -1. 7418 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 7419 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 7420 if (LBO->getOpcode() == Instruction::And && 7421 LCI->getValue() == CI->getValue()) 7422 if (const SCEVZeroExtendExpr *Z = 7423 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 7424 Type *UTy = BO->LHS->getType(); 7425 const SCEV *Z0 = Z->getOperand(); 7426 Type *Z0Ty = Z0->getType(); 7427 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 7428 7429 // If C is a low-bits mask, the zero extend is serving to 7430 // mask off the high bits. Complement the operand and 7431 // re-apply the zext. 7432 if (CI->getValue().isMask(Z0TySize)) 7433 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 7434 7435 // If C is a single bit, it may be in the sign-bit position 7436 // before the zero-extend. In this case, represent the xor 7437 // using an add, which is equivalent, and re-apply the zext. 7438 APInt Trunc = CI->getValue().trunc(Z0TySize); 7439 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 7440 Trunc.isSignMask()) 7441 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 7442 UTy); 7443 } 7444 } 7445 break; 7446 7447 case Instruction::Shl: 7448 // Turn shift left of a constant amount into a multiply. 7449 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 7450 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 7451 7452 // If the shift count is not less than the bitwidth, the result of 7453 // the shift is undefined. Don't try to analyze it, because the 7454 // resolution chosen here may differ from the resolution chosen in 7455 // other parts of the compiler. 7456 if (SA->getValue().uge(BitWidth)) 7457 break; 7458 7459 // We can safely preserve the nuw flag in all cases. It's also safe to 7460 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 7461 // requires special handling. It can be preserved as long as we're not 7462 // left shifting by bitwidth - 1. 7463 auto Flags = SCEV::FlagAnyWrap; 7464 if (BO->Op) { 7465 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 7466 if ((MulFlags & SCEV::FlagNSW) && 7467 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 7468 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 7469 if (MulFlags & SCEV::FlagNUW) 7470 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 7471 } 7472 7473 Constant *X = ConstantInt::get( 7474 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 7475 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 7476 } 7477 break; 7478 7479 case Instruction::AShr: { 7480 // AShr X, C, where C is a constant. 7481 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 7482 if (!CI) 7483 break; 7484 7485 Type *OuterTy = BO->LHS->getType(); 7486 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 7487 // If the shift count is not less than the bitwidth, the result of 7488 // the shift is undefined. Don't try to analyze it, because the 7489 // resolution chosen here may differ from the resolution chosen in 7490 // other parts of the compiler. 7491 if (CI->getValue().uge(BitWidth)) 7492 break; 7493 7494 if (CI->isZero()) 7495 return getSCEV(BO->LHS); // shift by zero --> noop 7496 7497 uint64_t AShrAmt = CI->getZExtValue(); 7498 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 7499 7500 Operator *L = dyn_cast<Operator>(BO->LHS); 7501 if (L && L->getOpcode() == Instruction::Shl) { 7502 // X = Shl A, n 7503 // Y = AShr X, m 7504 // Both n and m are constant. 7505 7506 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 7507 if (L->getOperand(1) == BO->RHS) 7508 // For a two-shift sext-inreg, i.e. n = m, 7509 // use sext(trunc(x)) as the SCEV expression. 7510 return getSignExtendExpr( 7511 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 7512 7513 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 7514 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 7515 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 7516 if (ShlAmt > AShrAmt) { 7517 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 7518 // expression. We already checked that ShlAmt < BitWidth, so 7519 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 7520 // ShlAmt - AShrAmt < Amt. 7521 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 7522 ShlAmt - AShrAmt); 7523 return getSignExtendExpr( 7524 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 7525 getConstant(Mul)), OuterTy); 7526 } 7527 } 7528 } 7529 break; 7530 } 7531 } 7532 } 7533 7534 switch (U->getOpcode()) { 7535 case Instruction::Trunc: 7536 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 7537 7538 case Instruction::ZExt: 7539 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7540 7541 case Instruction::SExt: 7542 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 7543 // The NSW flag of a subtract does not always survive the conversion to 7544 // A + (-1)*B. By pushing sign extension onto its operands we are much 7545 // more likely to preserve NSW and allow later AddRec optimisations. 7546 // 7547 // NOTE: This is effectively duplicating this logic from getSignExtend: 7548 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 7549 // but by that point the NSW information has potentially been lost. 7550 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 7551 Type *Ty = U->getType(); 7552 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 7553 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 7554 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 7555 } 7556 } 7557 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 7558 7559 case Instruction::BitCast: 7560 // BitCasts are no-op casts so we just eliminate the cast. 7561 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 7562 return getSCEV(U->getOperand(0)); 7563 break; 7564 7565 case Instruction::PtrToInt: { 7566 // Pointer to integer cast is straight-forward, so do model it. 7567 const SCEV *Op = getSCEV(U->getOperand(0)); 7568 Type *DstIntTy = U->getType(); 7569 // But only if effective SCEV (integer) type is wide enough to represent 7570 // all possible pointer values. 7571 const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy); 7572 if (isa<SCEVCouldNotCompute>(IntOp)) 7573 return getUnknown(V); 7574 return IntOp; 7575 } 7576 case Instruction::IntToPtr: 7577 // Just don't deal with inttoptr casts. 7578 return getUnknown(V); 7579 7580 case Instruction::SDiv: 7581 // If both operands are non-negative, this is just an udiv. 7582 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7583 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7584 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7585 break; 7586 7587 case Instruction::SRem: 7588 // If both operands are non-negative, this is just an urem. 7589 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 7590 isKnownNonNegative(getSCEV(U->getOperand(1)))) 7591 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 7592 break; 7593 7594 case Instruction::GetElementPtr: 7595 return createNodeForGEP(cast<GEPOperator>(U)); 7596 7597 case Instruction::PHI: 7598 return createNodeForPHI(cast<PHINode>(U)); 7599 7600 case Instruction::Select: 7601 return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1), 7602 U->getOperand(2)); 7603 7604 case Instruction::Call: 7605 case Instruction::Invoke: 7606 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 7607 return getSCEV(RV); 7608 7609 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 7610 switch (II->getIntrinsicID()) { 7611 case Intrinsic::abs: 7612 return getAbsExpr( 7613 getSCEV(II->getArgOperand(0)), 7614 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 7615 case Intrinsic::umax: 7616 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 7617 getSCEV(II->getArgOperand(1))); 7618 case Intrinsic::umin: 7619 return getUMinExpr(getSCEV(II->getArgOperand(0)), 7620 getSCEV(II->getArgOperand(1))); 7621 case Intrinsic::smax: 7622 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 7623 getSCEV(II->getArgOperand(1))); 7624 case Intrinsic::smin: 7625 return getSMinExpr(getSCEV(II->getArgOperand(0)), 7626 getSCEV(II->getArgOperand(1))); 7627 case Intrinsic::usub_sat: { 7628 const SCEV *X = getSCEV(II->getArgOperand(0)); 7629 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7630 const SCEV *ClampedY = getUMinExpr(X, Y); 7631 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 7632 } 7633 case Intrinsic::uadd_sat: { 7634 const SCEV *X = getSCEV(II->getArgOperand(0)); 7635 const SCEV *Y = getSCEV(II->getArgOperand(1)); 7636 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 7637 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 7638 } 7639 case Intrinsic::start_loop_iterations: 7640 // A start_loop_iterations is just equivalent to the first operand for 7641 // SCEV purposes. 7642 return getSCEV(II->getArgOperand(0)); 7643 default: 7644 break; 7645 } 7646 } 7647 break; 7648 } 7649 7650 return getUnknown(V); 7651 } 7652 7653 //===----------------------------------------------------------------------===// 7654 // Iteration Count Computation Code 7655 // 7656 7657 const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount, 7658 bool Extend) { 7659 if (isa<SCEVCouldNotCompute>(ExitCount)) 7660 return getCouldNotCompute(); 7661 7662 auto *ExitCountType = ExitCount->getType(); 7663 assert(ExitCountType->isIntegerTy()); 7664 7665 if (!Extend) 7666 return getAddExpr(ExitCount, getOne(ExitCountType)); 7667 7668 auto *WiderType = Type::getIntNTy(ExitCountType->getContext(), 7669 1 + ExitCountType->getScalarSizeInBits()); 7670 return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType), 7671 getOne(WiderType)); 7672 } 7673 7674 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 7675 if (!ExitCount) 7676 return 0; 7677 7678 ConstantInt *ExitConst = ExitCount->getValue(); 7679 7680 // Guard against huge trip counts. 7681 if (ExitConst->getValue().getActiveBits() > 32) 7682 return 0; 7683 7684 // In case of integer overflow, this returns 0, which is correct. 7685 return ((unsigned)ExitConst->getZExtValue()) + 1; 7686 } 7687 7688 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 7689 auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact)); 7690 return getConstantTripCount(ExitCount); 7691 } 7692 7693 unsigned 7694 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 7695 const BasicBlock *ExitingBlock) { 7696 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7697 assert(L->isLoopExiting(ExitingBlock) && 7698 "Exiting block must actually branch out of the loop!"); 7699 const SCEVConstant *ExitCount = 7700 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 7701 return getConstantTripCount(ExitCount); 7702 } 7703 7704 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 7705 const auto *MaxExitCount = 7706 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 7707 return getConstantTripCount(MaxExitCount); 7708 } 7709 7710 const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) { 7711 // We can't infer from Array in Irregular Loop. 7712 // FIXME: It's hard to infer loop bound from array operated in Nested Loop. 7713 if (!L->isLoopSimplifyForm() || !L->isInnermost()) 7714 return getCouldNotCompute(); 7715 7716 // FIXME: To make the scene more typical, we only analysis loops that have 7717 // one exiting block and that block must be the latch. To make it easier to 7718 // capture loops that have memory access and memory access will be executed 7719 // in each iteration. 7720 const BasicBlock *LoopLatch = L->getLoopLatch(); 7721 assert(LoopLatch && "See defination of simplify form loop."); 7722 if (L->getExitingBlock() != LoopLatch) 7723 return getCouldNotCompute(); 7724 7725 const DataLayout &DL = getDataLayout(); 7726 SmallVector<const SCEV *> InferCountColl; 7727 for (auto *BB : L->getBlocks()) { 7728 // Go here, we can know that Loop is a single exiting and simplified form 7729 // loop. Make sure that infer from Memory Operation in those BBs must be 7730 // executed in loop. First step, we can make sure that max execution time 7731 // of MemAccessBB in loop represents latch max excution time. 7732 // If MemAccessBB does not dom Latch, skip. 7733 // Entry 7734 // │ 7735 // ┌─────▼─────┐ 7736 // │Loop Header◄─────┐ 7737 // └──┬──────┬─┘ │ 7738 // │ │ │ 7739 // ┌────────▼──┐ ┌─▼─────┐ │ 7740 // │MemAccessBB│ │OtherBB│ │ 7741 // └────────┬──┘ └─┬─────┘ │ 7742 // │ │ │ 7743 // ┌─▼──────▼─┐ │ 7744 // │Loop Latch├─────┘ 7745 // └────┬─────┘ 7746 // ▼ 7747 // Exit 7748 if (!DT.dominates(BB, LoopLatch)) 7749 continue; 7750 7751 for (Instruction &Inst : *BB) { 7752 // Find Memory Operation Instruction. 7753 auto *GEP = getLoadStorePointerOperand(&Inst); 7754 if (!GEP) 7755 continue; 7756 7757 auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst)); 7758 // Do not infer from scalar type, eg."ElemSize = sizeof()". 7759 if (!ElemSize) 7760 continue; 7761 7762 // Use a existing polynomial recurrence on the trip count. 7763 auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP)); 7764 if (!AddRec) 7765 continue; 7766 auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec)); 7767 auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this)); 7768 if (!ArrBase || !Step) 7769 continue; 7770 assert(isLoopInvariant(ArrBase, L) && "See addrec definition"); 7771 7772 // Only handle { %array + step }, 7773 // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here. 7774 if (AddRec->getStart() != ArrBase) 7775 continue; 7776 7777 // Memory operation pattern which have gaps. 7778 // Or repeat memory opreation. 7779 // And index of GEP wraps arround. 7780 if (Step->getAPInt().getActiveBits() > 32 || 7781 Step->getAPInt().getZExtValue() != 7782 ElemSize->getAPInt().getZExtValue() || 7783 Step->isZero() || Step->getAPInt().isNegative()) 7784 continue; 7785 7786 // Only infer from stack array which has certain size. 7787 // Make sure alloca instruction is not excuted in loop. 7788 AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue()); 7789 if (!AllocateInst || L->contains(AllocateInst->getParent())) 7790 continue; 7791 7792 // Make sure only handle normal array. 7793 auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType()); 7794 auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize()); 7795 if (!Ty || !ArrSize || !ArrSize->isOne()) 7796 continue; 7797 7798 // FIXME: Since gep indices are silently zext to the indexing type, 7799 // we will have a narrow gep index which wraps around rather than 7800 // increasing strictly, we shoule ensure that step is increasing 7801 // strictly by the loop iteration. 7802 // Now we can infer a max execution time by MemLength/StepLength. 7803 const SCEV *MemSize = 7804 getConstant(Step->getType(), DL.getTypeAllocSize(Ty)); 7805 auto *MaxExeCount = 7806 dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step)); 7807 if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32) 7808 continue; 7809 7810 // If the loop reaches the maximum number of executions, we can not 7811 // access bytes starting outside the statically allocated size without 7812 // being immediate UB. But it is allowed to enter loop header one more 7813 // time. 7814 auto *InferCount = dyn_cast<SCEVConstant>( 7815 getAddExpr(MaxExeCount, getOne(MaxExeCount->getType()))); 7816 // Discard the maximum number of execution times under 32bits. 7817 if (!InferCount || InferCount->getAPInt().getActiveBits() > 32) 7818 continue; 7819 7820 InferCountColl.push_back(InferCount); 7821 } 7822 } 7823 7824 if (InferCountColl.size() == 0) 7825 return getCouldNotCompute(); 7826 7827 return getUMinFromMismatchedTypes(InferCountColl); 7828 } 7829 7830 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 7831 SmallVector<BasicBlock *, 8> ExitingBlocks; 7832 L->getExitingBlocks(ExitingBlocks); 7833 7834 Optional<unsigned> Res = None; 7835 for (auto *ExitingBB : ExitingBlocks) { 7836 unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB); 7837 if (!Res) 7838 Res = Multiple; 7839 Res = (unsigned)GreatestCommonDivisor64(*Res, Multiple); 7840 } 7841 return Res.getValueOr(1); 7842 } 7843 7844 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7845 const SCEV *ExitCount) { 7846 if (ExitCount == getCouldNotCompute()) 7847 return 1; 7848 7849 // Get the trip count 7850 const SCEV *TCExpr = getTripCountFromExitCount(ExitCount); 7851 7852 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 7853 if (!TC) 7854 // Attempt to factor more general cases. Returns the greatest power of 7855 // two divisor. If overflow happens, the trip count expression is still 7856 // divisible by the greatest power of 2 divisor returned. 7857 return 1U << std::min((uint32_t)31, 7858 GetMinTrailingZeros(applyLoopGuards(TCExpr, L))); 7859 7860 ConstantInt *Result = TC->getValue(); 7861 7862 // Guard against huge trip counts (this requires checking 7863 // for zero to handle the case where the trip count == -1 and the 7864 // addition wraps). 7865 if (!Result || Result->getValue().getActiveBits() > 32 || 7866 Result->getValue().getActiveBits() == 0) 7867 return 1; 7868 7869 return (unsigned)Result->getZExtValue(); 7870 } 7871 7872 /// Returns the largest constant divisor of the trip count of this loop as a 7873 /// normal unsigned value, if possible. This means that the actual trip count is 7874 /// always a multiple of the returned value (don't forget the trip count could 7875 /// very well be zero as well!). 7876 /// 7877 /// Returns 1 if the trip count is unknown or not guaranteed to be the 7878 /// multiple of a constant (which is also the case if the trip count is simply 7879 /// constant, use getSmallConstantTripCount for that case), Will also return 1 7880 /// if the trip count is very large (>= 2^32). 7881 /// 7882 /// As explained in the comments for getSmallConstantTripCount, this assumes 7883 /// that control exits the loop via ExitingBlock. 7884 unsigned 7885 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 7886 const BasicBlock *ExitingBlock) { 7887 assert(ExitingBlock && "Must pass a non-null exiting block!"); 7888 assert(L->isLoopExiting(ExitingBlock) && 7889 "Exiting block must actually branch out of the loop!"); 7890 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 7891 return getSmallConstantTripMultiple(L, ExitCount); 7892 } 7893 7894 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 7895 const BasicBlock *ExitingBlock, 7896 ExitCountKind Kind) { 7897 switch (Kind) { 7898 case Exact: 7899 case SymbolicMaximum: 7900 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 7901 case ConstantMaximum: 7902 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 7903 }; 7904 llvm_unreachable("Invalid ExitCountKind!"); 7905 } 7906 7907 const SCEV * 7908 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 7909 SmallVector<const SCEVPredicate *, 4> &Preds) { 7910 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 7911 } 7912 7913 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 7914 ExitCountKind Kind) { 7915 switch (Kind) { 7916 case Exact: 7917 return getBackedgeTakenInfo(L).getExact(L, this); 7918 case ConstantMaximum: 7919 return getBackedgeTakenInfo(L).getConstantMax(this); 7920 case SymbolicMaximum: 7921 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 7922 }; 7923 llvm_unreachable("Invalid ExitCountKind!"); 7924 } 7925 7926 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 7927 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 7928 } 7929 7930 /// Push PHI nodes in the header of the given loop onto the given Worklist. 7931 static void PushLoopPHIs(const Loop *L, 7932 SmallVectorImpl<Instruction *> &Worklist, 7933 SmallPtrSetImpl<Instruction *> &Visited) { 7934 BasicBlock *Header = L->getHeader(); 7935 7936 // Push all Loop-header PHIs onto the Worklist stack. 7937 for (PHINode &PN : Header->phis()) 7938 if (Visited.insert(&PN).second) 7939 Worklist.push_back(&PN); 7940 } 7941 7942 const ScalarEvolution::BackedgeTakenInfo & 7943 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 7944 auto &BTI = getBackedgeTakenInfo(L); 7945 if (BTI.hasFullInfo()) 7946 return BTI; 7947 7948 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7949 7950 if (!Pair.second) 7951 return Pair.first->second; 7952 7953 BackedgeTakenInfo Result = 7954 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 7955 7956 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 7957 } 7958 7959 ScalarEvolution::BackedgeTakenInfo & 7960 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 7961 // Initially insert an invalid entry for this loop. If the insertion 7962 // succeeds, proceed to actually compute a backedge-taken count and 7963 // update the value. The temporary CouldNotCompute value tells SCEV 7964 // code elsewhere that it shouldn't attempt to request a new 7965 // backedge-taken count, which could result in infinite recursion. 7966 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 7967 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 7968 if (!Pair.second) 7969 return Pair.first->second; 7970 7971 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 7972 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 7973 // must be cleared in this scope. 7974 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 7975 7976 // In product build, there are no usage of statistic. 7977 (void)NumTripCountsComputed; 7978 (void)NumTripCountsNotComputed; 7979 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 7980 const SCEV *BEExact = Result.getExact(L, this); 7981 if (BEExact != getCouldNotCompute()) { 7982 assert(isLoopInvariant(BEExact, L) && 7983 isLoopInvariant(Result.getConstantMax(this), L) && 7984 "Computed backedge-taken count isn't loop invariant for loop!"); 7985 ++NumTripCountsComputed; 7986 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 7987 isa<PHINode>(L->getHeader()->begin())) { 7988 // Only count loops that have phi nodes as not being computable. 7989 ++NumTripCountsNotComputed; 7990 } 7991 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 7992 7993 // Now that we know more about the trip count for this loop, forget any 7994 // existing SCEV values for PHI nodes in this loop since they are only 7995 // conservative estimates made without the benefit of trip count 7996 // information. This invalidation is not necessary for correctness, and is 7997 // only done to produce more precise results. 7998 if (Result.hasAnyInfo()) { 7999 // Invalidate any expression using an addrec in this loop. 8000 SmallVector<const SCEV *, 8> ToForget; 8001 auto LoopUsersIt = LoopUsers.find(L); 8002 if (LoopUsersIt != LoopUsers.end()) 8003 append_range(ToForget, LoopUsersIt->second); 8004 forgetMemoizedResults(ToForget); 8005 8006 // Invalidate constant-evolved loop header phis. 8007 for (PHINode &PN : L->getHeader()->phis()) 8008 ConstantEvolutionLoopExitValue.erase(&PN); 8009 } 8010 8011 // Re-lookup the insert position, since the call to 8012 // computeBackedgeTakenCount above could result in a 8013 // recusive call to getBackedgeTakenInfo (on a different 8014 // loop), which would invalidate the iterator computed 8015 // earlier. 8016 return BackedgeTakenCounts.find(L)->second = std::move(Result); 8017 } 8018 8019 void ScalarEvolution::forgetAllLoops() { 8020 // This method is intended to forget all info about loops. It should 8021 // invalidate caches as if the following happened: 8022 // - The trip counts of all loops have changed arbitrarily 8023 // - Every llvm::Value has been updated in place to produce a different 8024 // result. 8025 BackedgeTakenCounts.clear(); 8026 PredicatedBackedgeTakenCounts.clear(); 8027 BECountUsers.clear(); 8028 LoopPropertiesCache.clear(); 8029 ConstantEvolutionLoopExitValue.clear(); 8030 ValueExprMap.clear(); 8031 ValuesAtScopes.clear(); 8032 ValuesAtScopesUsers.clear(); 8033 LoopDispositions.clear(); 8034 BlockDispositions.clear(); 8035 UnsignedRanges.clear(); 8036 SignedRanges.clear(); 8037 ExprValueMap.clear(); 8038 HasRecMap.clear(); 8039 MinTrailingZerosCache.clear(); 8040 PredicatedSCEVRewrites.clear(); 8041 } 8042 8043 void ScalarEvolution::forgetLoop(const Loop *L) { 8044 SmallVector<const Loop *, 16> LoopWorklist(1, L); 8045 SmallVector<Instruction *, 32> Worklist; 8046 SmallPtrSet<Instruction *, 16> Visited; 8047 SmallVector<const SCEV *, 16> ToForget; 8048 8049 // Iterate over all the loops and sub-loops to drop SCEV information. 8050 while (!LoopWorklist.empty()) { 8051 auto *CurrL = LoopWorklist.pop_back_val(); 8052 8053 // Drop any stored trip count value. 8054 forgetBackedgeTakenCounts(CurrL, /* Predicated */ false); 8055 forgetBackedgeTakenCounts(CurrL, /* Predicated */ true); 8056 8057 // Drop information about predicated SCEV rewrites for this loop. 8058 for (auto I = PredicatedSCEVRewrites.begin(); 8059 I != PredicatedSCEVRewrites.end();) { 8060 std::pair<const SCEV *, const Loop *> Entry = I->first; 8061 if (Entry.second == CurrL) 8062 PredicatedSCEVRewrites.erase(I++); 8063 else 8064 ++I; 8065 } 8066 8067 auto LoopUsersItr = LoopUsers.find(CurrL); 8068 if (LoopUsersItr != LoopUsers.end()) { 8069 ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(), 8070 LoopUsersItr->second.end()); 8071 LoopUsers.erase(LoopUsersItr); 8072 } 8073 8074 // Drop information about expressions based on loop-header PHIs. 8075 PushLoopPHIs(CurrL, Worklist, Visited); 8076 8077 while (!Worklist.empty()) { 8078 Instruction *I = Worklist.pop_back_val(); 8079 8080 ValueExprMapType::iterator It = 8081 ValueExprMap.find_as(static_cast<Value *>(I)); 8082 if (It != ValueExprMap.end()) { 8083 eraseValueFromMap(It->first); 8084 ToForget.push_back(It->second); 8085 if (PHINode *PN = dyn_cast<PHINode>(I)) 8086 ConstantEvolutionLoopExitValue.erase(PN); 8087 } 8088 8089 PushDefUseChildren(I, Worklist, Visited); 8090 } 8091 8092 LoopPropertiesCache.erase(CurrL); 8093 // Forget all contained loops too, to avoid dangling entries in the 8094 // ValuesAtScopes map. 8095 LoopWorklist.append(CurrL->begin(), CurrL->end()); 8096 } 8097 forgetMemoizedResults(ToForget); 8098 } 8099 8100 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 8101 while (Loop *Parent = L->getParentLoop()) 8102 L = Parent; 8103 forgetLoop(L); 8104 } 8105 8106 void ScalarEvolution::forgetValue(Value *V) { 8107 Instruction *I = dyn_cast<Instruction>(V); 8108 if (!I) return; 8109 8110 // Drop information about expressions based on loop-header PHIs. 8111 SmallVector<Instruction *, 16> Worklist; 8112 SmallPtrSet<Instruction *, 8> Visited; 8113 SmallVector<const SCEV *, 8> ToForget; 8114 Worklist.push_back(I); 8115 Visited.insert(I); 8116 8117 while (!Worklist.empty()) { 8118 I = Worklist.pop_back_val(); 8119 ValueExprMapType::iterator It = 8120 ValueExprMap.find_as(static_cast<Value *>(I)); 8121 if (It != ValueExprMap.end()) { 8122 eraseValueFromMap(It->first); 8123 ToForget.push_back(It->second); 8124 if (PHINode *PN = dyn_cast<PHINode>(I)) 8125 ConstantEvolutionLoopExitValue.erase(PN); 8126 } 8127 8128 PushDefUseChildren(I, Worklist, Visited); 8129 } 8130 forgetMemoizedResults(ToForget); 8131 } 8132 8133 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 8134 LoopDispositions.clear(); 8135 } 8136 8137 /// Get the exact loop backedge taken count considering all loop exits. A 8138 /// computable result can only be returned for loops with all exiting blocks 8139 /// dominating the latch. howFarToZero assumes that the limit of each loop test 8140 /// is never skipped. This is a valid assumption as long as the loop exits via 8141 /// that test. For precise results, it is the caller's responsibility to specify 8142 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 8143 const SCEV * 8144 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 8145 SmallVector<const SCEVPredicate *, 4> *Preds) const { 8146 // If any exits were not computable, the loop is not computable. 8147 if (!isComplete() || ExitNotTaken.empty()) 8148 return SE->getCouldNotCompute(); 8149 8150 const BasicBlock *Latch = L->getLoopLatch(); 8151 // All exiting blocks we have collected must dominate the only backedge. 8152 if (!Latch) 8153 return SE->getCouldNotCompute(); 8154 8155 // All exiting blocks we have gathered dominate loop's latch, so exact trip 8156 // count is simply a minimum out of all these calculated exit counts. 8157 SmallVector<const SCEV *, 2> Ops; 8158 for (auto &ENT : ExitNotTaken) { 8159 const SCEV *BECount = ENT.ExactNotTaken; 8160 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 8161 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 8162 "We should only have known counts for exiting blocks that dominate " 8163 "latch!"); 8164 8165 Ops.push_back(BECount); 8166 8167 if (Preds) 8168 for (auto *P : ENT.Predicates) 8169 Preds->push_back(P); 8170 8171 assert((Preds || ENT.hasAlwaysTruePredicate()) && 8172 "Predicate should be always true!"); 8173 } 8174 8175 return SE->getUMinFromMismatchedTypes(Ops); 8176 } 8177 8178 /// Get the exact not taken count for this loop exit. 8179 const SCEV * 8180 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 8181 ScalarEvolution *SE) const { 8182 for (auto &ENT : ExitNotTaken) 8183 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 8184 return ENT.ExactNotTaken; 8185 8186 return SE->getCouldNotCompute(); 8187 } 8188 8189 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 8190 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 8191 for (auto &ENT : ExitNotTaken) 8192 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 8193 return ENT.MaxNotTaken; 8194 8195 return SE->getCouldNotCompute(); 8196 } 8197 8198 /// getConstantMax - Get the constant max backedge taken count for the loop. 8199 const SCEV * 8200 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 8201 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 8202 return !ENT.hasAlwaysTruePredicate(); 8203 }; 8204 8205 if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue)) 8206 return SE->getCouldNotCompute(); 8207 8208 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 8209 isa<SCEVConstant>(getConstantMax())) && 8210 "No point in having a non-constant max backedge taken count!"); 8211 return getConstantMax(); 8212 } 8213 8214 const SCEV * 8215 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 8216 ScalarEvolution *SE) { 8217 if (!SymbolicMax) 8218 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 8219 return SymbolicMax; 8220 } 8221 8222 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 8223 ScalarEvolution *SE) const { 8224 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 8225 return !ENT.hasAlwaysTruePredicate(); 8226 }; 8227 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 8228 } 8229 8230 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 8231 : ExitLimit(E, E, false, None) { 8232 } 8233 8234 ScalarEvolution::ExitLimit::ExitLimit( 8235 const SCEV *E, const SCEV *M, bool MaxOrZero, 8236 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 8237 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 8238 // If we prove the max count is zero, so is the symbolic bound. This happens 8239 // in practice due to differences in a) how context sensitive we've chosen 8240 // to be and b) how we reason about bounds impied by UB. 8241 if (MaxNotTaken->isZero()) 8242 ExactNotTaken = MaxNotTaken; 8243 8244 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 8245 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 8246 "Exact is not allowed to be less precise than Max"); 8247 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 8248 isa<SCEVConstant>(MaxNotTaken)) && 8249 "No point in having a non-constant max backedge taken count!"); 8250 for (auto *PredSet : PredSetList) 8251 for (auto *P : *PredSet) 8252 addPredicate(P); 8253 assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) && 8254 "Backedge count should be int"); 8255 assert((isa<SCEVCouldNotCompute>(M) || !M->getType()->isPointerTy()) && 8256 "Max backedge count should be int"); 8257 } 8258 8259 ScalarEvolution::ExitLimit::ExitLimit( 8260 const SCEV *E, const SCEV *M, bool MaxOrZero, 8261 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 8262 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 8263 } 8264 8265 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 8266 bool MaxOrZero) 8267 : ExitLimit(E, M, MaxOrZero, None) { 8268 } 8269 8270 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 8271 /// computable exit into a persistent ExitNotTakenInfo array. 8272 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 8273 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 8274 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 8275 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 8276 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8277 8278 ExitNotTaken.reserve(ExitCounts.size()); 8279 std::transform( 8280 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 8281 [&](const EdgeExitInfo &EEI) { 8282 BasicBlock *ExitBB = EEI.first; 8283 const ExitLimit &EL = EEI.second; 8284 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 8285 EL.Predicates); 8286 }); 8287 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 8288 isa<SCEVConstant>(ConstantMax)) && 8289 "No point in having a non-constant max backedge taken count!"); 8290 } 8291 8292 /// Compute the number of times the backedge of the specified loop will execute. 8293 ScalarEvolution::BackedgeTakenInfo 8294 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 8295 bool AllowPredicates) { 8296 SmallVector<BasicBlock *, 8> ExitingBlocks; 8297 L->getExitingBlocks(ExitingBlocks); 8298 8299 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 8300 8301 SmallVector<EdgeExitInfo, 4> ExitCounts; 8302 bool CouldComputeBECount = true; 8303 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 8304 const SCEV *MustExitMaxBECount = nullptr; 8305 const SCEV *MayExitMaxBECount = nullptr; 8306 bool MustExitMaxOrZero = false; 8307 8308 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 8309 // and compute maxBECount. 8310 // Do a union of all the predicates here. 8311 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 8312 BasicBlock *ExitBB = ExitingBlocks[i]; 8313 8314 // We canonicalize untaken exits to br (constant), ignore them so that 8315 // proving an exit untaken doesn't negatively impact our ability to reason 8316 // about the loop as whole. 8317 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 8318 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 8319 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8320 if (ExitIfTrue == CI->isZero()) 8321 continue; 8322 } 8323 8324 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 8325 8326 assert((AllowPredicates || EL.Predicates.empty()) && 8327 "Predicated exit limit when predicates are not allowed!"); 8328 8329 // 1. For each exit that can be computed, add an entry to ExitCounts. 8330 // CouldComputeBECount is true only if all exits can be computed. 8331 if (EL.ExactNotTaken == getCouldNotCompute()) 8332 // We couldn't compute an exact value for this exit, so 8333 // we won't be able to compute an exact value for the loop. 8334 CouldComputeBECount = false; 8335 else 8336 ExitCounts.emplace_back(ExitBB, EL); 8337 8338 // 2. Derive the loop's MaxBECount from each exit's max number of 8339 // non-exiting iterations. Partition the loop exits into two kinds: 8340 // LoopMustExits and LoopMayExits. 8341 // 8342 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 8343 // is a LoopMayExit. If any computable LoopMustExit is found, then 8344 // MaxBECount is the minimum EL.MaxNotTaken of computable 8345 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 8346 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 8347 // computable EL.MaxNotTaken. 8348 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 8349 DT.dominates(ExitBB, Latch)) { 8350 if (!MustExitMaxBECount) { 8351 MustExitMaxBECount = EL.MaxNotTaken; 8352 MustExitMaxOrZero = EL.MaxOrZero; 8353 } else { 8354 MustExitMaxBECount = 8355 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 8356 } 8357 } else if (MayExitMaxBECount != getCouldNotCompute()) { 8358 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 8359 MayExitMaxBECount = EL.MaxNotTaken; 8360 else { 8361 MayExitMaxBECount = 8362 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 8363 } 8364 } 8365 } 8366 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 8367 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 8368 // The loop backedge will be taken the maximum or zero times if there's 8369 // a single exit that must be taken the maximum or zero times. 8370 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 8371 8372 // Remember which SCEVs are used in exit limits for invalidation purposes. 8373 // We only care about non-constant SCEVs here, so we can ignore EL.MaxNotTaken 8374 // and MaxBECount, which must be SCEVConstant. 8375 for (const auto &Pair : ExitCounts) 8376 if (!isa<SCEVConstant>(Pair.second.ExactNotTaken)) 8377 BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates}); 8378 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 8379 MaxBECount, MaxOrZero); 8380 } 8381 8382 ScalarEvolution::ExitLimit 8383 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 8384 bool AllowPredicates) { 8385 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 8386 // If our exiting block does not dominate the latch, then its connection with 8387 // loop's exit limit may be far from trivial. 8388 const BasicBlock *Latch = L->getLoopLatch(); 8389 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 8390 return getCouldNotCompute(); 8391 8392 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 8393 Instruction *Term = ExitingBlock->getTerminator(); 8394 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 8395 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 8396 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 8397 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 8398 "It should have one successor in loop and one exit block!"); 8399 // Proceed to the next level to examine the exit condition expression. 8400 return computeExitLimitFromCond( 8401 L, BI->getCondition(), ExitIfTrue, 8402 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 8403 } 8404 8405 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 8406 // For switch, make sure that there is a single exit from the loop. 8407 BasicBlock *Exit = nullptr; 8408 for (auto *SBB : successors(ExitingBlock)) 8409 if (!L->contains(SBB)) { 8410 if (Exit) // Multiple exit successors. 8411 return getCouldNotCompute(); 8412 Exit = SBB; 8413 } 8414 assert(Exit && "Exiting block must have at least one exit"); 8415 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 8416 /*ControlsExit=*/IsOnlyExit); 8417 } 8418 8419 return getCouldNotCompute(); 8420 } 8421 8422 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 8423 const Loop *L, Value *ExitCond, bool ExitIfTrue, 8424 bool ControlsExit, bool AllowPredicates) { 8425 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 8426 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 8427 ControlsExit, AllowPredicates); 8428 } 8429 8430 Optional<ScalarEvolution::ExitLimit> 8431 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 8432 bool ExitIfTrue, bool ControlsExit, 8433 bool AllowPredicates) { 8434 (void)this->L; 8435 (void)this->ExitIfTrue; 8436 (void)this->AllowPredicates; 8437 8438 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8439 this->AllowPredicates == AllowPredicates && 8440 "Variance in assumed invariant key components!"); 8441 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 8442 if (Itr == TripCountMap.end()) 8443 return None; 8444 return Itr->second; 8445 } 8446 8447 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 8448 bool ExitIfTrue, 8449 bool ControlsExit, 8450 bool AllowPredicates, 8451 const ExitLimit &EL) { 8452 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 8453 this->AllowPredicates == AllowPredicates && 8454 "Variance in assumed invariant key components!"); 8455 8456 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 8457 assert(InsertResult.second && "Expected successful insertion!"); 8458 (void)InsertResult; 8459 (void)ExitIfTrue; 8460 } 8461 8462 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 8463 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8464 bool ControlsExit, bool AllowPredicates) { 8465 8466 if (auto MaybeEL = 8467 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8468 return *MaybeEL; 8469 8470 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 8471 ControlsExit, AllowPredicates); 8472 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 8473 return EL; 8474 } 8475 8476 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 8477 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8478 bool ControlsExit, bool AllowPredicates) { 8479 // Handle BinOp conditions (And, Or). 8480 if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp( 8481 Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 8482 return *LimitFromBinOp; 8483 8484 // With an icmp, it may be feasible to compute an exact backedge-taken count. 8485 // Proceed to the next level to examine the icmp. 8486 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 8487 ExitLimit EL = 8488 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 8489 if (EL.hasFullInfo() || !AllowPredicates) 8490 return EL; 8491 8492 // Try again, but use SCEV predicates this time. 8493 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 8494 /*AllowPredicates=*/true); 8495 } 8496 8497 // Check for a constant condition. These are normally stripped out by 8498 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 8499 // preserve the CFG and is temporarily leaving constant conditions 8500 // in place. 8501 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 8502 if (ExitIfTrue == !CI->getZExtValue()) 8503 // The backedge is always taken. 8504 return getCouldNotCompute(); 8505 else 8506 // The backedge is never taken. 8507 return getZero(CI->getType()); 8508 } 8509 8510 // If we're exiting based on the overflow flag of an x.with.overflow intrinsic 8511 // with a constant step, we can form an equivalent icmp predicate and figure 8512 // out how many iterations will be taken before we exit. 8513 const WithOverflowInst *WO; 8514 const APInt *C; 8515 if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) && 8516 match(WO->getRHS(), m_APInt(C))) { 8517 ConstantRange NWR = 8518 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C, 8519 WO->getNoWrapKind()); 8520 CmpInst::Predicate Pred; 8521 APInt NewRHSC, Offset; 8522 NWR.getEquivalentICmp(Pred, NewRHSC, Offset); 8523 if (!ExitIfTrue) 8524 Pred = ICmpInst::getInversePredicate(Pred); 8525 auto *LHS = getSCEV(WO->getLHS()); 8526 if (Offset != 0) 8527 LHS = getAddExpr(LHS, getConstant(Offset)); 8528 auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC), 8529 ControlsExit, AllowPredicates); 8530 if (EL.hasAnyInfo()) return EL; 8531 } 8532 8533 // If it's not an integer or pointer comparison then compute it the hard way. 8534 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8535 } 8536 8537 Optional<ScalarEvolution::ExitLimit> 8538 ScalarEvolution::computeExitLimitFromCondFromBinOp( 8539 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 8540 bool ControlsExit, bool AllowPredicates) { 8541 // Check if the controlling expression for this loop is an And or Or. 8542 Value *Op0, *Op1; 8543 bool IsAnd = false; 8544 if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) 8545 IsAnd = true; 8546 else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) 8547 IsAnd = false; 8548 else 8549 return None; 8550 8551 // EitherMayExit is true in these two cases: 8552 // br (and Op0 Op1), loop, exit 8553 // br (or Op0 Op1), exit, loop 8554 bool EitherMayExit = IsAnd ^ ExitIfTrue; 8555 ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue, 8556 ControlsExit && !EitherMayExit, 8557 AllowPredicates); 8558 ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue, 8559 ControlsExit && !EitherMayExit, 8560 AllowPredicates); 8561 8562 // Be robust against unsimplified IR for the form "op i1 X, NeutralElement" 8563 const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd); 8564 if (isa<ConstantInt>(Op1)) 8565 return Op1 == NeutralElement ? EL0 : EL1; 8566 if (isa<ConstantInt>(Op0)) 8567 return Op0 == NeutralElement ? EL1 : EL0; 8568 8569 const SCEV *BECount = getCouldNotCompute(); 8570 const SCEV *MaxBECount = getCouldNotCompute(); 8571 if (EitherMayExit) { 8572 // Both conditions must be same for the loop to continue executing. 8573 // Choose the less conservative count. 8574 if (EL0.ExactNotTaken != getCouldNotCompute() && 8575 EL1.ExactNotTaken != getCouldNotCompute()) { 8576 BECount = getUMinFromMismatchedTypes( 8577 EL0.ExactNotTaken, EL1.ExactNotTaken, 8578 /*Sequential=*/!isa<BinaryOperator>(ExitCond)); 8579 8580 // If EL0.ExactNotTaken was zero and ExitCond was a short-circuit form, 8581 // it should have been simplified to zero (see the condition (3) above) 8582 assert(!isa<BinaryOperator>(ExitCond) || !EL0.ExactNotTaken->isZero() || 8583 BECount->isZero()); 8584 } 8585 if (EL0.MaxNotTaken == getCouldNotCompute()) 8586 MaxBECount = EL1.MaxNotTaken; 8587 else if (EL1.MaxNotTaken == getCouldNotCompute()) 8588 MaxBECount = EL0.MaxNotTaken; 8589 else 8590 MaxBECount = getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 8591 } else { 8592 // Both conditions must be same at the same time for the loop to exit. 8593 // For now, be conservative. 8594 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 8595 BECount = EL0.ExactNotTaken; 8596 } 8597 8598 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 8599 // to be more aggressive when computing BECount than when computing 8600 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 8601 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 8602 // to not. 8603 if (isa<SCEVCouldNotCompute>(MaxBECount) && 8604 !isa<SCEVCouldNotCompute>(BECount)) 8605 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 8606 8607 return ExitLimit(BECount, MaxBECount, false, 8608 { &EL0.Predicates, &EL1.Predicates }); 8609 } 8610 8611 ScalarEvolution::ExitLimit 8612 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8613 ICmpInst *ExitCond, 8614 bool ExitIfTrue, 8615 bool ControlsExit, 8616 bool AllowPredicates) { 8617 // If the condition was exit on true, convert the condition to exit on false 8618 ICmpInst::Predicate Pred; 8619 if (!ExitIfTrue) 8620 Pred = ExitCond->getPredicate(); 8621 else 8622 Pred = ExitCond->getInversePredicate(); 8623 const ICmpInst::Predicate OriginalPred = Pred; 8624 8625 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 8626 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 8627 8628 ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit, 8629 AllowPredicates); 8630 if (EL.hasAnyInfo()) return EL; 8631 8632 auto *ExhaustiveCount = 8633 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 8634 8635 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 8636 return ExhaustiveCount; 8637 8638 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 8639 ExitCond->getOperand(1), L, OriginalPred); 8640 } 8641 ScalarEvolution::ExitLimit 8642 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 8643 ICmpInst::Predicate Pred, 8644 const SCEV *LHS, const SCEV *RHS, 8645 bool ControlsExit, 8646 bool AllowPredicates) { 8647 8648 // Try to evaluate any dependencies out of the loop. 8649 LHS = getSCEVAtScope(LHS, L); 8650 RHS = getSCEVAtScope(RHS, L); 8651 8652 // At this point, we would like to compute how many iterations of the 8653 // loop the predicate will return true for these inputs. 8654 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 8655 // If there is a loop-invariant, force it into the RHS. 8656 std::swap(LHS, RHS); 8657 Pred = ICmpInst::getSwappedPredicate(Pred); 8658 } 8659 8660 bool ControllingFiniteLoop = 8661 ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L); 8662 // Simplify the operands before analyzing them. 8663 (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0, 8664 ControllingFiniteLoop); 8665 8666 // If we have a comparison of a chrec against a constant, try to use value 8667 // ranges to answer this query. 8668 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 8669 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 8670 if (AddRec->getLoop() == L) { 8671 // Form the constant range. 8672 ConstantRange CompRange = 8673 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 8674 8675 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 8676 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 8677 } 8678 8679 // If this loop must exit based on this condition (or execute undefined 8680 // behaviour), and we can prove the test sequence produced must repeat 8681 // the same values on self-wrap of the IV, then we can infer that IV 8682 // doesn't self wrap because if it did, we'd have an infinite (undefined) 8683 // loop. 8684 if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) { 8685 // TODO: We can peel off any functions which are invertible *in L*. Loop 8686 // invariant terms are effectively constants for our purposes here. 8687 auto *InnerLHS = LHS; 8688 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) 8689 InnerLHS = ZExt->getOperand(); 8690 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) { 8691 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 8692 if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() && 8693 StrideC && StrideC->getAPInt().isPowerOf2()) { 8694 auto Flags = AR->getNoWrapFlags(); 8695 Flags = setFlags(Flags, SCEV::FlagNW); 8696 SmallVector<const SCEV*> Operands{AR->operands()}; 8697 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 8698 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 8699 } 8700 } 8701 } 8702 8703 switch (Pred) { 8704 case ICmpInst::ICMP_NE: { // while (X != Y) 8705 // Convert to: while (X-Y != 0) 8706 if (LHS->getType()->isPointerTy()) { 8707 LHS = getLosslessPtrToIntExpr(LHS); 8708 if (isa<SCEVCouldNotCompute>(LHS)) 8709 return LHS; 8710 } 8711 if (RHS->getType()->isPointerTy()) { 8712 RHS = getLosslessPtrToIntExpr(RHS); 8713 if (isa<SCEVCouldNotCompute>(RHS)) 8714 return RHS; 8715 } 8716 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 8717 AllowPredicates); 8718 if (EL.hasAnyInfo()) return EL; 8719 break; 8720 } 8721 case ICmpInst::ICMP_EQ: { // while (X == Y) 8722 // Convert to: while (X-Y == 0) 8723 if (LHS->getType()->isPointerTy()) { 8724 LHS = getLosslessPtrToIntExpr(LHS); 8725 if (isa<SCEVCouldNotCompute>(LHS)) 8726 return LHS; 8727 } 8728 if (RHS->getType()->isPointerTy()) { 8729 RHS = getLosslessPtrToIntExpr(RHS); 8730 if (isa<SCEVCouldNotCompute>(RHS)) 8731 return RHS; 8732 } 8733 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 8734 if (EL.hasAnyInfo()) return EL; 8735 break; 8736 } 8737 case ICmpInst::ICMP_SLT: 8738 case ICmpInst::ICMP_ULT: { // while (X < Y) 8739 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 8740 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 8741 AllowPredicates); 8742 if (EL.hasAnyInfo()) return EL; 8743 break; 8744 } 8745 case ICmpInst::ICMP_SGT: 8746 case ICmpInst::ICMP_UGT: { // while (X > Y) 8747 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 8748 ExitLimit EL = 8749 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 8750 AllowPredicates); 8751 if (EL.hasAnyInfo()) return EL; 8752 break; 8753 } 8754 default: 8755 break; 8756 } 8757 8758 return getCouldNotCompute(); 8759 } 8760 8761 ScalarEvolution::ExitLimit 8762 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 8763 SwitchInst *Switch, 8764 BasicBlock *ExitingBlock, 8765 bool ControlsExit) { 8766 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 8767 8768 // Give up if the exit is the default dest of a switch. 8769 if (Switch->getDefaultDest() == ExitingBlock) 8770 return getCouldNotCompute(); 8771 8772 assert(L->contains(Switch->getDefaultDest()) && 8773 "Default case must not exit the loop!"); 8774 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 8775 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 8776 8777 // while (X != Y) --> while (X-Y != 0) 8778 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 8779 if (EL.hasAnyInfo()) 8780 return EL; 8781 8782 return getCouldNotCompute(); 8783 } 8784 8785 static ConstantInt * 8786 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 8787 ScalarEvolution &SE) { 8788 const SCEV *InVal = SE.getConstant(C); 8789 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 8790 assert(isa<SCEVConstant>(Val) && 8791 "Evaluation of SCEV at constant didn't fold correctly?"); 8792 return cast<SCEVConstant>(Val)->getValue(); 8793 } 8794 8795 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 8796 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 8797 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 8798 if (!RHS) 8799 return getCouldNotCompute(); 8800 8801 const BasicBlock *Latch = L->getLoopLatch(); 8802 if (!Latch) 8803 return getCouldNotCompute(); 8804 8805 const BasicBlock *Predecessor = L->getLoopPredecessor(); 8806 if (!Predecessor) 8807 return getCouldNotCompute(); 8808 8809 // Return true if V is of the form "LHS `shift_op` <positive constant>". 8810 // Return LHS in OutLHS and shift_opt in OutOpCode. 8811 auto MatchPositiveShift = 8812 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 8813 8814 using namespace PatternMatch; 8815 8816 ConstantInt *ShiftAmt; 8817 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8818 OutOpCode = Instruction::LShr; 8819 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8820 OutOpCode = Instruction::AShr; 8821 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 8822 OutOpCode = Instruction::Shl; 8823 else 8824 return false; 8825 8826 return ShiftAmt->getValue().isStrictlyPositive(); 8827 }; 8828 8829 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 8830 // 8831 // loop: 8832 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 8833 // %iv.shifted = lshr i32 %iv, <positive constant> 8834 // 8835 // Return true on a successful match. Return the corresponding PHI node (%iv 8836 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 8837 auto MatchShiftRecurrence = 8838 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 8839 Optional<Instruction::BinaryOps> PostShiftOpCode; 8840 8841 { 8842 Instruction::BinaryOps OpC; 8843 Value *V; 8844 8845 // If we encounter a shift instruction, "peel off" the shift operation, 8846 // and remember that we did so. Later when we inspect %iv's backedge 8847 // value, we will make sure that the backedge value uses the same 8848 // operation. 8849 // 8850 // Note: the peeled shift operation does not have to be the same 8851 // instruction as the one feeding into the PHI's backedge value. We only 8852 // really care about it being the same *kind* of shift instruction -- 8853 // that's all that is required for our later inferences to hold. 8854 if (MatchPositiveShift(LHS, V, OpC)) { 8855 PostShiftOpCode = OpC; 8856 LHS = V; 8857 } 8858 } 8859 8860 PNOut = dyn_cast<PHINode>(LHS); 8861 if (!PNOut || PNOut->getParent() != L->getHeader()) 8862 return false; 8863 8864 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 8865 Value *OpLHS; 8866 8867 return 8868 // The backedge value for the PHI node must be a shift by a positive 8869 // amount 8870 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 8871 8872 // of the PHI node itself 8873 OpLHS == PNOut && 8874 8875 // and the kind of shift should be match the kind of shift we peeled 8876 // off, if any. 8877 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 8878 }; 8879 8880 PHINode *PN; 8881 Instruction::BinaryOps OpCode; 8882 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 8883 return getCouldNotCompute(); 8884 8885 const DataLayout &DL = getDataLayout(); 8886 8887 // The key rationale for this optimization is that for some kinds of shift 8888 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 8889 // within a finite number of iterations. If the condition guarding the 8890 // backedge (in the sense that the backedge is taken if the condition is true) 8891 // is false for the value the shift recurrence stabilizes to, then we know 8892 // that the backedge is taken only a finite number of times. 8893 8894 ConstantInt *StableValue = nullptr; 8895 switch (OpCode) { 8896 default: 8897 llvm_unreachable("Impossible case!"); 8898 8899 case Instruction::AShr: { 8900 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 8901 // bitwidth(K) iterations. 8902 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 8903 KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC, 8904 Predecessor->getTerminator(), &DT); 8905 auto *Ty = cast<IntegerType>(RHS->getType()); 8906 if (Known.isNonNegative()) 8907 StableValue = ConstantInt::get(Ty, 0); 8908 else if (Known.isNegative()) 8909 StableValue = ConstantInt::get(Ty, -1, true); 8910 else 8911 return getCouldNotCompute(); 8912 8913 break; 8914 } 8915 case Instruction::LShr: 8916 case Instruction::Shl: 8917 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 8918 // stabilize to 0 in at most bitwidth(K) iterations. 8919 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 8920 break; 8921 } 8922 8923 auto *Result = 8924 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 8925 assert(Result->getType()->isIntegerTy(1) && 8926 "Otherwise cannot be an operand to a branch instruction"); 8927 8928 if (Result->isZeroValue()) { 8929 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 8930 const SCEV *UpperBound = 8931 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 8932 return ExitLimit(getCouldNotCompute(), UpperBound, false); 8933 } 8934 8935 return getCouldNotCompute(); 8936 } 8937 8938 /// Return true if we can constant fold an instruction of the specified type, 8939 /// assuming that all operands were constants. 8940 static bool CanConstantFold(const Instruction *I) { 8941 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 8942 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8943 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 8944 return true; 8945 8946 if (const CallInst *CI = dyn_cast<CallInst>(I)) 8947 if (const Function *F = CI->getCalledFunction()) 8948 return canConstantFoldCallTo(CI, F); 8949 return false; 8950 } 8951 8952 /// Determine whether this instruction can constant evolve within this loop 8953 /// assuming its operands can all constant evolve. 8954 static bool canConstantEvolve(Instruction *I, const Loop *L) { 8955 // An instruction outside of the loop can't be derived from a loop PHI. 8956 if (!L->contains(I)) return false; 8957 8958 if (isa<PHINode>(I)) { 8959 // We don't currently keep track of the control flow needed to evaluate 8960 // PHIs, so we cannot handle PHIs inside of loops. 8961 return L->getHeader() == I->getParent(); 8962 } 8963 8964 // If we won't be able to constant fold this expression even if the operands 8965 // are constants, bail early. 8966 return CanConstantFold(I); 8967 } 8968 8969 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 8970 /// recursing through each instruction operand until reaching a loop header phi. 8971 static PHINode * 8972 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 8973 DenseMap<Instruction *, PHINode *> &PHIMap, 8974 unsigned Depth) { 8975 if (Depth > MaxConstantEvolvingDepth) 8976 return nullptr; 8977 8978 // Otherwise, we can evaluate this instruction if all of its operands are 8979 // constant or derived from a PHI node themselves. 8980 PHINode *PHI = nullptr; 8981 for (Value *Op : UseInst->operands()) { 8982 if (isa<Constant>(Op)) continue; 8983 8984 Instruction *OpInst = dyn_cast<Instruction>(Op); 8985 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 8986 8987 PHINode *P = dyn_cast<PHINode>(OpInst); 8988 if (!P) 8989 // If this operand is already visited, reuse the prior result. 8990 // We may have P != PHI if this is the deepest point at which the 8991 // inconsistent paths meet. 8992 P = PHIMap.lookup(OpInst); 8993 if (!P) { 8994 // Recurse and memoize the results, whether a phi is found or not. 8995 // This recursive call invalidates pointers into PHIMap. 8996 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 8997 PHIMap[OpInst] = P; 8998 } 8999 if (!P) 9000 return nullptr; // Not evolving from PHI 9001 if (PHI && PHI != P) 9002 return nullptr; // Evolving from multiple different PHIs. 9003 PHI = P; 9004 } 9005 // This is a expression evolving from a constant PHI! 9006 return PHI; 9007 } 9008 9009 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 9010 /// in the loop that V is derived from. We allow arbitrary operations along the 9011 /// way, but the operands of an operation must either be constants or a value 9012 /// derived from a constant PHI. If this expression does not fit with these 9013 /// constraints, return null. 9014 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 9015 Instruction *I = dyn_cast<Instruction>(V); 9016 if (!I || !canConstantEvolve(I, L)) return nullptr; 9017 9018 if (PHINode *PN = dyn_cast<PHINode>(I)) 9019 return PN; 9020 9021 // Record non-constant instructions contained by the loop. 9022 DenseMap<Instruction *, PHINode *> PHIMap; 9023 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 9024 } 9025 9026 /// EvaluateExpression - Given an expression that passes the 9027 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 9028 /// in the loop has the value PHIVal. If we can't fold this expression for some 9029 /// reason, return null. 9030 static Constant *EvaluateExpression(Value *V, const Loop *L, 9031 DenseMap<Instruction *, Constant *> &Vals, 9032 const DataLayout &DL, 9033 const TargetLibraryInfo *TLI) { 9034 // Convenient constant check, but redundant for recursive calls. 9035 if (Constant *C = dyn_cast<Constant>(V)) return C; 9036 Instruction *I = dyn_cast<Instruction>(V); 9037 if (!I) return nullptr; 9038 9039 if (Constant *C = Vals.lookup(I)) return C; 9040 9041 // An instruction inside the loop depends on a value outside the loop that we 9042 // weren't given a mapping for, or a value such as a call inside the loop. 9043 if (!canConstantEvolve(I, L)) return nullptr; 9044 9045 // An unmapped PHI can be due to a branch or another loop inside this loop, 9046 // or due to this not being the initial iteration through a loop where we 9047 // couldn't compute the evolution of this particular PHI last time. 9048 if (isa<PHINode>(I)) return nullptr; 9049 9050 std::vector<Constant*> Operands(I->getNumOperands()); 9051 9052 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 9053 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 9054 if (!Operand) { 9055 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 9056 if (!Operands[i]) return nullptr; 9057 continue; 9058 } 9059 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 9060 Vals[Operand] = C; 9061 if (!C) return nullptr; 9062 Operands[i] = C; 9063 } 9064 9065 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 9066 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 9067 Operands[1], DL, TLI); 9068 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 9069 if (!LI->isVolatile()) 9070 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 9071 } 9072 return ConstantFoldInstOperands(I, Operands, DL, TLI); 9073 } 9074 9075 9076 // If every incoming value to PN except the one for BB is a specific Constant, 9077 // return that, else return nullptr. 9078 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 9079 Constant *IncomingVal = nullptr; 9080 9081 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 9082 if (PN->getIncomingBlock(i) == BB) 9083 continue; 9084 9085 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 9086 if (!CurrentVal) 9087 return nullptr; 9088 9089 if (IncomingVal != CurrentVal) { 9090 if (IncomingVal) 9091 return nullptr; 9092 IncomingVal = CurrentVal; 9093 } 9094 } 9095 9096 return IncomingVal; 9097 } 9098 9099 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 9100 /// in the header of its containing loop, we know the loop executes a 9101 /// constant number of times, and the PHI node is just a recurrence 9102 /// involving constants, fold it. 9103 Constant * 9104 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 9105 const APInt &BEs, 9106 const Loop *L) { 9107 auto I = ConstantEvolutionLoopExitValue.find(PN); 9108 if (I != ConstantEvolutionLoopExitValue.end()) 9109 return I->second; 9110 9111 if (BEs.ugt(MaxBruteForceIterations)) 9112 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 9113 9114 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 9115 9116 DenseMap<Instruction *, Constant *> CurrentIterVals; 9117 BasicBlock *Header = L->getHeader(); 9118 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 9119 9120 BasicBlock *Latch = L->getLoopLatch(); 9121 if (!Latch) 9122 return nullptr; 9123 9124 for (PHINode &PHI : Header->phis()) { 9125 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 9126 CurrentIterVals[&PHI] = StartCST; 9127 } 9128 if (!CurrentIterVals.count(PN)) 9129 return RetVal = nullptr; 9130 9131 Value *BEValue = PN->getIncomingValueForBlock(Latch); 9132 9133 // Execute the loop symbolically to determine the exit value. 9134 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 9135 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 9136 9137 unsigned NumIterations = BEs.getZExtValue(); // must be in range 9138 unsigned IterationNum = 0; 9139 const DataLayout &DL = getDataLayout(); 9140 for (; ; ++IterationNum) { 9141 if (IterationNum == NumIterations) 9142 return RetVal = CurrentIterVals[PN]; // Got exit value! 9143 9144 // Compute the value of the PHIs for the next iteration. 9145 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 9146 DenseMap<Instruction *, Constant *> NextIterVals; 9147 Constant *NextPHI = 9148 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9149 if (!NextPHI) 9150 return nullptr; // Couldn't evaluate! 9151 NextIterVals[PN] = NextPHI; 9152 9153 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 9154 9155 // Also evaluate the other PHI nodes. However, we don't get to stop if we 9156 // cease to be able to evaluate one of them or if they stop evolving, 9157 // because that doesn't necessarily prevent us from computing PN. 9158 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 9159 for (const auto &I : CurrentIterVals) { 9160 PHINode *PHI = dyn_cast<PHINode>(I.first); 9161 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 9162 PHIsToCompute.emplace_back(PHI, I.second); 9163 } 9164 // We use two distinct loops because EvaluateExpression may invalidate any 9165 // iterators into CurrentIterVals. 9166 for (const auto &I : PHIsToCompute) { 9167 PHINode *PHI = I.first; 9168 Constant *&NextPHI = NextIterVals[PHI]; 9169 if (!NextPHI) { // Not already computed. 9170 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 9171 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9172 } 9173 if (NextPHI != I.second) 9174 StoppedEvolving = false; 9175 } 9176 9177 // If all entries in CurrentIterVals == NextIterVals then we can stop 9178 // iterating, the loop can't continue to change. 9179 if (StoppedEvolving) 9180 return RetVal = CurrentIterVals[PN]; 9181 9182 CurrentIterVals.swap(NextIterVals); 9183 } 9184 } 9185 9186 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 9187 Value *Cond, 9188 bool ExitWhen) { 9189 PHINode *PN = getConstantEvolvingPHI(Cond, L); 9190 if (!PN) return getCouldNotCompute(); 9191 9192 // If the loop is canonicalized, the PHI will have exactly two entries. 9193 // That's the only form we support here. 9194 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 9195 9196 DenseMap<Instruction *, Constant *> CurrentIterVals; 9197 BasicBlock *Header = L->getHeader(); 9198 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 9199 9200 BasicBlock *Latch = L->getLoopLatch(); 9201 assert(Latch && "Should follow from NumIncomingValues == 2!"); 9202 9203 for (PHINode &PHI : Header->phis()) { 9204 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 9205 CurrentIterVals[&PHI] = StartCST; 9206 } 9207 if (!CurrentIterVals.count(PN)) 9208 return getCouldNotCompute(); 9209 9210 // Okay, we find a PHI node that defines the trip count of this loop. Execute 9211 // the loop symbolically to determine when the condition gets a value of 9212 // "ExitWhen". 9213 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 9214 const DataLayout &DL = getDataLayout(); 9215 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 9216 auto *CondVal = dyn_cast_or_null<ConstantInt>( 9217 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 9218 9219 // Couldn't symbolically evaluate. 9220 if (!CondVal) return getCouldNotCompute(); 9221 9222 if (CondVal->getValue() == uint64_t(ExitWhen)) { 9223 ++NumBruteForceTripCountsComputed; 9224 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 9225 } 9226 9227 // Update all the PHI nodes for the next iteration. 9228 DenseMap<Instruction *, Constant *> NextIterVals; 9229 9230 // Create a list of which PHIs we need to compute. We want to do this before 9231 // calling EvaluateExpression on them because that may invalidate iterators 9232 // into CurrentIterVals. 9233 SmallVector<PHINode *, 8> PHIsToCompute; 9234 for (const auto &I : CurrentIterVals) { 9235 PHINode *PHI = dyn_cast<PHINode>(I.first); 9236 if (!PHI || PHI->getParent() != Header) continue; 9237 PHIsToCompute.push_back(PHI); 9238 } 9239 for (PHINode *PHI : PHIsToCompute) { 9240 Constant *&NextPHI = NextIterVals[PHI]; 9241 if (NextPHI) continue; // Already computed! 9242 9243 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 9244 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 9245 } 9246 CurrentIterVals.swap(NextIterVals); 9247 } 9248 9249 // Too many iterations were needed to evaluate. 9250 return getCouldNotCompute(); 9251 } 9252 9253 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 9254 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 9255 ValuesAtScopes[V]; 9256 // Check to see if we've folded this expression at this loop before. 9257 for (auto &LS : Values) 9258 if (LS.first == L) 9259 return LS.second ? LS.second : V; 9260 9261 Values.emplace_back(L, nullptr); 9262 9263 // Otherwise compute it. 9264 const SCEV *C = computeSCEVAtScope(V, L); 9265 for (auto &LS : reverse(ValuesAtScopes[V])) 9266 if (LS.first == L) { 9267 LS.second = C; 9268 if (!isa<SCEVConstant>(C)) 9269 ValuesAtScopesUsers[C].push_back({L, V}); 9270 break; 9271 } 9272 return C; 9273 } 9274 9275 /// This builds up a Constant using the ConstantExpr interface. That way, we 9276 /// will return Constants for objects which aren't represented by a 9277 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 9278 /// Returns NULL if the SCEV isn't representable as a Constant. 9279 static Constant *BuildConstantFromSCEV(const SCEV *V) { 9280 switch (V->getSCEVType()) { 9281 case scCouldNotCompute: 9282 case scAddRecExpr: 9283 return nullptr; 9284 case scConstant: 9285 return cast<SCEVConstant>(V)->getValue(); 9286 case scUnknown: 9287 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 9288 case scSignExtend: { 9289 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 9290 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 9291 return ConstantExpr::getSExt(CastOp, SS->getType()); 9292 return nullptr; 9293 } 9294 case scZeroExtend: { 9295 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 9296 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 9297 return ConstantExpr::getZExt(CastOp, SZ->getType()); 9298 return nullptr; 9299 } 9300 case scPtrToInt: { 9301 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 9302 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 9303 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 9304 9305 return nullptr; 9306 } 9307 case scTruncate: { 9308 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 9309 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 9310 return ConstantExpr::getTrunc(CastOp, ST->getType()); 9311 return nullptr; 9312 } 9313 case scAddExpr: { 9314 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 9315 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 9316 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 9317 unsigned AS = PTy->getAddressSpace(); 9318 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9319 C = ConstantExpr::getBitCast(C, DestPtrTy); 9320 } 9321 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 9322 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 9323 if (!C2) 9324 return nullptr; 9325 9326 // First pointer! 9327 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 9328 unsigned AS = C2->getType()->getPointerAddressSpace(); 9329 std::swap(C, C2); 9330 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 9331 // The offsets have been converted to bytes. We can add bytes to an 9332 // i8* by GEP with the byte count in the first index. 9333 C = ConstantExpr::getBitCast(C, DestPtrTy); 9334 } 9335 9336 // Don't bother trying to sum two pointers. We probably can't 9337 // statically compute a load that results from it anyway. 9338 if (C2->getType()->isPointerTy()) 9339 return nullptr; 9340 9341 if (C->getType()->isPointerTy()) { 9342 C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()), 9343 C, C2); 9344 } else { 9345 C = ConstantExpr::getAdd(C, C2); 9346 } 9347 } 9348 return C; 9349 } 9350 return nullptr; 9351 } 9352 case scMulExpr: { 9353 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 9354 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 9355 // Don't bother with pointers at all. 9356 if (C->getType()->isPointerTy()) 9357 return nullptr; 9358 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 9359 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 9360 if (!C2 || C2->getType()->isPointerTy()) 9361 return nullptr; 9362 C = ConstantExpr::getMul(C, C2); 9363 } 9364 return C; 9365 } 9366 return nullptr; 9367 } 9368 case scUDivExpr: { 9369 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 9370 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 9371 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 9372 if (LHS->getType() == RHS->getType()) 9373 return ConstantExpr::getUDiv(LHS, RHS); 9374 return nullptr; 9375 } 9376 case scSMaxExpr: 9377 case scUMaxExpr: 9378 case scSMinExpr: 9379 case scUMinExpr: 9380 case scSequentialUMinExpr: 9381 return nullptr; // TODO: smax, umax, smin, umax, umin_seq. 9382 } 9383 llvm_unreachable("Unknown SCEV kind!"); 9384 } 9385 9386 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 9387 if (isa<SCEVConstant>(V)) return V; 9388 9389 // If this instruction is evolved from a constant-evolving PHI, compute the 9390 // exit value from the loop without using SCEVs. 9391 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 9392 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 9393 if (PHINode *PN = dyn_cast<PHINode>(I)) { 9394 const Loop *CurrLoop = this->LI[I->getParent()]; 9395 // Looking for loop exit value. 9396 if (CurrLoop && CurrLoop->getParentLoop() == L && 9397 PN->getParent() == CurrLoop->getHeader()) { 9398 // Okay, there is no closed form solution for the PHI node. Check 9399 // to see if the loop that contains it has a known backedge-taken 9400 // count. If so, we may be able to force computation of the exit 9401 // value. 9402 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 9403 // This trivial case can show up in some degenerate cases where 9404 // the incoming IR has not yet been fully simplified. 9405 if (BackedgeTakenCount->isZero()) { 9406 Value *InitValue = nullptr; 9407 bool MultipleInitValues = false; 9408 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 9409 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 9410 if (!InitValue) 9411 InitValue = PN->getIncomingValue(i); 9412 else if (InitValue != PN->getIncomingValue(i)) { 9413 MultipleInitValues = true; 9414 break; 9415 } 9416 } 9417 } 9418 if (!MultipleInitValues && InitValue) 9419 return getSCEV(InitValue); 9420 } 9421 // Do we have a loop invariant value flowing around the backedge 9422 // for a loop which must execute the backedge? 9423 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 9424 isKnownPositive(BackedgeTakenCount) && 9425 PN->getNumIncomingValues() == 2) { 9426 9427 unsigned InLoopPred = 9428 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 9429 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 9430 if (CurrLoop->isLoopInvariant(BackedgeVal)) 9431 return getSCEV(BackedgeVal); 9432 } 9433 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 9434 // Okay, we know how many times the containing loop executes. If 9435 // this is a constant evolving PHI node, get the final value at 9436 // the specified iteration number. 9437 Constant *RV = getConstantEvolutionLoopExitValue( 9438 PN, BTCC->getAPInt(), CurrLoop); 9439 if (RV) return getSCEV(RV); 9440 } 9441 } 9442 9443 // If there is a single-input Phi, evaluate it at our scope. If we can 9444 // prove that this replacement does not break LCSSA form, use new value. 9445 if (PN->getNumOperands() == 1) { 9446 const SCEV *Input = getSCEV(PN->getOperand(0)); 9447 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 9448 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 9449 // for the simplest case just support constants. 9450 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 9451 } 9452 } 9453 9454 // Okay, this is an expression that we cannot symbolically evaluate 9455 // into a SCEV. Check to see if it's possible to symbolically evaluate 9456 // the arguments into constants, and if so, try to constant propagate the 9457 // result. This is particularly useful for computing loop exit values. 9458 if (CanConstantFold(I)) { 9459 SmallVector<Constant *, 4> Operands; 9460 bool MadeImprovement = false; 9461 for (Value *Op : I->operands()) { 9462 if (Constant *C = dyn_cast<Constant>(Op)) { 9463 Operands.push_back(C); 9464 continue; 9465 } 9466 9467 // If any of the operands is non-constant and if they are 9468 // non-integer and non-pointer, don't even try to analyze them 9469 // with scev techniques. 9470 if (!isSCEVable(Op->getType())) 9471 return V; 9472 9473 const SCEV *OrigV = getSCEV(Op); 9474 const SCEV *OpV = getSCEVAtScope(OrigV, L); 9475 MadeImprovement |= OrigV != OpV; 9476 9477 Constant *C = BuildConstantFromSCEV(OpV); 9478 if (!C) return V; 9479 if (C->getType() != Op->getType()) 9480 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 9481 Op->getType(), 9482 false), 9483 C, Op->getType()); 9484 Operands.push_back(C); 9485 } 9486 9487 // Check to see if getSCEVAtScope actually made an improvement. 9488 if (MadeImprovement) { 9489 Constant *C = nullptr; 9490 const DataLayout &DL = getDataLayout(); 9491 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 9492 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 9493 Operands[1], DL, &TLI); 9494 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 9495 if (!Load->isVolatile()) 9496 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 9497 DL); 9498 } else 9499 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 9500 if (!C) return V; 9501 return getSCEV(C); 9502 } 9503 } 9504 } 9505 9506 // This is some other type of SCEVUnknown, just return it. 9507 return V; 9508 } 9509 9510 if (isa<SCEVCommutativeExpr>(V) || isa<SCEVSequentialMinMaxExpr>(V)) { 9511 const auto *Comm = cast<SCEVNAryExpr>(V); 9512 // Avoid performing the look-up in the common case where the specified 9513 // expression has no loop-variant portions. 9514 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 9515 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9516 if (OpAtScope != Comm->getOperand(i)) { 9517 // Okay, at least one of these operands is loop variant but might be 9518 // foldable. Build a new instance of the folded commutative expression. 9519 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 9520 Comm->op_begin()+i); 9521 NewOps.push_back(OpAtScope); 9522 9523 for (++i; i != e; ++i) { 9524 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 9525 NewOps.push_back(OpAtScope); 9526 } 9527 if (isa<SCEVAddExpr>(Comm)) 9528 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 9529 if (isa<SCEVMulExpr>(Comm)) 9530 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 9531 if (isa<SCEVMinMaxExpr>(Comm)) 9532 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 9533 if (isa<SCEVSequentialMinMaxExpr>(Comm)) 9534 return getSequentialMinMaxExpr(Comm->getSCEVType(), NewOps); 9535 llvm_unreachable("Unknown commutative / sequential min/max SCEV type!"); 9536 } 9537 } 9538 // If we got here, all operands are loop invariant. 9539 return Comm; 9540 } 9541 9542 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 9543 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 9544 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 9545 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 9546 return Div; // must be loop invariant 9547 return getUDivExpr(LHS, RHS); 9548 } 9549 9550 // If this is a loop recurrence for a loop that does not contain L, then we 9551 // are dealing with the final value computed by the loop. 9552 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 9553 // First, attempt to evaluate each operand. 9554 // Avoid performing the look-up in the common case where the specified 9555 // expression has no loop-variant portions. 9556 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 9557 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 9558 if (OpAtScope == AddRec->getOperand(i)) 9559 continue; 9560 9561 // Okay, at least one of these operands is loop variant but might be 9562 // foldable. Build a new instance of the folded commutative expression. 9563 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 9564 AddRec->op_begin()+i); 9565 NewOps.push_back(OpAtScope); 9566 for (++i; i != e; ++i) 9567 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 9568 9569 const SCEV *FoldedRec = 9570 getAddRecExpr(NewOps, AddRec->getLoop(), 9571 AddRec->getNoWrapFlags(SCEV::FlagNW)); 9572 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 9573 // The addrec may be folded to a nonrecurrence, for example, if the 9574 // induction variable is multiplied by zero after constant folding. Go 9575 // ahead and return the folded value. 9576 if (!AddRec) 9577 return FoldedRec; 9578 break; 9579 } 9580 9581 // If the scope is outside the addrec's loop, evaluate it by using the 9582 // loop exit value of the addrec. 9583 if (!AddRec->getLoop()->contains(L)) { 9584 // To evaluate this recurrence, we need to know how many times the AddRec 9585 // loop iterates. Compute this now. 9586 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 9587 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 9588 9589 // Then, evaluate the AddRec. 9590 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 9591 } 9592 9593 return AddRec; 9594 } 9595 9596 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 9597 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 9598 if (Op == Cast->getOperand()) 9599 return Cast; // must be loop invariant 9600 return getCastExpr(Cast->getSCEVType(), Op, Cast->getType()); 9601 } 9602 9603 llvm_unreachable("Unknown SCEV type!"); 9604 } 9605 9606 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 9607 return getSCEVAtScope(getSCEV(V), L); 9608 } 9609 9610 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 9611 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 9612 return stripInjectiveFunctions(ZExt->getOperand()); 9613 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 9614 return stripInjectiveFunctions(SExt->getOperand()); 9615 return S; 9616 } 9617 9618 /// Finds the minimum unsigned root of the following equation: 9619 /// 9620 /// A * X = B (mod N) 9621 /// 9622 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 9623 /// A and B isn't important. 9624 /// 9625 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 9626 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 9627 ScalarEvolution &SE) { 9628 uint32_t BW = A.getBitWidth(); 9629 assert(BW == SE.getTypeSizeInBits(B->getType())); 9630 assert(A != 0 && "A must be non-zero."); 9631 9632 // 1. D = gcd(A, N) 9633 // 9634 // The gcd of A and N may have only one prime factor: 2. The number of 9635 // trailing zeros in A is its multiplicity 9636 uint32_t Mult2 = A.countTrailingZeros(); 9637 // D = 2^Mult2 9638 9639 // 2. Check if B is divisible by D. 9640 // 9641 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 9642 // is not less than multiplicity of this prime factor for D. 9643 if (SE.GetMinTrailingZeros(B) < Mult2) 9644 return SE.getCouldNotCompute(); 9645 9646 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 9647 // modulo (N / D). 9648 // 9649 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 9650 // (N / D) in general. The inverse itself always fits into BW bits, though, 9651 // so we immediately truncate it. 9652 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 9653 APInt Mod(BW + 1, 0); 9654 Mod.setBit(BW - Mult2); // Mod = N / D 9655 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 9656 9657 // 4. Compute the minimum unsigned root of the equation: 9658 // I * (B / D) mod (N / D) 9659 // To simplify the computation, we factor out the divide by D: 9660 // (I * B mod N) / D 9661 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 9662 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 9663 } 9664 9665 /// For a given quadratic addrec, generate coefficients of the corresponding 9666 /// quadratic equation, multiplied by a common value to ensure that they are 9667 /// integers. 9668 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 9669 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 9670 /// were multiplied by, and BitWidth is the bit width of the original addrec 9671 /// coefficients. 9672 /// This function returns None if the addrec coefficients are not compile- 9673 /// time constants. 9674 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 9675 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 9676 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 9677 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 9678 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 9679 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 9680 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 9681 << *AddRec << '\n'); 9682 9683 // We currently can only solve this if the coefficients are constants. 9684 if (!LC || !MC || !NC) { 9685 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 9686 return None; 9687 } 9688 9689 APInt L = LC->getAPInt(); 9690 APInt M = MC->getAPInt(); 9691 APInt N = NC->getAPInt(); 9692 assert(!N.isZero() && "This is not a quadratic addrec"); 9693 9694 unsigned BitWidth = LC->getAPInt().getBitWidth(); 9695 unsigned NewWidth = BitWidth + 1; 9696 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 9697 << BitWidth << '\n'); 9698 // The sign-extension (as opposed to a zero-extension) here matches the 9699 // extension used in SolveQuadraticEquationWrap (with the same motivation). 9700 N = N.sext(NewWidth); 9701 M = M.sext(NewWidth); 9702 L = L.sext(NewWidth); 9703 9704 // The increments are M, M+N, M+2N, ..., so the accumulated values are 9705 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 9706 // L+M, L+2M+N, L+3M+3N, ... 9707 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 9708 // 9709 // The equation Acc = 0 is then 9710 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 9711 // In a quadratic form it becomes: 9712 // N n^2 + (2M-N) n + 2L = 0. 9713 9714 APInt A = N; 9715 APInt B = 2 * M - A; 9716 APInt C = 2 * L; 9717 APInt T = APInt(NewWidth, 2); 9718 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 9719 << "x + " << C << ", coeff bw: " << NewWidth 9720 << ", multiplied by " << T << '\n'); 9721 return std::make_tuple(A, B, C, T, BitWidth); 9722 } 9723 9724 /// Helper function to compare optional APInts: 9725 /// (a) if X and Y both exist, return min(X, Y), 9726 /// (b) if neither X nor Y exist, return None, 9727 /// (c) if exactly one of X and Y exists, return that value. 9728 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 9729 if (X.hasValue() && Y.hasValue()) { 9730 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 9731 APInt XW = X->sextOrSelf(W); 9732 APInt YW = Y->sextOrSelf(W); 9733 return XW.slt(YW) ? *X : *Y; 9734 } 9735 if (!X.hasValue() && !Y.hasValue()) 9736 return None; 9737 return X.hasValue() ? *X : *Y; 9738 } 9739 9740 /// Helper function to truncate an optional APInt to a given BitWidth. 9741 /// When solving addrec-related equations, it is preferable to return a value 9742 /// that has the same bit width as the original addrec's coefficients. If the 9743 /// solution fits in the original bit width, truncate it (except for i1). 9744 /// Returning a value of a different bit width may inhibit some optimizations. 9745 /// 9746 /// In general, a solution to a quadratic equation generated from an addrec 9747 /// may require BW+1 bits, where BW is the bit width of the addrec's 9748 /// coefficients. The reason is that the coefficients of the quadratic 9749 /// equation are BW+1 bits wide (to avoid truncation when converting from 9750 /// the addrec to the equation). 9751 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 9752 if (!X.hasValue()) 9753 return None; 9754 unsigned W = X->getBitWidth(); 9755 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 9756 return X->trunc(BitWidth); 9757 return X; 9758 } 9759 9760 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 9761 /// iterations. The values L, M, N are assumed to be signed, and they 9762 /// should all have the same bit widths. 9763 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 9764 /// where BW is the bit width of the addrec's coefficients. 9765 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 9766 /// returned as such, otherwise the bit width of the returned value may 9767 /// be greater than BW. 9768 /// 9769 /// This function returns None if 9770 /// (a) the addrec coefficients are not constant, or 9771 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 9772 /// like x^2 = 5, no integer solutions exist, in other cases an integer 9773 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 9774 static Optional<APInt> 9775 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 9776 APInt A, B, C, M; 9777 unsigned BitWidth; 9778 auto T = GetQuadraticEquation(AddRec); 9779 if (!T.hasValue()) 9780 return None; 9781 9782 std::tie(A, B, C, M, BitWidth) = *T; 9783 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 9784 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 9785 if (!X.hasValue()) 9786 return None; 9787 9788 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 9789 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 9790 if (!V->isZero()) 9791 return None; 9792 9793 return TruncIfPossible(X, BitWidth); 9794 } 9795 9796 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 9797 /// iterations. The values M, N are assumed to be signed, and they 9798 /// should all have the same bit widths. 9799 /// Find the least n such that c(n) does not belong to the given range, 9800 /// while c(n-1) does. 9801 /// 9802 /// This function returns None if 9803 /// (a) the addrec coefficients are not constant, or 9804 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 9805 /// bounds of the range. 9806 static Optional<APInt> 9807 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 9808 const ConstantRange &Range, ScalarEvolution &SE) { 9809 assert(AddRec->getOperand(0)->isZero() && 9810 "Starting value of addrec should be 0"); 9811 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 9812 << Range << ", addrec " << *AddRec << '\n'); 9813 // This case is handled in getNumIterationsInRange. Here we can assume that 9814 // we start in the range. 9815 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 9816 "Addrec's initial value should be in range"); 9817 9818 APInt A, B, C, M; 9819 unsigned BitWidth; 9820 auto T = GetQuadraticEquation(AddRec); 9821 if (!T.hasValue()) 9822 return None; 9823 9824 // Be careful about the return value: there can be two reasons for not 9825 // returning an actual number. First, if no solutions to the equations 9826 // were found, and second, if the solutions don't leave the given range. 9827 // The first case means that the actual solution is "unknown", the second 9828 // means that it's known, but not valid. If the solution is unknown, we 9829 // cannot make any conclusions. 9830 // Return a pair: the optional solution and a flag indicating if the 9831 // solution was found. 9832 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 9833 // Solve for signed overflow and unsigned overflow, pick the lower 9834 // solution. 9835 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 9836 << Bound << " (before multiplying by " << M << ")\n"); 9837 Bound *= M; // The quadratic equation multiplier. 9838 9839 Optional<APInt> SO = None; 9840 if (BitWidth > 1) { 9841 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9842 "signed overflow\n"); 9843 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 9844 } 9845 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 9846 "unsigned overflow\n"); 9847 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 9848 BitWidth+1); 9849 9850 auto LeavesRange = [&] (const APInt &X) { 9851 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 9852 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 9853 if (Range.contains(V0->getValue())) 9854 return false; 9855 // X should be at least 1, so X-1 is non-negative. 9856 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 9857 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 9858 if (Range.contains(V1->getValue())) 9859 return true; 9860 return false; 9861 }; 9862 9863 // If SolveQuadraticEquationWrap returns None, it means that there can 9864 // be a solution, but the function failed to find it. We cannot treat it 9865 // as "no solution". 9866 if (!SO.hasValue() || !UO.hasValue()) 9867 return { None, false }; 9868 9869 // Check the smaller value first to see if it leaves the range. 9870 // At this point, both SO and UO must have values. 9871 Optional<APInt> Min = MinOptional(SO, UO); 9872 if (LeavesRange(*Min)) 9873 return { Min, true }; 9874 Optional<APInt> Max = Min == SO ? UO : SO; 9875 if (LeavesRange(*Max)) 9876 return { Max, true }; 9877 9878 // Solutions were found, but were eliminated, hence the "true". 9879 return { None, true }; 9880 }; 9881 9882 std::tie(A, B, C, M, BitWidth) = *T; 9883 // Lower bound is inclusive, subtract 1 to represent the exiting value. 9884 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 9885 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 9886 auto SL = SolveForBoundary(Lower); 9887 auto SU = SolveForBoundary(Upper); 9888 // If any of the solutions was unknown, no meaninigful conclusions can 9889 // be made. 9890 if (!SL.second || !SU.second) 9891 return None; 9892 9893 // Claim: The correct solution is not some value between Min and Max. 9894 // 9895 // Justification: Assuming that Min and Max are different values, one of 9896 // them is when the first signed overflow happens, the other is when the 9897 // first unsigned overflow happens. Crossing the range boundary is only 9898 // possible via an overflow (treating 0 as a special case of it, modeling 9899 // an overflow as crossing k*2^W for some k). 9900 // 9901 // The interesting case here is when Min was eliminated as an invalid 9902 // solution, but Max was not. The argument is that if there was another 9903 // overflow between Min and Max, it would also have been eliminated if 9904 // it was considered. 9905 // 9906 // For a given boundary, it is possible to have two overflows of the same 9907 // type (signed/unsigned) without having the other type in between: this 9908 // can happen when the vertex of the parabola is between the iterations 9909 // corresponding to the overflows. This is only possible when the two 9910 // overflows cross k*2^W for the same k. In such case, if the second one 9911 // left the range (and was the first one to do so), the first overflow 9912 // would have to enter the range, which would mean that either we had left 9913 // the range before or that we started outside of it. Both of these cases 9914 // are contradictions. 9915 // 9916 // Claim: In the case where SolveForBoundary returns None, the correct 9917 // solution is not some value between the Max for this boundary and the 9918 // Min of the other boundary. 9919 // 9920 // Justification: Assume that we had such Max_A and Min_B corresponding 9921 // to range boundaries A and B and such that Max_A < Min_B. If there was 9922 // a solution between Max_A and Min_B, it would have to be caused by an 9923 // overflow corresponding to either A or B. It cannot correspond to B, 9924 // since Min_B is the first occurrence of such an overflow. If it 9925 // corresponded to A, it would have to be either a signed or an unsigned 9926 // overflow that is larger than both eliminated overflows for A. But 9927 // between the eliminated overflows and this overflow, the values would 9928 // cover the entire value space, thus crossing the other boundary, which 9929 // is a contradiction. 9930 9931 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 9932 } 9933 9934 ScalarEvolution::ExitLimit 9935 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 9936 bool AllowPredicates) { 9937 9938 // This is only used for loops with a "x != y" exit test. The exit condition 9939 // is now expressed as a single expression, V = x-y. So the exit test is 9940 // effectively V != 0. We know and take advantage of the fact that this 9941 // expression only being used in a comparison by zero context. 9942 9943 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 9944 // If the value is a constant 9945 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9946 // If the value is already zero, the branch will execute zero times. 9947 if (C->getValue()->isZero()) return C; 9948 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9949 } 9950 9951 const SCEVAddRecExpr *AddRec = 9952 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 9953 9954 if (!AddRec && AllowPredicates) 9955 // Try to make this an AddRec using runtime tests, in the first X 9956 // iterations of this loop, where X is the SCEV expression found by the 9957 // algorithm below. 9958 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 9959 9960 if (!AddRec || AddRec->getLoop() != L) 9961 return getCouldNotCompute(); 9962 9963 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 9964 // the quadratic equation to solve it. 9965 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 9966 // We can only use this value if the chrec ends up with an exact zero 9967 // value at this index. When solving for "X*X != 5", for example, we 9968 // should not accept a root of 2. 9969 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 9970 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 9971 return ExitLimit(R, R, false, Predicates); 9972 } 9973 return getCouldNotCompute(); 9974 } 9975 9976 // Otherwise we can only handle this if it is affine. 9977 if (!AddRec->isAffine()) 9978 return getCouldNotCompute(); 9979 9980 // If this is an affine expression, the execution count of this branch is 9981 // the minimum unsigned root of the following equation: 9982 // 9983 // Start + Step*N = 0 (mod 2^BW) 9984 // 9985 // equivalent to: 9986 // 9987 // Step*N = -Start (mod 2^BW) 9988 // 9989 // where BW is the common bit width of Start and Step. 9990 9991 // Get the initial value for the loop. 9992 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 9993 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 9994 9995 // For now we handle only constant steps. 9996 // 9997 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 9998 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 9999 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 10000 // We have not yet seen any such cases. 10001 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 10002 if (!StepC || StepC->getValue()->isZero()) 10003 return getCouldNotCompute(); 10004 10005 // For positive steps (counting up until unsigned overflow): 10006 // N = -Start/Step (as unsigned) 10007 // For negative steps (counting down to zero): 10008 // N = Start/-Step 10009 // First compute the unsigned distance from zero in the direction of Step. 10010 bool CountDown = StepC->getAPInt().isNegative(); 10011 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 10012 10013 // Handle unitary steps, which cannot wraparound. 10014 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 10015 // N = Distance (as unsigned) 10016 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 10017 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 10018 MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance)); 10019 10020 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 10021 // we end up with a loop whose backedge-taken count is n - 1. Detect this 10022 // case, and see if we can improve the bound. 10023 // 10024 // Explicitly handling this here is necessary because getUnsignedRange 10025 // isn't context-sensitive; it doesn't know that we only care about the 10026 // range inside the loop. 10027 const SCEV *Zero = getZero(Distance->getType()); 10028 const SCEV *One = getOne(Distance->getType()); 10029 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 10030 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 10031 // If Distance + 1 doesn't overflow, we can compute the maximum distance 10032 // as "unsigned_max(Distance + 1) - 1". 10033 ConstantRange CR = getUnsignedRange(DistancePlusOne); 10034 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 10035 } 10036 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 10037 } 10038 10039 // If the condition controls loop exit (the loop exits only if the expression 10040 // is true) and the addition is no-wrap we can use unsigned divide to 10041 // compute the backedge count. In this case, the step may not divide the 10042 // distance, but we don't care because if the condition is "missed" the loop 10043 // will have undefined behavior due to wrapping. 10044 if (ControlsExit && AddRec->hasNoSelfWrap() && 10045 loopHasNoAbnormalExits(AddRec->getLoop())) { 10046 const SCEV *Exact = 10047 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 10048 const SCEV *Max = getCouldNotCompute(); 10049 if (Exact != getCouldNotCompute()) { 10050 APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L)); 10051 Max = getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact))); 10052 } 10053 return ExitLimit(Exact, Max, false, Predicates); 10054 } 10055 10056 // Solve the general equation. 10057 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 10058 getNegativeSCEV(Start), *this); 10059 10060 const SCEV *M = E; 10061 if (E != getCouldNotCompute()) { 10062 APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L)); 10063 M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E))); 10064 } 10065 return ExitLimit(E, M, false, Predicates); 10066 } 10067 10068 ScalarEvolution::ExitLimit 10069 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 10070 // Loops that look like: while (X == 0) are very strange indeed. We don't 10071 // handle them yet except for the trivial case. This could be expanded in the 10072 // future as needed. 10073 10074 // If the value is a constant, check to see if it is known to be non-zero 10075 // already. If so, the backedge will execute zero times. 10076 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 10077 if (!C->getValue()->isZero()) 10078 return getZero(C->getType()); 10079 return getCouldNotCompute(); // Otherwise it will loop infinitely. 10080 } 10081 10082 // We could implement others, but I really doubt anyone writes loops like 10083 // this, and if they did, they would already be constant folded. 10084 return getCouldNotCompute(); 10085 } 10086 10087 std::pair<const BasicBlock *, const BasicBlock *> 10088 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 10089 const { 10090 // If the block has a unique predecessor, then there is no path from the 10091 // predecessor to the block that does not go through the direct edge 10092 // from the predecessor to the block. 10093 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 10094 return {Pred, BB}; 10095 10096 // A loop's header is defined to be a block that dominates the loop. 10097 // If the header has a unique predecessor outside the loop, it must be 10098 // a block that has exactly one successor that can reach the loop. 10099 if (const Loop *L = LI.getLoopFor(BB)) 10100 return {L->getLoopPredecessor(), L->getHeader()}; 10101 10102 return {nullptr, nullptr}; 10103 } 10104 10105 /// SCEV structural equivalence is usually sufficient for testing whether two 10106 /// expressions are equal, however for the purposes of looking for a condition 10107 /// guarding a loop, it can be useful to be a little more general, since a 10108 /// front-end may have replicated the controlling expression. 10109 static bool HasSameValue(const SCEV *A, const SCEV *B) { 10110 // Quick check to see if they are the same SCEV. 10111 if (A == B) return true; 10112 10113 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 10114 // Not all instructions that are "identical" compute the same value. For 10115 // instance, two distinct alloca instructions allocating the same type are 10116 // identical and do not read memory; but compute distinct values. 10117 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 10118 }; 10119 10120 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 10121 // two different instructions with the same value. Check for this case. 10122 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 10123 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 10124 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 10125 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 10126 if (ComputesEqualValues(AI, BI)) 10127 return true; 10128 10129 // Otherwise assume they may have a different value. 10130 return false; 10131 } 10132 10133 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 10134 const SCEV *&LHS, const SCEV *&RHS, 10135 unsigned Depth, 10136 bool ControllingFiniteLoop) { 10137 bool Changed = false; 10138 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 10139 // '0 != 0'. 10140 auto TrivialCase = [&](bool TriviallyTrue) { 10141 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 10142 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 10143 return true; 10144 }; 10145 // If we hit the max recursion limit bail out. 10146 if (Depth >= 3) 10147 return false; 10148 10149 // Canonicalize a constant to the right side. 10150 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 10151 // Check for both operands constant. 10152 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 10153 if (ConstantExpr::getICmp(Pred, 10154 LHSC->getValue(), 10155 RHSC->getValue())->isNullValue()) 10156 return TrivialCase(false); 10157 else 10158 return TrivialCase(true); 10159 } 10160 // Otherwise swap the operands to put the constant on the right. 10161 std::swap(LHS, RHS); 10162 Pred = ICmpInst::getSwappedPredicate(Pred); 10163 Changed = true; 10164 } 10165 10166 // If we're comparing an addrec with a value which is loop-invariant in the 10167 // addrec's loop, put the addrec on the left. Also make a dominance check, 10168 // as both operands could be addrecs loop-invariant in each other's loop. 10169 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 10170 const Loop *L = AR->getLoop(); 10171 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 10172 std::swap(LHS, RHS); 10173 Pred = ICmpInst::getSwappedPredicate(Pred); 10174 Changed = true; 10175 } 10176 } 10177 10178 // If there's a constant operand, canonicalize comparisons with boundary 10179 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 10180 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 10181 const APInt &RA = RC->getAPInt(); 10182 10183 bool SimplifiedByConstantRange = false; 10184 10185 if (!ICmpInst::isEquality(Pred)) { 10186 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 10187 if (ExactCR.isFullSet()) 10188 return TrivialCase(true); 10189 else if (ExactCR.isEmptySet()) 10190 return TrivialCase(false); 10191 10192 APInt NewRHS; 10193 CmpInst::Predicate NewPred; 10194 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 10195 ICmpInst::isEquality(NewPred)) { 10196 // We were able to convert an inequality to an equality. 10197 Pred = NewPred; 10198 RHS = getConstant(NewRHS); 10199 Changed = SimplifiedByConstantRange = true; 10200 } 10201 } 10202 10203 if (!SimplifiedByConstantRange) { 10204 switch (Pred) { 10205 default: 10206 break; 10207 case ICmpInst::ICMP_EQ: 10208 case ICmpInst::ICMP_NE: 10209 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 10210 if (!RA) 10211 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 10212 if (const SCEVMulExpr *ME = 10213 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 10214 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 10215 ME->getOperand(0)->isAllOnesValue()) { 10216 RHS = AE->getOperand(1); 10217 LHS = ME->getOperand(1); 10218 Changed = true; 10219 } 10220 break; 10221 10222 10223 // The "Should have been caught earlier!" messages refer to the fact 10224 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 10225 // should have fired on the corresponding cases, and canonicalized the 10226 // check to trivial case. 10227 10228 case ICmpInst::ICMP_UGE: 10229 assert(!RA.isMinValue() && "Should have been caught earlier!"); 10230 Pred = ICmpInst::ICMP_UGT; 10231 RHS = getConstant(RA - 1); 10232 Changed = true; 10233 break; 10234 case ICmpInst::ICMP_ULE: 10235 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 10236 Pred = ICmpInst::ICMP_ULT; 10237 RHS = getConstant(RA + 1); 10238 Changed = true; 10239 break; 10240 case ICmpInst::ICMP_SGE: 10241 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 10242 Pred = ICmpInst::ICMP_SGT; 10243 RHS = getConstant(RA - 1); 10244 Changed = true; 10245 break; 10246 case ICmpInst::ICMP_SLE: 10247 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 10248 Pred = ICmpInst::ICMP_SLT; 10249 RHS = getConstant(RA + 1); 10250 Changed = true; 10251 break; 10252 } 10253 } 10254 } 10255 10256 // Check for obvious equality. 10257 if (HasSameValue(LHS, RHS)) { 10258 if (ICmpInst::isTrueWhenEqual(Pred)) 10259 return TrivialCase(true); 10260 if (ICmpInst::isFalseWhenEqual(Pred)) 10261 return TrivialCase(false); 10262 } 10263 10264 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 10265 // adding or subtracting 1 from one of the operands. This can be done for 10266 // one of two reasons: 10267 // 1) The range of the RHS does not include the (signed/unsigned) boundaries 10268 // 2) The loop is finite, with this comparison controlling the exit. Since the 10269 // loop is finite, the bound cannot include the corresponding boundary 10270 // (otherwise it would loop forever). 10271 switch (Pred) { 10272 case ICmpInst::ICMP_SLE: 10273 if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) { 10274 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10275 SCEV::FlagNSW); 10276 Pred = ICmpInst::ICMP_SLT; 10277 Changed = true; 10278 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 10279 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 10280 SCEV::FlagNSW); 10281 Pred = ICmpInst::ICMP_SLT; 10282 Changed = true; 10283 } 10284 break; 10285 case ICmpInst::ICMP_SGE: 10286 if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) { 10287 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 10288 SCEV::FlagNSW); 10289 Pred = ICmpInst::ICMP_SGT; 10290 Changed = true; 10291 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 10292 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10293 SCEV::FlagNSW); 10294 Pred = ICmpInst::ICMP_SGT; 10295 Changed = true; 10296 } 10297 break; 10298 case ICmpInst::ICMP_ULE: 10299 if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) { 10300 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 10301 SCEV::FlagNUW); 10302 Pred = ICmpInst::ICMP_ULT; 10303 Changed = true; 10304 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 10305 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 10306 Pred = ICmpInst::ICMP_ULT; 10307 Changed = true; 10308 } 10309 break; 10310 case ICmpInst::ICMP_UGE: 10311 if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) { 10312 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 10313 Pred = ICmpInst::ICMP_UGT; 10314 Changed = true; 10315 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 10316 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 10317 SCEV::FlagNUW); 10318 Pred = ICmpInst::ICMP_UGT; 10319 Changed = true; 10320 } 10321 break; 10322 default: 10323 break; 10324 } 10325 10326 // TODO: More simplifications are possible here. 10327 10328 // Recursively simplify until we either hit a recursion limit or nothing 10329 // changes. 10330 if (Changed) 10331 return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1, 10332 ControllingFiniteLoop); 10333 10334 return Changed; 10335 } 10336 10337 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 10338 return getSignedRangeMax(S).isNegative(); 10339 } 10340 10341 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 10342 return getSignedRangeMin(S).isStrictlyPositive(); 10343 } 10344 10345 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 10346 return !getSignedRangeMin(S).isNegative(); 10347 } 10348 10349 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 10350 return !getSignedRangeMax(S).isStrictlyPositive(); 10351 } 10352 10353 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 10354 return getUnsignedRangeMin(S) != 0; 10355 } 10356 10357 std::pair<const SCEV *, const SCEV *> 10358 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 10359 // Compute SCEV on entry of loop L. 10360 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 10361 if (Start == getCouldNotCompute()) 10362 return { Start, Start }; 10363 // Compute post increment SCEV for loop L. 10364 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 10365 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 10366 return { Start, PostInc }; 10367 } 10368 10369 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 10370 const SCEV *LHS, const SCEV *RHS) { 10371 // First collect all loops. 10372 SmallPtrSet<const Loop *, 8> LoopsUsed; 10373 getUsedLoops(LHS, LoopsUsed); 10374 getUsedLoops(RHS, LoopsUsed); 10375 10376 if (LoopsUsed.empty()) 10377 return false; 10378 10379 // Domination relationship must be a linear order on collected loops. 10380 #ifndef NDEBUG 10381 for (auto *L1 : LoopsUsed) 10382 for (auto *L2 : LoopsUsed) 10383 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 10384 DT.dominates(L2->getHeader(), L1->getHeader())) && 10385 "Domination relationship is not a linear order"); 10386 #endif 10387 10388 const Loop *MDL = 10389 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 10390 [&](const Loop *L1, const Loop *L2) { 10391 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 10392 }); 10393 10394 // Get init and post increment value for LHS. 10395 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 10396 // if LHS contains unknown non-invariant SCEV then bail out. 10397 if (SplitLHS.first == getCouldNotCompute()) 10398 return false; 10399 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 10400 // Get init and post increment value for RHS. 10401 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 10402 // if RHS contains unknown non-invariant SCEV then bail out. 10403 if (SplitRHS.first == getCouldNotCompute()) 10404 return false; 10405 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 10406 // It is possible that init SCEV contains an invariant load but it does 10407 // not dominate MDL and is not available at MDL loop entry, so we should 10408 // check it here. 10409 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 10410 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 10411 return false; 10412 10413 // It seems backedge guard check is faster than entry one so in some cases 10414 // it can speed up whole estimation by short circuit 10415 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 10416 SplitRHS.second) && 10417 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 10418 } 10419 10420 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 10421 const SCEV *LHS, const SCEV *RHS) { 10422 // Canonicalize the inputs first. 10423 (void)SimplifyICmpOperands(Pred, LHS, RHS); 10424 10425 if (isKnownViaInduction(Pred, LHS, RHS)) 10426 return true; 10427 10428 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 10429 return true; 10430 10431 // Otherwise see what can be done with some simple reasoning. 10432 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 10433 } 10434 10435 Optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred, 10436 const SCEV *LHS, 10437 const SCEV *RHS) { 10438 if (isKnownPredicate(Pred, LHS, RHS)) 10439 return true; 10440 else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS)) 10441 return false; 10442 return None; 10443 } 10444 10445 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 10446 const SCEV *LHS, const SCEV *RHS, 10447 const Instruction *CtxI) { 10448 // TODO: Analyze guards and assumes from Context's block. 10449 return isKnownPredicate(Pred, LHS, RHS) || 10450 isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS); 10451 } 10452 10453 Optional<bool> ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, 10454 const SCEV *LHS, 10455 const SCEV *RHS, 10456 const Instruction *CtxI) { 10457 Optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS); 10458 if (KnownWithoutContext) 10459 return KnownWithoutContext; 10460 10461 if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS)) 10462 return true; 10463 else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), 10464 ICmpInst::getInversePredicate(Pred), 10465 LHS, RHS)) 10466 return false; 10467 return None; 10468 } 10469 10470 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 10471 const SCEVAddRecExpr *LHS, 10472 const SCEV *RHS) { 10473 const Loop *L = LHS->getLoop(); 10474 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 10475 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 10476 } 10477 10478 Optional<ScalarEvolution::MonotonicPredicateType> 10479 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 10480 ICmpInst::Predicate Pred) { 10481 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 10482 10483 #ifndef NDEBUG 10484 // Verify an invariant: inverting the predicate should turn a monotonically 10485 // increasing change to a monotonically decreasing one, and vice versa. 10486 if (Result) { 10487 auto ResultSwapped = 10488 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 10489 10490 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 10491 assert(ResultSwapped.getValue() != Result.getValue() && 10492 "monotonicity should flip as we flip the predicate"); 10493 } 10494 #endif 10495 10496 return Result; 10497 } 10498 10499 Optional<ScalarEvolution::MonotonicPredicateType> 10500 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 10501 ICmpInst::Predicate Pred) { 10502 // A zero step value for LHS means the induction variable is essentially a 10503 // loop invariant value. We don't really depend on the predicate actually 10504 // flipping from false to true (for increasing predicates, and the other way 10505 // around for decreasing predicates), all we care about is that *if* the 10506 // predicate changes then it only changes from false to true. 10507 // 10508 // A zero step value in itself is not very useful, but there may be places 10509 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 10510 // as general as possible. 10511 10512 // Only handle LE/LT/GE/GT predicates. 10513 if (!ICmpInst::isRelational(Pred)) 10514 return None; 10515 10516 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 10517 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 10518 "Should be greater or less!"); 10519 10520 // Check that AR does not wrap. 10521 if (ICmpInst::isUnsigned(Pred)) { 10522 if (!LHS->hasNoUnsignedWrap()) 10523 return None; 10524 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10525 } else { 10526 assert(ICmpInst::isSigned(Pred) && 10527 "Relational predicate is either signed or unsigned!"); 10528 if (!LHS->hasNoSignedWrap()) 10529 return None; 10530 10531 const SCEV *Step = LHS->getStepRecurrence(*this); 10532 10533 if (isKnownNonNegative(Step)) 10534 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10535 10536 if (isKnownNonPositive(Step)) 10537 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 10538 10539 return None; 10540 } 10541 } 10542 10543 Optional<ScalarEvolution::LoopInvariantPredicate> 10544 ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred, 10545 const SCEV *LHS, const SCEV *RHS, 10546 const Loop *L) { 10547 10548 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10549 if (!isLoopInvariant(RHS, L)) { 10550 if (!isLoopInvariant(LHS, L)) 10551 return None; 10552 10553 std::swap(LHS, RHS); 10554 Pred = ICmpInst::getSwappedPredicate(Pred); 10555 } 10556 10557 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10558 if (!ArLHS || ArLHS->getLoop() != L) 10559 return None; 10560 10561 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 10562 if (!MonotonicType) 10563 return None; 10564 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 10565 // true as the loop iterates, and the backedge is control dependent on 10566 // "ArLHS `Pred` RHS" == true then we can reason as follows: 10567 // 10568 // * if the predicate was false in the first iteration then the predicate 10569 // is never evaluated again, since the loop exits without taking the 10570 // backedge. 10571 // * if the predicate was true in the first iteration then it will 10572 // continue to be true for all future iterations since it is 10573 // monotonically increasing. 10574 // 10575 // For both the above possibilities, we can replace the loop varying 10576 // predicate with its value on the first iteration of the loop (which is 10577 // loop invariant). 10578 // 10579 // A similar reasoning applies for a monotonically decreasing predicate, by 10580 // replacing true with false and false with true in the above two bullets. 10581 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 10582 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 10583 10584 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 10585 return None; 10586 10587 return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(), RHS); 10588 } 10589 10590 Optional<ScalarEvolution::LoopInvariantPredicate> 10591 ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations( 10592 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 10593 const Instruction *CtxI, const SCEV *MaxIter) { 10594 // Try to prove the following set of facts: 10595 // - The predicate is monotonic in the iteration space. 10596 // - If the check does not fail on the 1st iteration: 10597 // - No overflow will happen during first MaxIter iterations; 10598 // - It will not fail on the MaxIter'th iteration. 10599 // If the check does fail on the 1st iteration, we leave the loop and no 10600 // other checks matter. 10601 10602 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 10603 if (!isLoopInvariant(RHS, L)) { 10604 if (!isLoopInvariant(LHS, L)) 10605 return None; 10606 10607 std::swap(LHS, RHS); 10608 Pred = ICmpInst::getSwappedPredicate(Pred); 10609 } 10610 10611 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 10612 if (!AR || AR->getLoop() != L) 10613 return None; 10614 10615 // The predicate must be relational (i.e. <, <=, >=, >). 10616 if (!ICmpInst::isRelational(Pred)) 10617 return None; 10618 10619 // TODO: Support steps other than +/- 1. 10620 const SCEV *Step = AR->getStepRecurrence(*this); 10621 auto *One = getOne(Step->getType()); 10622 auto *MinusOne = getNegativeSCEV(One); 10623 if (Step != One && Step != MinusOne) 10624 return None; 10625 10626 // Type mismatch here means that MaxIter is potentially larger than max 10627 // unsigned value in start type, which mean we cannot prove no wrap for the 10628 // indvar. 10629 if (AR->getType() != MaxIter->getType()) 10630 return None; 10631 10632 // Value of IV on suggested last iteration. 10633 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 10634 // Does it still meet the requirement? 10635 if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS)) 10636 return None; 10637 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 10638 // not exceed max unsigned value of this type), this effectively proves 10639 // that there is no wrap during the iteration. To prove that there is no 10640 // signed/unsigned wrap, we need to check that 10641 // Start <= Last for step = 1 or Start >= Last for step = -1. 10642 ICmpInst::Predicate NoOverflowPred = 10643 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 10644 if (Step == MinusOne) 10645 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 10646 const SCEV *Start = AR->getStart(); 10647 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI)) 10648 return None; 10649 10650 // Everything is fine. 10651 return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS); 10652 } 10653 10654 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 10655 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 10656 if (HasSameValue(LHS, RHS)) 10657 return ICmpInst::isTrueWhenEqual(Pred); 10658 10659 // This code is split out from isKnownPredicate because it is called from 10660 // within isLoopEntryGuardedByCond. 10661 10662 auto CheckRanges = [&](const ConstantRange &RangeLHS, 10663 const ConstantRange &RangeRHS) { 10664 return RangeLHS.icmp(Pred, RangeRHS); 10665 }; 10666 10667 // The check at the top of the function catches the case where the values are 10668 // known to be equal. 10669 if (Pred == CmpInst::ICMP_EQ) 10670 return false; 10671 10672 if (Pred == CmpInst::ICMP_NE) { 10673 if (CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 10674 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS))) 10675 return true; 10676 auto *Diff = getMinusSCEV(LHS, RHS); 10677 return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff); 10678 } 10679 10680 if (CmpInst::isSigned(Pred)) 10681 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 10682 10683 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 10684 } 10685 10686 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 10687 const SCEV *LHS, 10688 const SCEV *RHS) { 10689 // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where 10690 // C1 and C2 are constant integers. If either X or Y are not add expressions, 10691 // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via 10692 // OutC1 and OutC2. 10693 auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y, 10694 APInt &OutC1, APInt &OutC2, 10695 SCEV::NoWrapFlags ExpectedFlags) { 10696 const SCEV *XNonConstOp, *XConstOp; 10697 const SCEV *YNonConstOp, *YConstOp; 10698 SCEV::NoWrapFlags XFlagsPresent; 10699 SCEV::NoWrapFlags YFlagsPresent; 10700 10701 if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) { 10702 XConstOp = getZero(X->getType()); 10703 XNonConstOp = X; 10704 XFlagsPresent = ExpectedFlags; 10705 } 10706 if (!isa<SCEVConstant>(XConstOp) || 10707 (XFlagsPresent & ExpectedFlags) != ExpectedFlags) 10708 return false; 10709 10710 if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) { 10711 YConstOp = getZero(Y->getType()); 10712 YNonConstOp = Y; 10713 YFlagsPresent = ExpectedFlags; 10714 } 10715 10716 if (!isa<SCEVConstant>(YConstOp) || 10717 (YFlagsPresent & ExpectedFlags) != ExpectedFlags) 10718 return false; 10719 10720 if (YNonConstOp != XNonConstOp) 10721 return false; 10722 10723 OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt(); 10724 OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt(); 10725 10726 return true; 10727 }; 10728 10729 APInt C1; 10730 APInt C2; 10731 10732 switch (Pred) { 10733 default: 10734 break; 10735 10736 case ICmpInst::ICMP_SGE: 10737 std::swap(LHS, RHS); 10738 LLVM_FALLTHROUGH; 10739 case ICmpInst::ICMP_SLE: 10740 // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2. 10741 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2)) 10742 return true; 10743 10744 break; 10745 10746 case ICmpInst::ICMP_SGT: 10747 std::swap(LHS, RHS); 10748 LLVM_FALLTHROUGH; 10749 case ICmpInst::ICMP_SLT: 10750 // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2. 10751 if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2)) 10752 return true; 10753 10754 break; 10755 10756 case ICmpInst::ICMP_UGE: 10757 std::swap(LHS, RHS); 10758 LLVM_FALLTHROUGH; 10759 case ICmpInst::ICMP_ULE: 10760 // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2. 10761 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2)) 10762 return true; 10763 10764 break; 10765 10766 case ICmpInst::ICMP_UGT: 10767 std::swap(LHS, RHS); 10768 LLVM_FALLTHROUGH; 10769 case ICmpInst::ICMP_ULT: 10770 // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2. 10771 if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2)) 10772 return true; 10773 break; 10774 } 10775 10776 return false; 10777 } 10778 10779 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 10780 const SCEV *LHS, 10781 const SCEV *RHS) { 10782 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 10783 return false; 10784 10785 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 10786 // the stack can result in exponential time complexity. 10787 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 10788 10789 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 10790 // 10791 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 10792 // isKnownPredicate. isKnownPredicate is more powerful, but also more 10793 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 10794 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 10795 // use isKnownPredicate later if needed. 10796 return isKnownNonNegative(RHS) && 10797 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 10798 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 10799 } 10800 10801 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 10802 ICmpInst::Predicate Pred, 10803 const SCEV *LHS, const SCEV *RHS) { 10804 // No need to even try if we know the module has no guards. 10805 if (!HasGuards) 10806 return false; 10807 10808 return any_of(*BB, [&](const Instruction &I) { 10809 using namespace llvm::PatternMatch; 10810 10811 Value *Condition; 10812 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 10813 m_Value(Condition))) && 10814 isImpliedCond(Pred, LHS, RHS, Condition, false); 10815 }); 10816 } 10817 10818 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 10819 /// protected by a conditional between LHS and RHS. This is used to 10820 /// to eliminate casts. 10821 bool 10822 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 10823 ICmpInst::Predicate Pred, 10824 const SCEV *LHS, const SCEV *RHS) { 10825 // Interpret a null as meaning no loop, where there is obviously no guard 10826 // (interprocedural conditions notwithstanding). 10827 if (!L) return true; 10828 10829 if (VerifyIR) 10830 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 10831 "This cannot be done on broken IR!"); 10832 10833 10834 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 10835 return true; 10836 10837 BasicBlock *Latch = L->getLoopLatch(); 10838 if (!Latch) 10839 return false; 10840 10841 BranchInst *LoopContinuePredicate = 10842 dyn_cast<BranchInst>(Latch->getTerminator()); 10843 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 10844 isImpliedCond(Pred, LHS, RHS, 10845 LoopContinuePredicate->getCondition(), 10846 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 10847 return true; 10848 10849 // We don't want more than one activation of the following loops on the stack 10850 // -- that can lead to O(n!) time complexity. 10851 if (WalkingBEDominatingConds) 10852 return false; 10853 10854 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 10855 10856 // See if we can exploit a trip count to prove the predicate. 10857 const auto &BETakenInfo = getBackedgeTakenInfo(L); 10858 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 10859 if (LatchBECount != getCouldNotCompute()) { 10860 // We know that Latch branches back to the loop header exactly 10861 // LatchBECount times. This means the backdege condition at Latch is 10862 // equivalent to "{0,+,1} u< LatchBECount". 10863 Type *Ty = LatchBECount->getType(); 10864 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 10865 const SCEV *LoopCounter = 10866 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 10867 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 10868 LatchBECount)) 10869 return true; 10870 } 10871 10872 // Check conditions due to any @llvm.assume intrinsics. 10873 for (auto &AssumeVH : AC.assumptions()) { 10874 if (!AssumeVH) 10875 continue; 10876 auto *CI = cast<CallInst>(AssumeVH); 10877 if (!DT.dominates(CI, Latch->getTerminator())) 10878 continue; 10879 10880 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 10881 return true; 10882 } 10883 10884 // If the loop is not reachable from the entry block, we risk running into an 10885 // infinite loop as we walk up into the dom tree. These loops do not matter 10886 // anyway, so we just return a conservative answer when we see them. 10887 if (!DT.isReachableFromEntry(L->getHeader())) 10888 return false; 10889 10890 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 10891 return true; 10892 10893 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 10894 DTN != HeaderDTN; DTN = DTN->getIDom()) { 10895 assert(DTN && "should reach the loop header before reaching the root!"); 10896 10897 BasicBlock *BB = DTN->getBlock(); 10898 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 10899 return true; 10900 10901 BasicBlock *PBB = BB->getSinglePredecessor(); 10902 if (!PBB) 10903 continue; 10904 10905 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 10906 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 10907 continue; 10908 10909 Value *Condition = ContinuePredicate->getCondition(); 10910 10911 // If we have an edge `E` within the loop body that dominates the only 10912 // latch, the condition guarding `E` also guards the backedge. This 10913 // reasoning works only for loops with a single latch. 10914 10915 BasicBlockEdge DominatingEdge(PBB, BB); 10916 if (DominatingEdge.isSingleEdge()) { 10917 // We're constructively (and conservatively) enumerating edges within the 10918 // loop body that dominate the latch. The dominator tree better agree 10919 // with us on this: 10920 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 10921 10922 if (isImpliedCond(Pred, LHS, RHS, Condition, 10923 BB != ContinuePredicate->getSuccessor(0))) 10924 return true; 10925 } 10926 } 10927 10928 return false; 10929 } 10930 10931 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 10932 ICmpInst::Predicate Pred, 10933 const SCEV *LHS, 10934 const SCEV *RHS) { 10935 if (VerifyIR) 10936 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 10937 "This cannot be done on broken IR!"); 10938 10939 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 10940 // the facts (a >= b && a != b) separately. A typical situation is when the 10941 // non-strict comparison is known from ranges and non-equality is known from 10942 // dominating predicates. If we are proving strict comparison, we always try 10943 // to prove non-equality and non-strict comparison separately. 10944 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 10945 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 10946 bool ProvedNonStrictComparison = false; 10947 bool ProvedNonEquality = false; 10948 10949 auto SplitAndProve = 10950 [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool { 10951 if (!ProvedNonStrictComparison) 10952 ProvedNonStrictComparison = Fn(NonStrictPredicate); 10953 if (!ProvedNonEquality) 10954 ProvedNonEquality = Fn(ICmpInst::ICMP_NE); 10955 if (ProvedNonStrictComparison && ProvedNonEquality) 10956 return true; 10957 return false; 10958 }; 10959 10960 if (ProvingStrictComparison) { 10961 auto ProofFn = [&](ICmpInst::Predicate P) { 10962 return isKnownViaNonRecursiveReasoning(P, LHS, RHS); 10963 }; 10964 if (SplitAndProve(ProofFn)) 10965 return true; 10966 } 10967 10968 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 10969 auto ProveViaGuard = [&](const BasicBlock *Block) { 10970 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 10971 return true; 10972 if (ProvingStrictComparison) { 10973 auto ProofFn = [&](ICmpInst::Predicate P) { 10974 return isImpliedViaGuard(Block, P, LHS, RHS); 10975 }; 10976 if (SplitAndProve(ProofFn)) 10977 return true; 10978 } 10979 return false; 10980 }; 10981 10982 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 10983 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 10984 const Instruction *CtxI = &BB->front(); 10985 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI)) 10986 return true; 10987 if (ProvingStrictComparison) { 10988 auto ProofFn = [&](ICmpInst::Predicate P) { 10989 return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI); 10990 }; 10991 if (SplitAndProve(ProofFn)) 10992 return true; 10993 } 10994 return false; 10995 }; 10996 10997 // Starting at the block's predecessor, climb up the predecessor chain, as long 10998 // as there are predecessors that can be found that have unique successors 10999 // leading to the original block. 11000 const Loop *ContainingLoop = LI.getLoopFor(BB); 11001 const BasicBlock *PredBB; 11002 if (ContainingLoop && ContainingLoop->getHeader() == BB) 11003 PredBB = ContainingLoop->getLoopPredecessor(); 11004 else 11005 PredBB = BB->getSinglePredecessor(); 11006 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 11007 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 11008 if (ProveViaGuard(Pair.first)) 11009 return true; 11010 11011 const BranchInst *LoopEntryPredicate = 11012 dyn_cast<BranchInst>(Pair.first->getTerminator()); 11013 if (!LoopEntryPredicate || 11014 LoopEntryPredicate->isUnconditional()) 11015 continue; 11016 11017 if (ProveViaCond(LoopEntryPredicate->getCondition(), 11018 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 11019 return true; 11020 } 11021 11022 // Check conditions due to any @llvm.assume intrinsics. 11023 for (auto &AssumeVH : AC.assumptions()) { 11024 if (!AssumeVH) 11025 continue; 11026 auto *CI = cast<CallInst>(AssumeVH); 11027 if (!DT.dominates(CI, BB)) 11028 continue; 11029 11030 if (ProveViaCond(CI->getArgOperand(0), false)) 11031 return true; 11032 } 11033 11034 return false; 11035 } 11036 11037 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 11038 ICmpInst::Predicate Pred, 11039 const SCEV *LHS, 11040 const SCEV *RHS) { 11041 // Interpret a null as meaning no loop, where there is obviously no guard 11042 // (interprocedural conditions notwithstanding). 11043 if (!L) 11044 return false; 11045 11046 // Both LHS and RHS must be available at loop entry. 11047 assert(isAvailableAtLoopEntry(LHS, L) && 11048 "LHS is not available at Loop Entry"); 11049 assert(isAvailableAtLoopEntry(RHS, L) && 11050 "RHS is not available at Loop Entry"); 11051 11052 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 11053 return true; 11054 11055 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 11056 } 11057 11058 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 11059 const SCEV *RHS, 11060 const Value *FoundCondValue, bool Inverse, 11061 const Instruction *CtxI) { 11062 // False conditions implies anything. Do not bother analyzing it further. 11063 if (FoundCondValue == 11064 ConstantInt::getBool(FoundCondValue->getContext(), Inverse)) 11065 return true; 11066 11067 if (!PendingLoopPredicates.insert(FoundCondValue).second) 11068 return false; 11069 11070 auto ClearOnExit = 11071 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 11072 11073 // Recursively handle And and Or conditions. 11074 const Value *Op0, *Op1; 11075 if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) { 11076 if (!Inverse) 11077 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 11078 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 11079 } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) { 11080 if (Inverse) 11081 return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) || 11082 isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI); 11083 } 11084 11085 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 11086 if (!ICI) return false; 11087 11088 // Now that we found a conditional branch that dominates the loop or controls 11089 // the loop latch. Check to see if it is the comparison we are looking for. 11090 ICmpInst::Predicate FoundPred; 11091 if (Inverse) 11092 FoundPred = ICI->getInversePredicate(); 11093 else 11094 FoundPred = ICI->getPredicate(); 11095 11096 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 11097 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 11098 11099 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI); 11100 } 11101 11102 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 11103 const SCEV *RHS, 11104 ICmpInst::Predicate FoundPred, 11105 const SCEV *FoundLHS, const SCEV *FoundRHS, 11106 const Instruction *CtxI) { 11107 // Balance the types. 11108 if (getTypeSizeInBits(LHS->getType()) < 11109 getTypeSizeInBits(FoundLHS->getType())) { 11110 // For unsigned and equality predicates, try to prove that both found 11111 // operands fit into narrow unsigned range. If so, try to prove facts in 11112 // narrow types. 11113 if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() && 11114 !FoundRHS->getType()->isPointerTy()) { 11115 auto *NarrowType = LHS->getType(); 11116 auto *WideType = FoundLHS->getType(); 11117 auto BitWidth = getTypeSizeInBits(NarrowType); 11118 const SCEV *MaxValue = getZeroExtendExpr( 11119 getConstant(APInt::getMaxValue(BitWidth)), WideType); 11120 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS, 11121 MaxValue) && 11122 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS, 11123 MaxValue)) { 11124 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 11125 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 11126 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 11127 TruncFoundRHS, CtxI)) 11128 return true; 11129 } 11130 } 11131 11132 if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy()) 11133 return false; 11134 if (CmpInst::isSigned(Pred)) { 11135 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 11136 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 11137 } else { 11138 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 11139 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 11140 } 11141 } else if (getTypeSizeInBits(LHS->getType()) > 11142 getTypeSizeInBits(FoundLHS->getType())) { 11143 if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy()) 11144 return false; 11145 if (CmpInst::isSigned(FoundPred)) { 11146 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 11147 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 11148 } else { 11149 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 11150 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 11151 } 11152 } 11153 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 11154 FoundRHS, CtxI); 11155 } 11156 11157 bool ScalarEvolution::isImpliedCondBalancedTypes( 11158 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11159 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 11160 const Instruction *CtxI) { 11161 assert(getTypeSizeInBits(LHS->getType()) == 11162 getTypeSizeInBits(FoundLHS->getType()) && 11163 "Types should be balanced!"); 11164 // Canonicalize the query to match the way instcombine will have 11165 // canonicalized the comparison. 11166 if (SimplifyICmpOperands(Pred, LHS, RHS)) 11167 if (LHS == RHS) 11168 return CmpInst::isTrueWhenEqual(Pred); 11169 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 11170 if (FoundLHS == FoundRHS) 11171 return CmpInst::isFalseWhenEqual(FoundPred); 11172 11173 // Check to see if we can make the LHS or RHS match. 11174 if (LHS == FoundRHS || RHS == FoundLHS) { 11175 if (isa<SCEVConstant>(RHS)) { 11176 std::swap(FoundLHS, FoundRHS); 11177 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 11178 } else { 11179 std::swap(LHS, RHS); 11180 Pred = ICmpInst::getSwappedPredicate(Pred); 11181 } 11182 } 11183 11184 // Check whether the found predicate is the same as the desired predicate. 11185 if (FoundPred == Pred) 11186 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 11187 11188 // Check whether swapping the found predicate makes it the same as the 11189 // desired predicate. 11190 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 11191 // We can write the implication 11192 // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS 11193 // using one of the following ways: 11194 // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS 11195 // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS 11196 // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS 11197 // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS 11198 // Forms 1. and 2. require swapping the operands of one condition. Don't 11199 // do this if it would break canonical constant/addrec ordering. 11200 if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS)) 11201 return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS, 11202 CtxI); 11203 if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS)) 11204 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI); 11205 11206 // There's no clear preference between forms 3. and 4., try both. Avoid 11207 // forming getNotSCEV of pointer values as the resulting subtract is 11208 // not legal. 11209 if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() && 11210 isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS), 11211 FoundLHS, FoundRHS, CtxI)) 11212 return true; 11213 11214 if (!FoundLHS->getType()->isPointerTy() && 11215 !FoundRHS->getType()->isPointerTy() && 11216 isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS), 11217 getNotSCEV(FoundRHS), CtxI)) 11218 return true; 11219 11220 return false; 11221 } 11222 11223 auto IsSignFlippedPredicate = [](CmpInst::Predicate P1, 11224 CmpInst::Predicate P2) { 11225 assert(P1 != P2 && "Handled earlier!"); 11226 return CmpInst::isRelational(P2) && 11227 P1 == CmpInst::getFlippedSignednessPredicate(P2); 11228 }; 11229 if (IsSignFlippedPredicate(Pred, FoundPred)) { 11230 // Unsigned comparison is the same as signed comparison when both the 11231 // operands are non-negative or negative. 11232 if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) || 11233 (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS))) 11234 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI); 11235 // Create local copies that we can freely swap and canonicalize our 11236 // conditions to "le/lt". 11237 ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred; 11238 const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS, 11239 *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS; 11240 if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) { 11241 CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred); 11242 CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred); 11243 std::swap(CanonicalLHS, CanonicalRHS); 11244 std::swap(CanonicalFoundLHS, CanonicalFoundRHS); 11245 } 11246 assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) && 11247 "Must be!"); 11248 assert((ICmpInst::isLT(CanonicalFoundPred) || 11249 ICmpInst::isLE(CanonicalFoundPred)) && 11250 "Must be!"); 11251 if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS)) 11252 // Use implication: 11253 // x <u y && y >=s 0 --> x <s y. 11254 // If we can prove the left part, the right part is also proven. 11255 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11256 CanonicalRHS, CanonicalFoundLHS, 11257 CanonicalFoundRHS); 11258 if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS)) 11259 // Use implication: 11260 // x <s y && y <s 0 --> x <u y. 11261 // If we can prove the left part, the right part is also proven. 11262 return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS, 11263 CanonicalRHS, CanonicalFoundLHS, 11264 CanonicalFoundRHS); 11265 } 11266 11267 // Check if we can make progress by sharpening ranges. 11268 if (FoundPred == ICmpInst::ICMP_NE && 11269 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 11270 11271 const SCEVConstant *C = nullptr; 11272 const SCEV *V = nullptr; 11273 11274 if (isa<SCEVConstant>(FoundLHS)) { 11275 C = cast<SCEVConstant>(FoundLHS); 11276 V = FoundRHS; 11277 } else { 11278 C = cast<SCEVConstant>(FoundRHS); 11279 V = FoundLHS; 11280 } 11281 11282 // The guarding predicate tells us that C != V. If the known range 11283 // of V is [C, t), we can sharpen the range to [C + 1, t). The 11284 // range we consider has to correspond to same signedness as the 11285 // predicate we're interested in folding. 11286 11287 APInt Min = ICmpInst::isSigned(Pred) ? 11288 getSignedRangeMin(V) : getUnsignedRangeMin(V); 11289 11290 if (Min == C->getAPInt()) { 11291 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 11292 // This is true even if (Min + 1) wraps around -- in case of 11293 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 11294 11295 APInt SharperMin = Min + 1; 11296 11297 switch (Pred) { 11298 case ICmpInst::ICMP_SGE: 11299 case ICmpInst::ICMP_UGE: 11300 // We know V `Pred` SharperMin. If this implies LHS `Pred` 11301 // RHS, we're done. 11302 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 11303 CtxI)) 11304 return true; 11305 LLVM_FALLTHROUGH; 11306 11307 case ICmpInst::ICMP_SGT: 11308 case ICmpInst::ICMP_UGT: 11309 // We know from the range information that (V `Pred` Min || 11310 // V == Min). We know from the guarding condition that !(V 11311 // == Min). This gives us 11312 // 11313 // V `Pred` Min || V == Min && !(V == Min) 11314 // => V `Pred` Min 11315 // 11316 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 11317 11318 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI)) 11319 return true; 11320 break; 11321 11322 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 11323 case ICmpInst::ICMP_SLE: 11324 case ICmpInst::ICMP_ULE: 11325 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11326 LHS, V, getConstant(SharperMin), CtxI)) 11327 return true; 11328 LLVM_FALLTHROUGH; 11329 11330 case ICmpInst::ICMP_SLT: 11331 case ICmpInst::ICMP_ULT: 11332 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 11333 LHS, V, getConstant(Min), CtxI)) 11334 return true; 11335 break; 11336 11337 default: 11338 // No change 11339 break; 11340 } 11341 } 11342 } 11343 11344 // Check whether the actual condition is beyond sufficient. 11345 if (FoundPred == ICmpInst::ICMP_EQ) 11346 if (ICmpInst::isTrueWhenEqual(Pred)) 11347 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11348 return true; 11349 if (Pred == ICmpInst::ICMP_NE) 11350 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 11351 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI)) 11352 return true; 11353 11354 // Otherwise assume the worst. 11355 return false; 11356 } 11357 11358 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 11359 const SCEV *&L, const SCEV *&R, 11360 SCEV::NoWrapFlags &Flags) { 11361 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 11362 if (!AE || AE->getNumOperands() != 2) 11363 return false; 11364 11365 L = AE->getOperand(0); 11366 R = AE->getOperand(1); 11367 Flags = AE->getNoWrapFlags(); 11368 return true; 11369 } 11370 11371 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 11372 const SCEV *Less) { 11373 // We avoid subtracting expressions here because this function is usually 11374 // fairly deep in the call stack (i.e. is called many times). 11375 11376 // X - X = 0. 11377 if (More == Less) 11378 return APInt(getTypeSizeInBits(More->getType()), 0); 11379 11380 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 11381 const auto *LAR = cast<SCEVAddRecExpr>(Less); 11382 const auto *MAR = cast<SCEVAddRecExpr>(More); 11383 11384 if (LAR->getLoop() != MAR->getLoop()) 11385 return None; 11386 11387 // We look at affine expressions only; not for correctness but to keep 11388 // getStepRecurrence cheap. 11389 if (!LAR->isAffine() || !MAR->isAffine()) 11390 return None; 11391 11392 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 11393 return None; 11394 11395 Less = LAR->getStart(); 11396 More = MAR->getStart(); 11397 11398 // fall through 11399 } 11400 11401 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 11402 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 11403 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 11404 return M - L; 11405 } 11406 11407 SCEV::NoWrapFlags Flags; 11408 const SCEV *LLess = nullptr, *RLess = nullptr; 11409 const SCEV *LMore = nullptr, *RMore = nullptr; 11410 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 11411 // Compare (X + C1) vs X. 11412 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 11413 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 11414 if (RLess == More) 11415 return -(C1->getAPInt()); 11416 11417 // Compare X vs (X + C2). 11418 if (splitBinaryAdd(More, LMore, RMore, Flags)) 11419 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 11420 if (RMore == Less) 11421 return C2->getAPInt(); 11422 11423 // Compare (X + C1) vs (X + C2). 11424 if (C1 && C2 && RLess == RMore) 11425 return C2->getAPInt() - C1->getAPInt(); 11426 11427 return None; 11428 } 11429 11430 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 11431 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11432 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) { 11433 // Try to recognize the following pattern: 11434 // 11435 // FoundRHS = ... 11436 // ... 11437 // loop: 11438 // FoundLHS = {Start,+,W} 11439 // context_bb: // Basic block from the same loop 11440 // known(Pred, FoundLHS, FoundRHS) 11441 // 11442 // If some predicate is known in the context of a loop, it is also known on 11443 // each iteration of this loop, including the first iteration. Therefore, in 11444 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 11445 // prove the original pred using this fact. 11446 if (!CtxI) 11447 return false; 11448 const BasicBlock *ContextBB = CtxI->getParent(); 11449 // Make sure AR varies in the context block. 11450 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 11451 const Loop *L = AR->getLoop(); 11452 // Make sure that context belongs to the loop and executes on 1st iteration 11453 // (if it ever executes at all). 11454 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11455 return false; 11456 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 11457 return false; 11458 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 11459 } 11460 11461 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 11462 const Loop *L = AR->getLoop(); 11463 // Make sure that context belongs to the loop and executes on 1st iteration 11464 // (if it ever executes at all). 11465 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 11466 return false; 11467 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 11468 return false; 11469 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 11470 } 11471 11472 return false; 11473 } 11474 11475 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 11476 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 11477 const SCEV *FoundLHS, const SCEV *FoundRHS) { 11478 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 11479 return false; 11480 11481 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 11482 if (!AddRecLHS) 11483 return false; 11484 11485 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 11486 if (!AddRecFoundLHS) 11487 return false; 11488 11489 // We'd like to let SCEV reason about control dependencies, so we constrain 11490 // both the inequalities to be about add recurrences on the same loop. This 11491 // way we can use isLoopEntryGuardedByCond later. 11492 11493 const Loop *L = AddRecFoundLHS->getLoop(); 11494 if (L != AddRecLHS->getLoop()) 11495 return false; 11496 11497 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 11498 // 11499 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 11500 // ... (2) 11501 // 11502 // Informal proof for (2), assuming (1) [*]: 11503 // 11504 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 11505 // 11506 // Then 11507 // 11508 // FoundLHS s< FoundRHS s< INT_MIN - C 11509 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 11510 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 11511 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 11512 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 11513 // <=> FoundLHS + C s< FoundRHS + C 11514 // 11515 // [*]: (1) can be proved by ruling out overflow. 11516 // 11517 // [**]: This can be proved by analyzing all the four possibilities: 11518 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 11519 // (A s>= 0, B s>= 0). 11520 // 11521 // Note: 11522 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 11523 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 11524 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 11525 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 11526 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 11527 // C)". 11528 11529 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 11530 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 11531 if (!LDiff || !RDiff || *LDiff != *RDiff) 11532 return false; 11533 11534 if (LDiff->isMinValue()) 11535 return true; 11536 11537 APInt FoundRHSLimit; 11538 11539 if (Pred == CmpInst::ICMP_ULT) { 11540 FoundRHSLimit = -(*RDiff); 11541 } else { 11542 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 11543 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 11544 } 11545 11546 // Try to prove (1) or (2), as needed. 11547 return isAvailableAtLoopEntry(FoundRHS, L) && 11548 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 11549 getConstant(FoundRHSLimit)); 11550 } 11551 11552 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 11553 const SCEV *LHS, const SCEV *RHS, 11554 const SCEV *FoundLHS, 11555 const SCEV *FoundRHS, unsigned Depth) { 11556 const PHINode *LPhi = nullptr, *RPhi = nullptr; 11557 11558 auto ClearOnExit = make_scope_exit([&]() { 11559 if (LPhi) { 11560 bool Erased = PendingMerges.erase(LPhi); 11561 assert(Erased && "Failed to erase LPhi!"); 11562 (void)Erased; 11563 } 11564 if (RPhi) { 11565 bool Erased = PendingMerges.erase(RPhi); 11566 assert(Erased && "Failed to erase RPhi!"); 11567 (void)Erased; 11568 } 11569 }); 11570 11571 // Find respective Phis and check that they are not being pending. 11572 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 11573 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 11574 if (!PendingMerges.insert(Phi).second) 11575 return false; 11576 LPhi = Phi; 11577 } 11578 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 11579 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 11580 // If we detect a loop of Phi nodes being processed by this method, for 11581 // example: 11582 // 11583 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 11584 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 11585 // 11586 // we don't want to deal with a case that complex, so return conservative 11587 // answer false. 11588 if (!PendingMerges.insert(Phi).second) 11589 return false; 11590 RPhi = Phi; 11591 } 11592 11593 // If none of LHS, RHS is a Phi, nothing to do here. 11594 if (!LPhi && !RPhi) 11595 return false; 11596 11597 // If there is a SCEVUnknown Phi we are interested in, make it left. 11598 if (!LPhi) { 11599 std::swap(LHS, RHS); 11600 std::swap(FoundLHS, FoundRHS); 11601 std::swap(LPhi, RPhi); 11602 Pred = ICmpInst::getSwappedPredicate(Pred); 11603 } 11604 11605 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 11606 const BasicBlock *LBB = LPhi->getParent(); 11607 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11608 11609 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 11610 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 11611 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 11612 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 11613 }; 11614 11615 if (RPhi && RPhi->getParent() == LBB) { 11616 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 11617 // If we compare two Phis from the same block, and for each entry block 11618 // the predicate is true for incoming values from this block, then the 11619 // predicate is also true for the Phis. 11620 for (const BasicBlock *IncBB : predecessors(LBB)) { 11621 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11622 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 11623 if (!ProvedEasily(L, R)) 11624 return false; 11625 } 11626 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 11627 // Case two: RHS is also a Phi from the same basic block, and it is an 11628 // AddRec. It means that there is a loop which has both AddRec and Unknown 11629 // PHIs, for it we can compare incoming values of AddRec from above the loop 11630 // and latch with their respective incoming values of LPhi. 11631 // TODO: Generalize to handle loops with many inputs in a header. 11632 if (LPhi->getNumIncomingValues() != 2) return false; 11633 11634 auto *RLoop = RAR->getLoop(); 11635 auto *Predecessor = RLoop->getLoopPredecessor(); 11636 assert(Predecessor && "Loop with AddRec with no predecessor?"); 11637 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 11638 if (!ProvedEasily(L1, RAR->getStart())) 11639 return false; 11640 auto *Latch = RLoop->getLoopLatch(); 11641 assert(Latch && "Loop with AddRec with no latch?"); 11642 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 11643 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 11644 return false; 11645 } else { 11646 // In all other cases go over inputs of LHS and compare each of them to RHS, 11647 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 11648 // At this point RHS is either a non-Phi, or it is a Phi from some block 11649 // different from LBB. 11650 for (const BasicBlock *IncBB : predecessors(LBB)) { 11651 // Check that RHS is available in this block. 11652 if (!dominates(RHS, IncBB)) 11653 return false; 11654 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 11655 // Make sure L does not refer to a value from a potentially previous 11656 // iteration of a loop. 11657 if (!properlyDominates(L, IncBB)) 11658 return false; 11659 if (!ProvedEasily(L, RHS)) 11660 return false; 11661 } 11662 } 11663 return true; 11664 } 11665 11666 bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred, 11667 const SCEV *LHS, 11668 const SCEV *RHS, 11669 const SCEV *FoundLHS, 11670 const SCEV *FoundRHS) { 11671 // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make 11672 // sure that we are dealing with same LHS. 11673 if (RHS == FoundRHS) { 11674 std::swap(LHS, RHS); 11675 std::swap(FoundLHS, FoundRHS); 11676 Pred = ICmpInst::getSwappedPredicate(Pred); 11677 } 11678 if (LHS != FoundLHS) 11679 return false; 11680 11681 auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS); 11682 if (!SUFoundRHS) 11683 return false; 11684 11685 Value *Shiftee, *ShiftValue; 11686 11687 using namespace PatternMatch; 11688 if (match(SUFoundRHS->getValue(), 11689 m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) { 11690 auto *ShifteeS = getSCEV(Shiftee); 11691 // Prove one of the following: 11692 // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS 11693 // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS 11694 // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0 11695 // ---> LHS <s RHS 11696 // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0 11697 // ---> LHS <=s RHS 11698 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) 11699 return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS); 11700 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) 11701 if (isKnownNonNegative(ShifteeS)) 11702 return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS); 11703 } 11704 11705 return false; 11706 } 11707 11708 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 11709 const SCEV *LHS, const SCEV *RHS, 11710 const SCEV *FoundLHS, 11711 const SCEV *FoundRHS, 11712 const Instruction *CtxI) { 11713 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11714 return true; 11715 11716 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11717 return true; 11718 11719 if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS)) 11720 return true; 11721 11722 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 11723 CtxI)) 11724 return true; 11725 11726 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 11727 FoundLHS, FoundRHS); 11728 } 11729 11730 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 11731 template <typename MinMaxExprType> 11732 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 11733 const SCEV *Candidate) { 11734 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 11735 if (!MinMaxExpr) 11736 return false; 11737 11738 return is_contained(MinMaxExpr->operands(), Candidate); 11739 } 11740 11741 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 11742 ICmpInst::Predicate Pred, 11743 const SCEV *LHS, const SCEV *RHS) { 11744 // If both sides are affine addrecs for the same loop, with equal 11745 // steps, and we know the recurrences don't wrap, then we only 11746 // need to check the predicate on the starting values. 11747 11748 if (!ICmpInst::isRelational(Pred)) 11749 return false; 11750 11751 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 11752 if (!LAR) 11753 return false; 11754 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 11755 if (!RAR) 11756 return false; 11757 if (LAR->getLoop() != RAR->getLoop()) 11758 return false; 11759 if (!LAR->isAffine() || !RAR->isAffine()) 11760 return false; 11761 11762 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 11763 return false; 11764 11765 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 11766 SCEV::FlagNSW : SCEV::FlagNUW; 11767 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 11768 return false; 11769 11770 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 11771 } 11772 11773 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 11774 /// expression? 11775 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 11776 ICmpInst::Predicate Pred, 11777 const SCEV *LHS, const SCEV *RHS) { 11778 switch (Pred) { 11779 default: 11780 return false; 11781 11782 case ICmpInst::ICMP_SGE: 11783 std::swap(LHS, RHS); 11784 LLVM_FALLTHROUGH; 11785 case ICmpInst::ICMP_SLE: 11786 return 11787 // min(A, ...) <= A 11788 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 11789 // A <= max(A, ...) 11790 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 11791 11792 case ICmpInst::ICMP_UGE: 11793 std::swap(LHS, RHS); 11794 LLVM_FALLTHROUGH; 11795 case ICmpInst::ICMP_ULE: 11796 return 11797 // min(A, ...) <= A 11798 // FIXME: what about umin_seq? 11799 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 11800 // A <= max(A, ...) 11801 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 11802 } 11803 11804 llvm_unreachable("covered switch fell through?!"); 11805 } 11806 11807 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 11808 const SCEV *LHS, const SCEV *RHS, 11809 const SCEV *FoundLHS, 11810 const SCEV *FoundRHS, 11811 unsigned Depth) { 11812 assert(getTypeSizeInBits(LHS->getType()) == 11813 getTypeSizeInBits(RHS->getType()) && 11814 "LHS and RHS have different sizes?"); 11815 assert(getTypeSizeInBits(FoundLHS->getType()) == 11816 getTypeSizeInBits(FoundRHS->getType()) && 11817 "FoundLHS and FoundRHS have different sizes?"); 11818 // We want to avoid hurting the compile time with analysis of too big trees. 11819 if (Depth > MaxSCEVOperationsImplicationDepth) 11820 return false; 11821 11822 // We only want to work with GT comparison so far. 11823 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 11824 Pred = CmpInst::getSwappedPredicate(Pred); 11825 std::swap(LHS, RHS); 11826 std::swap(FoundLHS, FoundRHS); 11827 } 11828 11829 // For unsigned, try to reduce it to corresponding signed comparison. 11830 if (Pred == ICmpInst::ICMP_UGT) 11831 // We can replace unsigned predicate with its signed counterpart if all 11832 // involved values are non-negative. 11833 // TODO: We could have better support for unsigned. 11834 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 11835 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 11836 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 11837 // use this fact to prove that LHS and RHS are non-negative. 11838 const SCEV *MinusOne = getMinusOne(LHS->getType()); 11839 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 11840 FoundRHS) && 11841 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 11842 FoundRHS)) 11843 Pred = ICmpInst::ICMP_SGT; 11844 } 11845 11846 if (Pred != ICmpInst::ICMP_SGT) 11847 return false; 11848 11849 auto GetOpFromSExt = [&](const SCEV *S) { 11850 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 11851 return Ext->getOperand(); 11852 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 11853 // the constant in some cases. 11854 return S; 11855 }; 11856 11857 // Acquire values from extensions. 11858 auto *OrigLHS = LHS; 11859 auto *OrigFoundLHS = FoundLHS; 11860 LHS = GetOpFromSExt(LHS); 11861 FoundLHS = GetOpFromSExt(FoundLHS); 11862 11863 // Is the SGT predicate can be proved trivially or using the found context. 11864 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 11865 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 11866 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 11867 FoundRHS, Depth + 1); 11868 }; 11869 11870 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 11871 // We want to avoid creation of any new non-constant SCEV. Since we are 11872 // going to compare the operands to RHS, we should be certain that we don't 11873 // need any size extensions for this. So let's decline all cases when the 11874 // sizes of types of LHS and RHS do not match. 11875 // TODO: Maybe try to get RHS from sext to catch more cases? 11876 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 11877 return false; 11878 11879 // Should not overflow. 11880 if (!LHSAddExpr->hasNoSignedWrap()) 11881 return false; 11882 11883 auto *LL = LHSAddExpr->getOperand(0); 11884 auto *LR = LHSAddExpr->getOperand(1); 11885 auto *MinusOne = getMinusOne(RHS->getType()); 11886 11887 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 11888 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 11889 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 11890 }; 11891 // Try to prove the following rule: 11892 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 11893 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 11894 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 11895 return true; 11896 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 11897 Value *LL, *LR; 11898 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 11899 11900 using namespace llvm::PatternMatch; 11901 11902 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 11903 // Rules for division. 11904 // We are going to perform some comparisons with Denominator and its 11905 // derivative expressions. In general case, creating a SCEV for it may 11906 // lead to a complex analysis of the entire graph, and in particular it 11907 // can request trip count recalculation for the same loop. This would 11908 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 11909 // this, we only want to create SCEVs that are constants in this section. 11910 // So we bail if Denominator is not a constant. 11911 if (!isa<ConstantInt>(LR)) 11912 return false; 11913 11914 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 11915 11916 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 11917 // then a SCEV for the numerator already exists and matches with FoundLHS. 11918 auto *Numerator = getExistingSCEV(LL); 11919 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 11920 return false; 11921 11922 // Make sure that the numerator matches with FoundLHS and the denominator 11923 // is positive. 11924 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 11925 return false; 11926 11927 auto *DTy = Denominator->getType(); 11928 auto *FRHSTy = FoundRHS->getType(); 11929 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 11930 // One of types is a pointer and another one is not. We cannot extend 11931 // them properly to a wider type, so let us just reject this case. 11932 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 11933 // to avoid this check. 11934 return false; 11935 11936 // Given that: 11937 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 11938 auto *WTy = getWiderType(DTy, FRHSTy); 11939 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 11940 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 11941 11942 // Try to prove the following rule: 11943 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 11944 // For example, given that FoundLHS > 2. It means that FoundLHS is at 11945 // least 3. If we divide it by Denominator < 4, we will have at least 1. 11946 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 11947 if (isKnownNonPositive(RHS) && 11948 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 11949 return true; 11950 11951 // Try to prove the following rule: 11952 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 11953 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 11954 // If we divide it by Denominator > 2, then: 11955 // 1. If FoundLHS is negative, then the result is 0. 11956 // 2. If FoundLHS is non-negative, then the result is non-negative. 11957 // Anyways, the result is non-negative. 11958 auto *MinusOne = getMinusOne(WTy); 11959 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 11960 if (isKnownNegative(RHS) && 11961 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 11962 return true; 11963 } 11964 } 11965 11966 // If our expression contained SCEVUnknown Phis, and we split it down and now 11967 // need to prove something for them, try to prove the predicate for every 11968 // possible incoming values of those Phis. 11969 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 11970 return true; 11971 11972 return false; 11973 } 11974 11975 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 11976 const SCEV *LHS, const SCEV *RHS) { 11977 // zext x u<= sext x, sext x s<= zext x 11978 switch (Pred) { 11979 case ICmpInst::ICMP_SGE: 11980 std::swap(LHS, RHS); 11981 LLVM_FALLTHROUGH; 11982 case ICmpInst::ICMP_SLE: { 11983 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 11984 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 11985 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 11986 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11987 return true; 11988 break; 11989 } 11990 case ICmpInst::ICMP_UGE: 11991 std::swap(LHS, RHS); 11992 LLVM_FALLTHROUGH; 11993 case ICmpInst::ICMP_ULE: { 11994 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 11995 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 11996 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 11997 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 11998 return true; 11999 break; 12000 } 12001 default: 12002 break; 12003 }; 12004 return false; 12005 } 12006 12007 bool 12008 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 12009 const SCEV *LHS, const SCEV *RHS) { 12010 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 12011 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 12012 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 12013 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 12014 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 12015 } 12016 12017 bool 12018 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 12019 const SCEV *LHS, const SCEV *RHS, 12020 const SCEV *FoundLHS, 12021 const SCEV *FoundRHS) { 12022 switch (Pred) { 12023 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 12024 case ICmpInst::ICMP_EQ: 12025 case ICmpInst::ICMP_NE: 12026 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 12027 return true; 12028 break; 12029 case ICmpInst::ICMP_SLT: 12030 case ICmpInst::ICMP_SLE: 12031 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 12032 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 12033 return true; 12034 break; 12035 case ICmpInst::ICMP_SGT: 12036 case ICmpInst::ICMP_SGE: 12037 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 12038 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 12039 return true; 12040 break; 12041 case ICmpInst::ICMP_ULT: 12042 case ICmpInst::ICMP_ULE: 12043 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 12044 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 12045 return true; 12046 break; 12047 case ICmpInst::ICMP_UGT: 12048 case ICmpInst::ICMP_UGE: 12049 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 12050 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 12051 return true; 12052 break; 12053 } 12054 12055 // Maybe it can be proved via operations? 12056 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 12057 return true; 12058 12059 return false; 12060 } 12061 12062 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 12063 const SCEV *LHS, 12064 const SCEV *RHS, 12065 const SCEV *FoundLHS, 12066 const SCEV *FoundRHS) { 12067 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 12068 // The restriction on `FoundRHS` be lifted easily -- it exists only to 12069 // reduce the compile time impact of this optimization. 12070 return false; 12071 12072 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 12073 if (!Addend) 12074 return false; 12075 12076 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 12077 12078 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 12079 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 12080 ConstantRange FoundLHSRange = 12081 ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS); 12082 12083 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 12084 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 12085 12086 // We can also compute the range of values for `LHS` that satisfy the 12087 // consequent, "`LHS` `Pred` `RHS`": 12088 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 12089 // The antecedent implies the consequent if every value of `LHS` that 12090 // satisfies the antecedent also satisfies the consequent. 12091 return LHSRange.icmp(Pred, ConstRHS); 12092 } 12093 12094 bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 12095 bool IsSigned) { 12096 assert(isKnownPositive(Stride) && "Positive stride expected!"); 12097 12098 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 12099 const SCEV *One = getOne(Stride->getType()); 12100 12101 if (IsSigned) { 12102 APInt MaxRHS = getSignedRangeMax(RHS); 12103 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 12104 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 12105 12106 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 12107 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 12108 } 12109 12110 APInt MaxRHS = getUnsignedRangeMax(RHS); 12111 APInt MaxValue = APInt::getMaxValue(BitWidth); 12112 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 12113 12114 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 12115 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 12116 } 12117 12118 bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 12119 bool IsSigned) { 12120 12121 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 12122 const SCEV *One = getOne(Stride->getType()); 12123 12124 if (IsSigned) { 12125 APInt MinRHS = getSignedRangeMin(RHS); 12126 APInt MinValue = APInt::getSignedMinValue(BitWidth); 12127 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 12128 12129 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 12130 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 12131 } 12132 12133 APInt MinRHS = getUnsignedRangeMin(RHS); 12134 APInt MinValue = APInt::getMinValue(BitWidth); 12135 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 12136 12137 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 12138 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 12139 } 12140 12141 const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) { 12142 // umin(N, 1) + floor((N - umin(N, 1)) / D) 12143 // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin 12144 // expression fixes the case of N=0. 12145 const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType())); 12146 const SCEV *NMinusOne = getMinusSCEV(N, MinNOne); 12147 return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D)); 12148 } 12149 12150 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 12151 const SCEV *Stride, 12152 const SCEV *End, 12153 unsigned BitWidth, 12154 bool IsSigned) { 12155 // The logic in this function assumes we can represent a positive stride. 12156 // If we can't, the backedge-taken count must be zero. 12157 if (IsSigned && BitWidth == 1) 12158 return getZero(Stride->getType()); 12159 12160 // This code has only been closely audited for negative strides in the 12161 // unsigned comparison case, it may be correct for signed comparison, but 12162 // that needs to be established. 12163 assert((!IsSigned || !isKnownNonPositive(Stride)) && 12164 "Stride is expected strictly positive for signed case!"); 12165 12166 // Calculate the maximum backedge count based on the range of values 12167 // permitted by Start, End, and Stride. 12168 APInt MinStart = 12169 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 12170 12171 APInt MinStride = 12172 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 12173 12174 // We assume either the stride is positive, or the backedge-taken count 12175 // is zero. So force StrideForMaxBECount to be at least one. 12176 APInt One(BitWidth, 1); 12177 APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride) 12178 : APIntOps::umax(One, MinStride); 12179 12180 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 12181 : APInt::getMaxValue(BitWidth); 12182 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 12183 12184 // Although End can be a MAX expression we estimate MaxEnd considering only 12185 // the case End = RHS of the loop termination condition. This is safe because 12186 // in the other case (End - Start) is zero, leading to a zero maximum backedge 12187 // taken count. 12188 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 12189 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 12190 12191 // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride) 12192 MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart) 12193 : APIntOps::umax(MaxEnd, MinStart); 12194 12195 return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */, 12196 getConstant(StrideForMaxBECount) /* Step */); 12197 } 12198 12199 ScalarEvolution::ExitLimit 12200 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 12201 const Loop *L, bool IsSigned, 12202 bool ControlsExit, bool AllowPredicates) { 12203 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12204 12205 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12206 bool PredicatedIV = false; 12207 12208 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) { 12209 // Can we prove this loop *must* be UB if overflow of IV occurs? 12210 // Reasoning goes as follows: 12211 // * Suppose the IV did self wrap. 12212 // * If Stride evenly divides the iteration space, then once wrap 12213 // occurs, the loop must revisit the same values. 12214 // * We know that RHS is invariant, and that none of those values 12215 // caused this exit to be taken previously. Thus, this exit is 12216 // dynamically dead. 12217 // * If this is the sole exit, then a dead exit implies the loop 12218 // must be infinite if there are no abnormal exits. 12219 // * If the loop were infinite, then it must either not be mustprogress 12220 // or have side effects. Otherwise, it must be UB. 12221 // * It can't (by assumption), be UB so we have contradicted our 12222 // premise and can conclude the IV did not in fact self-wrap. 12223 if (!isLoopInvariant(RHS, L)) 12224 return false; 12225 12226 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)); 12227 if (!StrideC || !StrideC->getAPInt().isPowerOf2()) 12228 return false; 12229 12230 if (!ControlsExit || !loopHasNoAbnormalExits(L)) 12231 return false; 12232 12233 return loopIsFiniteByAssumption(L); 12234 }; 12235 12236 if (!IV) { 12237 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) { 12238 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand()); 12239 if (AR && AR->getLoop() == L && AR->isAffine()) { 12240 auto canProveNUW = [&]() { 12241 if (!isLoopInvariant(RHS, L)) 12242 return false; 12243 12244 if (!isKnownNonZero(AR->getStepRecurrence(*this))) 12245 // We need the sequence defined by AR to strictly increase in the 12246 // unsigned integer domain for the logic below to hold. 12247 return false; 12248 12249 const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType()); 12250 const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType()); 12251 // If RHS <=u Limit, then there must exist a value V in the sequence 12252 // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and 12253 // V <=u UINT_MAX. Thus, we must exit the loop before unsigned 12254 // overflow occurs. This limit also implies that a signed comparison 12255 // (in the wide bitwidth) is equivalent to an unsigned comparison as 12256 // the high bits on both sides must be zero. 12257 APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this)); 12258 APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1); 12259 Limit = Limit.zext(OuterBitWidth); 12260 return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit); 12261 }; 12262 auto Flags = AR->getNoWrapFlags(); 12263 if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW()) 12264 Flags = setFlags(Flags, SCEV::FlagNUW); 12265 12266 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags); 12267 if (AR->hasNoUnsignedWrap()) { 12268 // Emulate what getZeroExtendExpr would have done during construction 12269 // if we'd been able to infer the fact just above at that time. 12270 const SCEV *Step = AR->getStepRecurrence(*this); 12271 Type *Ty = ZExt->getType(); 12272 auto *S = getAddRecExpr( 12273 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0), 12274 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags()); 12275 IV = dyn_cast<SCEVAddRecExpr>(S); 12276 } 12277 } 12278 } 12279 } 12280 12281 12282 if (!IV && AllowPredicates) { 12283 // Try to make this an AddRec using runtime tests, in the first X 12284 // iterations of this loop, where X is the SCEV expression found by the 12285 // algorithm below. 12286 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12287 PredicatedIV = true; 12288 } 12289 12290 // Avoid weird loops 12291 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12292 return getCouldNotCompute(); 12293 12294 // A precondition of this method is that the condition being analyzed 12295 // reaches an exiting branch which dominates the latch. Given that, we can 12296 // assume that an increment which violates the nowrap specification and 12297 // produces poison must cause undefined behavior when the resulting poison 12298 // value is branched upon and thus we can conclude that the backedge is 12299 // taken no more often than would be required to produce that poison value. 12300 // Note that a well defined loop can exit on the iteration which violates 12301 // the nowrap specification if there is another exit (either explicit or 12302 // implicit/exceptional) which causes the loop to execute before the 12303 // exiting instruction we're analyzing would trigger UB. 12304 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12305 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12306 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; 12307 12308 const SCEV *Stride = IV->getStepRecurrence(*this); 12309 12310 bool PositiveStride = isKnownPositive(Stride); 12311 12312 // Avoid negative or zero stride values. 12313 if (!PositiveStride) { 12314 // We can compute the correct backedge taken count for loops with unknown 12315 // strides if we can prove that the loop is not an infinite loop with side 12316 // effects. Here's the loop structure we are trying to handle - 12317 // 12318 // i = start 12319 // do { 12320 // A[i] = i; 12321 // i += s; 12322 // } while (i < end); 12323 // 12324 // The backedge taken count for such loops is evaluated as - 12325 // (max(end, start + stride) - start - 1) /u stride 12326 // 12327 // The additional preconditions that we need to check to prove correctness 12328 // of the above formula is as follows - 12329 // 12330 // a) IV is either nuw or nsw depending upon signedness (indicated by the 12331 // NoWrap flag). 12332 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has 12333 // no side effects within the loop) 12334 // c) loop has a single static exit (with no abnormal exits) 12335 // 12336 // Precondition a) implies that if the stride is negative, this is a single 12337 // trip loop. The backedge taken count formula reduces to zero in this case. 12338 // 12339 // Precondition b) and c) combine to imply that if rhs is invariant in L, 12340 // then a zero stride means the backedge can't be taken without executing 12341 // undefined behavior. 12342 // 12343 // The positive stride case is the same as isKnownPositive(Stride) returning 12344 // true (original behavior of the function). 12345 // 12346 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) || 12347 !loopHasNoAbnormalExits(L)) 12348 return getCouldNotCompute(); 12349 12350 // This bailout is protecting the logic in computeMaxBECountForLT which 12351 // has not yet been sufficiently auditted or tested with negative strides. 12352 // We used to filter out all known-non-positive cases here, we're in the 12353 // process of being less restrictive bit by bit. 12354 if (IsSigned && isKnownNonPositive(Stride)) 12355 return getCouldNotCompute(); 12356 12357 if (!isKnownNonZero(Stride)) { 12358 // If we have a step of zero, and RHS isn't invariant in L, we don't know 12359 // if it might eventually be greater than start and if so, on which 12360 // iteration. We can't even produce a useful upper bound. 12361 if (!isLoopInvariant(RHS, L)) 12362 return getCouldNotCompute(); 12363 12364 // We allow a potentially zero stride, but we need to divide by stride 12365 // below. Since the loop can't be infinite and this check must control 12366 // the sole exit, we can infer the exit must be taken on the first 12367 // iteration (e.g. backedge count = 0) if the stride is zero. Given that, 12368 // we know the numerator in the divides below must be zero, so we can 12369 // pick an arbitrary non-zero value for the denominator (e.g. stride) 12370 // and produce the right result. 12371 // FIXME: Handle the case where Stride is poison? 12372 auto wouldZeroStrideBeUB = [&]() { 12373 // Proof by contradiction. Suppose the stride were zero. If we can 12374 // prove that the backedge *is* taken on the first iteration, then since 12375 // we know this condition controls the sole exit, we must have an 12376 // infinite loop. We can't have a (well defined) infinite loop per 12377 // check just above. 12378 // Note: The (Start - Stride) term is used to get the start' term from 12379 // (start' + stride,+,stride). Remember that we only care about the 12380 // result of this expression when stride == 0 at runtime. 12381 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride); 12382 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS); 12383 }; 12384 if (!wouldZeroStrideBeUB()) { 12385 Stride = getUMaxExpr(Stride, getOne(Stride->getType())); 12386 } 12387 } 12388 } else if (!Stride->isOne() && !NoWrap) { 12389 auto isUBOnWrap = [&]() { 12390 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This 12391 // follows trivially from the fact that every (un)signed-wrapped, but 12392 // not self-wrapped value must be LT than the last value before 12393 // (un)signed wrap. Since we know that last value didn't exit, nor 12394 // will any smaller one. 12395 return canAssumeNoSelfWrap(IV); 12396 }; 12397 12398 // Avoid proven overflow cases: this will ensure that the backedge taken 12399 // count will not generate any unsigned overflow. Relaxed no-overflow 12400 // conditions exploit NoWrapFlags, allowing to optimize in presence of 12401 // undefined behaviors like the case of C language. 12402 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap()) 12403 return getCouldNotCompute(); 12404 } 12405 12406 // On all paths just preceeding, we established the following invariant: 12407 // IV can be assumed not to overflow up to and including the exiting 12408 // iteration. We proved this in one of two ways: 12409 // 1) We can show overflow doesn't occur before the exiting iteration 12410 // 1a) canIVOverflowOnLT, and b) step of one 12411 // 2) We can show that if overflow occurs, the loop must execute UB 12412 // before any possible exit. 12413 // Note that we have not yet proved RHS invariant (in general). 12414 12415 const SCEV *Start = IV->getStart(); 12416 12417 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond. 12418 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases. 12419 // Use integer-typed versions for actual computation; we can't subtract 12420 // pointers in general. 12421 const SCEV *OrigStart = Start; 12422 const SCEV *OrigRHS = RHS; 12423 if (Start->getType()->isPointerTy()) { 12424 Start = getLosslessPtrToIntExpr(Start); 12425 if (isa<SCEVCouldNotCompute>(Start)) 12426 return Start; 12427 } 12428 if (RHS->getType()->isPointerTy()) { 12429 RHS = getLosslessPtrToIntExpr(RHS); 12430 if (isa<SCEVCouldNotCompute>(RHS)) 12431 return RHS; 12432 } 12433 12434 // When the RHS is not invariant, we do not know the end bound of the loop and 12435 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 12436 // calculate the MaxBECount, given the start, stride and max value for the end 12437 // bound of the loop (RHS), and the fact that IV does not overflow (which is 12438 // checked above). 12439 if (!isLoopInvariant(RHS, L)) { 12440 const SCEV *MaxBECount = computeMaxBECountForLT( 12441 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12442 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 12443 false /*MaxOrZero*/, Predicates); 12444 } 12445 12446 // We use the expression (max(End,Start)-Start)/Stride to describe the 12447 // backedge count, as if the backedge is taken at least once max(End,Start) 12448 // is End and so the result is as above, and if not max(End,Start) is Start 12449 // so we get a backedge count of zero. 12450 const SCEV *BECount = nullptr; 12451 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride); 12452 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!"); 12453 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!"); 12454 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!"); 12455 // Can we prove (max(RHS,Start) > Start - Stride? 12456 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) && 12457 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) { 12458 // In this case, we can use a refined formula for computing backedge taken 12459 // count. The general formula remains: 12460 // "End-Start /uceiling Stride" where "End = max(RHS,Start)" 12461 // We want to use the alternate formula: 12462 // "((End - 1) - (Start - Stride)) /u Stride" 12463 // Let's do a quick case analysis to show these are equivalent under 12464 // our precondition that max(RHS,Start) > Start - Stride. 12465 // * For RHS <= Start, the backedge-taken count must be zero. 12466 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12467 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to 12468 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values 12469 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing 12470 // this to the stride of 1 case. 12471 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride". 12472 // "((End - 1) - (Start - Stride)) /u Stride" reduces to 12473 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to 12474 // "((RHS - (Start - Stride) - 1) /u Stride". 12475 // Our preconditions trivially imply no overflow in that form. 12476 const SCEV *MinusOne = getMinusOne(Stride->getType()); 12477 const SCEV *Numerator = 12478 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride)); 12479 BECount = getUDivExpr(Numerator, Stride); 12480 } 12481 12482 const SCEV *BECountIfBackedgeTaken = nullptr; 12483 if (!BECount) { 12484 auto canProveRHSGreaterThanEqualStart = [&]() { 12485 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 12486 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart)) 12487 return true; 12488 12489 // (RHS > Start - 1) implies RHS >= Start. 12490 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if 12491 // "Start - 1" doesn't overflow. 12492 // * For signed comparison, if Start - 1 does overflow, it's equal 12493 // to INT_MAX, and "RHS >s INT_MAX" is trivially false. 12494 // * For unsigned comparison, if Start - 1 does overflow, it's equal 12495 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false. 12496 // 12497 // FIXME: Should isLoopEntryGuardedByCond do this for us? 12498 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12499 auto *StartMinusOne = getAddExpr(OrigStart, 12500 getMinusOne(OrigStart->getType())); 12501 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne); 12502 }; 12503 12504 // If we know that RHS >= Start in the context of loop, then we know that 12505 // max(RHS, Start) = RHS at this point. 12506 const SCEV *End; 12507 if (canProveRHSGreaterThanEqualStart()) { 12508 End = RHS; 12509 } else { 12510 // If RHS < Start, the backedge will be taken zero times. So in 12511 // general, we can write the backedge-taken count as: 12512 // 12513 // RHS >= Start ? ceil(RHS - Start) / Stride : 0 12514 // 12515 // We convert it to the following to make it more convenient for SCEV: 12516 // 12517 // ceil(max(RHS, Start) - Start) / Stride 12518 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 12519 12520 // See what would happen if we assume the backedge is taken. This is 12521 // used to compute MaxBECount. 12522 BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride); 12523 } 12524 12525 // At this point, we know: 12526 // 12527 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End 12528 // 2. The index variable doesn't overflow. 12529 // 12530 // Therefore, we know N exists such that 12531 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)" 12532 // doesn't overflow. 12533 // 12534 // Using this information, try to prove whether the addition in 12535 // "(Start - End) + (Stride - 1)" has unsigned overflow. 12536 const SCEV *One = getOne(Stride->getType()); 12537 bool MayAddOverflow = [&] { 12538 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) { 12539 if (StrideC->getAPInt().isPowerOf2()) { 12540 // Suppose Stride is a power of two, and Start/End are unsigned 12541 // integers. Let UMAX be the largest representable unsigned 12542 // integer. 12543 // 12544 // By the preconditions of this function, we know 12545 // "(Start + Stride * N) >= End", and this doesn't overflow. 12546 // As a formula: 12547 // 12548 // End <= (Start + Stride * N) <= UMAX 12549 // 12550 // Subtracting Start from all the terms: 12551 // 12552 // End - Start <= Stride * N <= UMAX - Start 12553 // 12554 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore: 12555 // 12556 // End - Start <= Stride * N <= UMAX 12557 // 12558 // Stride * N is a multiple of Stride. Therefore, 12559 // 12560 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride) 12561 // 12562 // Since Stride is a power of two, UMAX + 1 is divisible by Stride. 12563 // Therefore, UMAX mod Stride == Stride - 1. So we can write: 12564 // 12565 // End - Start <= Stride * N <= UMAX - Stride - 1 12566 // 12567 // Dropping the middle term: 12568 // 12569 // End - Start <= UMAX - Stride - 1 12570 // 12571 // Adding Stride - 1 to both sides: 12572 // 12573 // (End - Start) + (Stride - 1) <= UMAX 12574 // 12575 // In other words, the addition doesn't have unsigned overflow. 12576 // 12577 // A similar proof works if we treat Start/End as signed values. 12578 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to 12579 // use signed max instead of unsigned max. Note that we're trying 12580 // to prove a lack of unsigned overflow in either case. 12581 return false; 12582 } 12583 } 12584 if (Start == Stride || Start == getMinusSCEV(Stride, One)) { 12585 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1. 12586 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End. 12587 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End. 12588 // 12589 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End. 12590 return false; 12591 } 12592 return true; 12593 }(); 12594 12595 const SCEV *Delta = getMinusSCEV(End, Start); 12596 if (!MayAddOverflow) { 12597 // floor((D + (S - 1)) / S) 12598 // We prefer this formulation if it's legal because it's fewer operations. 12599 BECount = 12600 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride); 12601 } else { 12602 BECount = getUDivCeilSCEV(Delta, Stride); 12603 } 12604 } 12605 12606 const SCEV *MaxBECount; 12607 bool MaxOrZero = false; 12608 if (isa<SCEVConstant>(BECount)) { 12609 MaxBECount = BECount; 12610 } else if (BECountIfBackedgeTaken && 12611 isa<SCEVConstant>(BECountIfBackedgeTaken)) { 12612 // If we know exactly how many times the backedge will be taken if it's 12613 // taken at least once, then the backedge count will either be that or 12614 // zero. 12615 MaxBECount = BECountIfBackedgeTaken; 12616 MaxOrZero = true; 12617 } else { 12618 MaxBECount = computeMaxBECountForLT( 12619 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 12620 } 12621 12622 if (isa<SCEVCouldNotCompute>(MaxBECount) && 12623 !isa<SCEVCouldNotCompute>(BECount)) 12624 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 12625 12626 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 12627 } 12628 12629 ScalarEvolution::ExitLimit 12630 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 12631 const Loop *L, bool IsSigned, 12632 bool ControlsExit, bool AllowPredicates) { 12633 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 12634 // We handle only IV > Invariant 12635 if (!isLoopInvariant(RHS, L)) 12636 return getCouldNotCompute(); 12637 12638 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 12639 if (!IV && AllowPredicates) 12640 // Try to make this an AddRec using runtime tests, in the first X 12641 // iterations of this loop, where X is the SCEV expression found by the 12642 // algorithm below. 12643 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 12644 12645 // Avoid weird loops 12646 if (!IV || IV->getLoop() != L || !IV->isAffine()) 12647 return getCouldNotCompute(); 12648 12649 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW; 12650 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType); 12651 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; 12652 12653 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 12654 12655 // Avoid negative or zero stride values 12656 if (!isKnownPositive(Stride)) 12657 return getCouldNotCompute(); 12658 12659 // Avoid proven overflow cases: this will ensure that the backedge taken count 12660 // will not generate any unsigned overflow. Relaxed no-overflow conditions 12661 // exploit NoWrapFlags, allowing to optimize in presence of undefined 12662 // behaviors like the case of C language. 12663 if (!Stride->isOne() && !NoWrap) 12664 if (canIVOverflowOnGT(RHS, Stride, IsSigned)) 12665 return getCouldNotCompute(); 12666 12667 const SCEV *Start = IV->getStart(); 12668 const SCEV *End = RHS; 12669 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 12670 // If we know that Start >= RHS in the context of loop, then we know that 12671 // min(RHS, Start) = RHS at this point. 12672 if (isLoopEntryGuardedByCond( 12673 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 12674 End = RHS; 12675 else 12676 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 12677 } 12678 12679 if (Start->getType()->isPointerTy()) { 12680 Start = getLosslessPtrToIntExpr(Start); 12681 if (isa<SCEVCouldNotCompute>(Start)) 12682 return Start; 12683 } 12684 if (End->getType()->isPointerTy()) { 12685 End = getLosslessPtrToIntExpr(End); 12686 if (isa<SCEVCouldNotCompute>(End)) 12687 return End; 12688 } 12689 12690 // Compute ((Start - End) + (Stride - 1)) / Stride. 12691 // FIXME: This can overflow. Holding off on fixing this for now; 12692 // howManyGreaterThans will hopefully be gone soon. 12693 const SCEV *One = getOne(Stride->getType()); 12694 const SCEV *BECount = getUDivExpr( 12695 getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride); 12696 12697 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 12698 : getUnsignedRangeMax(Start); 12699 12700 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 12701 : getUnsignedRangeMin(Stride); 12702 12703 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 12704 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 12705 : APInt::getMinValue(BitWidth) + (MinStride - 1); 12706 12707 // Although End can be a MIN expression we estimate MinEnd considering only 12708 // the case End = RHS. This is safe because in the other case (Start - End) 12709 // is zero, leading to a zero maximum backedge taken count. 12710 APInt MinEnd = 12711 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 12712 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 12713 12714 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 12715 ? BECount 12716 : getUDivCeilSCEV(getConstant(MaxStart - MinEnd), 12717 getConstant(MinStride)); 12718 12719 if (isa<SCEVCouldNotCompute>(MaxBECount)) 12720 MaxBECount = BECount; 12721 12722 return ExitLimit(BECount, MaxBECount, false, Predicates); 12723 } 12724 12725 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 12726 ScalarEvolution &SE) const { 12727 if (Range.isFullSet()) // Infinite loop. 12728 return SE.getCouldNotCompute(); 12729 12730 // If the start is a non-zero constant, shift the range to simplify things. 12731 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 12732 if (!SC->getValue()->isZero()) { 12733 SmallVector<const SCEV *, 4> Operands(operands()); 12734 Operands[0] = SE.getZero(SC->getType()); 12735 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 12736 getNoWrapFlags(FlagNW)); 12737 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 12738 return ShiftedAddRec->getNumIterationsInRange( 12739 Range.subtract(SC->getAPInt()), SE); 12740 // This is strange and shouldn't happen. 12741 return SE.getCouldNotCompute(); 12742 } 12743 12744 // The only time we can solve this is when we have all constant indices. 12745 // Otherwise, we cannot determine the overflow conditions. 12746 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 12747 return SE.getCouldNotCompute(); 12748 12749 // Okay at this point we know that all elements of the chrec are constants and 12750 // that the start element is zero. 12751 12752 // First check to see if the range contains zero. If not, the first 12753 // iteration exits. 12754 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 12755 if (!Range.contains(APInt(BitWidth, 0))) 12756 return SE.getZero(getType()); 12757 12758 if (isAffine()) { 12759 // If this is an affine expression then we have this situation: 12760 // Solve {0,+,A} in Range === Ax in Range 12761 12762 // We know that zero is in the range. If A is positive then we know that 12763 // the upper value of the range must be the first possible exit value. 12764 // If A is negative then the lower of the range is the last possible loop 12765 // value. Also note that we already checked for a full range. 12766 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 12767 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 12768 12769 // The exit value should be (End+A)/A. 12770 APInt ExitVal = (End + A).udiv(A); 12771 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 12772 12773 // Evaluate at the exit value. If we really did fall out of the valid 12774 // range, then we computed our trip count, otherwise wrap around or other 12775 // things must have happened. 12776 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 12777 if (Range.contains(Val->getValue())) 12778 return SE.getCouldNotCompute(); // Something strange happened 12779 12780 // Ensure that the previous value is in the range. 12781 assert(Range.contains( 12782 EvaluateConstantChrecAtConstant(this, 12783 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 12784 "Linear scev computation is off in a bad way!"); 12785 return SE.getConstant(ExitValue); 12786 } 12787 12788 if (isQuadratic()) { 12789 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 12790 return SE.getConstant(S.getValue()); 12791 } 12792 12793 return SE.getCouldNotCompute(); 12794 } 12795 12796 const SCEVAddRecExpr * 12797 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 12798 assert(getNumOperands() > 1 && "AddRec with zero step?"); 12799 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 12800 // but in this case we cannot guarantee that the value returned will be an 12801 // AddRec because SCEV does not have a fixed point where it stops 12802 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 12803 // may happen if we reach arithmetic depth limit while simplifying. So we 12804 // construct the returned value explicitly. 12805 SmallVector<const SCEV *, 3> Ops; 12806 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 12807 // (this + Step) is {A+B,+,B+C,+...,+,N}. 12808 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 12809 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 12810 // We know that the last operand is not a constant zero (otherwise it would 12811 // have been popped out earlier). This guarantees us that if the result has 12812 // the same last operand, then it will also not be popped out, meaning that 12813 // the returned value will be an AddRec. 12814 const SCEV *Last = getOperand(getNumOperands() - 1); 12815 assert(!Last->isZero() && "Recurrency with zero step?"); 12816 Ops.push_back(Last); 12817 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 12818 SCEV::FlagAnyWrap)); 12819 } 12820 12821 // Return true when S contains at least an undef value. 12822 bool ScalarEvolution::containsUndefs(const SCEV *S) const { 12823 return SCEVExprContains(S, [](const SCEV *S) { 12824 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 12825 return isa<UndefValue>(SU->getValue()); 12826 return false; 12827 }); 12828 } 12829 12830 /// Return the size of an element read or written by Inst. 12831 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 12832 Type *Ty; 12833 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 12834 Ty = Store->getValueOperand()->getType(); 12835 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 12836 Ty = Load->getType(); 12837 else 12838 return nullptr; 12839 12840 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 12841 return getSizeOfExpr(ETy, Ty); 12842 } 12843 12844 //===----------------------------------------------------------------------===// 12845 // SCEVCallbackVH Class Implementation 12846 //===----------------------------------------------------------------------===// 12847 12848 void ScalarEvolution::SCEVCallbackVH::deleted() { 12849 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12850 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 12851 SE->ConstantEvolutionLoopExitValue.erase(PN); 12852 SE->eraseValueFromMap(getValPtr()); 12853 // this now dangles! 12854 } 12855 12856 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 12857 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 12858 12859 // Forget all the expressions associated with users of the old value, 12860 // so that future queries will recompute the expressions using the new 12861 // value. 12862 Value *Old = getValPtr(); 12863 SmallVector<User *, 16> Worklist(Old->users()); 12864 SmallPtrSet<User *, 8> Visited; 12865 while (!Worklist.empty()) { 12866 User *U = Worklist.pop_back_val(); 12867 // Deleting the Old value will cause this to dangle. Postpone 12868 // that until everything else is done. 12869 if (U == Old) 12870 continue; 12871 if (!Visited.insert(U).second) 12872 continue; 12873 if (PHINode *PN = dyn_cast<PHINode>(U)) 12874 SE->ConstantEvolutionLoopExitValue.erase(PN); 12875 SE->eraseValueFromMap(U); 12876 llvm::append_range(Worklist, U->users()); 12877 } 12878 // Delete the Old value. 12879 if (PHINode *PN = dyn_cast<PHINode>(Old)) 12880 SE->ConstantEvolutionLoopExitValue.erase(PN); 12881 SE->eraseValueFromMap(Old); 12882 // this now dangles! 12883 } 12884 12885 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 12886 : CallbackVH(V), SE(se) {} 12887 12888 //===----------------------------------------------------------------------===// 12889 // ScalarEvolution Class Implementation 12890 //===----------------------------------------------------------------------===// 12891 12892 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 12893 AssumptionCache &AC, DominatorTree &DT, 12894 LoopInfo &LI) 12895 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 12896 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 12897 LoopDispositions(64), BlockDispositions(64) { 12898 // To use guards for proving predicates, we need to scan every instruction in 12899 // relevant basic blocks, and not just terminators. Doing this is a waste of 12900 // time if the IR does not actually contain any calls to 12901 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 12902 // 12903 // This pessimizes the case where a pass that preserves ScalarEvolution wants 12904 // to _add_ guards to the module when there weren't any before, and wants 12905 // ScalarEvolution to optimize based on those guards. For now we prefer to be 12906 // efficient in lieu of being smart in that rather obscure case. 12907 12908 auto *GuardDecl = F.getParent()->getFunction( 12909 Intrinsic::getName(Intrinsic::experimental_guard)); 12910 HasGuards = GuardDecl && !GuardDecl->use_empty(); 12911 } 12912 12913 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 12914 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 12915 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 12916 ValueExprMap(std::move(Arg.ValueExprMap)), 12917 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 12918 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 12919 PendingMerges(std::move(Arg.PendingMerges)), 12920 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 12921 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 12922 PredicatedBackedgeTakenCounts( 12923 std::move(Arg.PredicatedBackedgeTakenCounts)), 12924 BECountUsers(std::move(Arg.BECountUsers)), 12925 ConstantEvolutionLoopExitValue( 12926 std::move(Arg.ConstantEvolutionLoopExitValue)), 12927 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 12928 ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)), 12929 LoopDispositions(std::move(Arg.LoopDispositions)), 12930 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 12931 BlockDispositions(std::move(Arg.BlockDispositions)), 12932 SCEVUsers(std::move(Arg.SCEVUsers)), 12933 UnsignedRanges(std::move(Arg.UnsignedRanges)), 12934 SignedRanges(std::move(Arg.SignedRanges)), 12935 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 12936 UniquePreds(std::move(Arg.UniquePreds)), 12937 SCEVAllocator(std::move(Arg.SCEVAllocator)), 12938 LoopUsers(std::move(Arg.LoopUsers)), 12939 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 12940 FirstUnknown(Arg.FirstUnknown) { 12941 Arg.FirstUnknown = nullptr; 12942 } 12943 12944 ScalarEvolution::~ScalarEvolution() { 12945 // Iterate through all the SCEVUnknown instances and call their 12946 // destructors, so that they release their references to their values. 12947 for (SCEVUnknown *U = FirstUnknown; U;) { 12948 SCEVUnknown *Tmp = U; 12949 U = U->Next; 12950 Tmp->~SCEVUnknown(); 12951 } 12952 FirstUnknown = nullptr; 12953 12954 ExprValueMap.clear(); 12955 ValueExprMap.clear(); 12956 HasRecMap.clear(); 12957 BackedgeTakenCounts.clear(); 12958 PredicatedBackedgeTakenCounts.clear(); 12959 12960 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 12961 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 12962 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 12963 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 12964 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 12965 } 12966 12967 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 12968 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 12969 } 12970 12971 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 12972 const Loop *L) { 12973 // Print all inner loops first 12974 for (Loop *I : *L) 12975 PrintLoopInfo(OS, SE, I); 12976 12977 OS << "Loop "; 12978 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12979 OS << ": "; 12980 12981 SmallVector<BasicBlock *, 8> ExitingBlocks; 12982 L->getExitingBlocks(ExitingBlocks); 12983 if (ExitingBlocks.size() != 1) 12984 OS << "<multiple exits> "; 12985 12986 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 12987 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 12988 else 12989 OS << "Unpredictable backedge-taken count.\n"; 12990 12991 if (ExitingBlocks.size() > 1) 12992 for (BasicBlock *ExitingBlock : ExitingBlocks) { 12993 OS << " exit count for " << ExitingBlock->getName() << ": " 12994 << *SE->getExitCount(L, ExitingBlock) << "\n"; 12995 } 12996 12997 OS << "Loop "; 12998 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12999 OS << ": "; 13000 13001 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 13002 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 13003 if (SE->isBackedgeTakenCountMaxOrZero(L)) 13004 OS << ", actual taken count either this or zero."; 13005 } else { 13006 OS << "Unpredictable max backedge-taken count. "; 13007 } 13008 13009 OS << "\n" 13010 "Loop "; 13011 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 13012 OS << ": "; 13013 13014 SmallVector<const SCEVPredicate *, 4> Preds; 13015 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds); 13016 if (!isa<SCEVCouldNotCompute>(PBT)) { 13017 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 13018 OS << " Predicates:\n"; 13019 for (auto *P : Preds) 13020 P->print(OS, 4); 13021 } else { 13022 OS << "Unpredictable predicated backedge-taken count. "; 13023 } 13024 OS << "\n"; 13025 13026 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 13027 OS << "Loop "; 13028 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 13029 OS << ": "; 13030 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 13031 } 13032 } 13033 13034 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 13035 switch (LD) { 13036 case ScalarEvolution::LoopVariant: 13037 return "Variant"; 13038 case ScalarEvolution::LoopInvariant: 13039 return "Invariant"; 13040 case ScalarEvolution::LoopComputable: 13041 return "Computable"; 13042 } 13043 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 13044 } 13045 13046 void ScalarEvolution::print(raw_ostream &OS) const { 13047 // ScalarEvolution's implementation of the print method is to print 13048 // out SCEV values of all instructions that are interesting. Doing 13049 // this potentially causes it to create new SCEV objects though, 13050 // which technically conflicts with the const qualifier. This isn't 13051 // observable from outside the class though, so casting away the 13052 // const isn't dangerous. 13053 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 13054 13055 if (ClassifyExpressions) { 13056 OS << "Classifying expressions for: "; 13057 F.printAsOperand(OS, /*PrintType=*/false); 13058 OS << "\n"; 13059 for (Instruction &I : instructions(F)) 13060 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 13061 OS << I << '\n'; 13062 OS << " --> "; 13063 const SCEV *SV = SE.getSCEV(&I); 13064 SV->print(OS); 13065 if (!isa<SCEVCouldNotCompute>(SV)) { 13066 OS << " U: "; 13067 SE.getUnsignedRange(SV).print(OS); 13068 OS << " S: "; 13069 SE.getSignedRange(SV).print(OS); 13070 } 13071 13072 const Loop *L = LI.getLoopFor(I.getParent()); 13073 13074 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 13075 if (AtUse != SV) { 13076 OS << " --> "; 13077 AtUse->print(OS); 13078 if (!isa<SCEVCouldNotCompute>(AtUse)) { 13079 OS << " U: "; 13080 SE.getUnsignedRange(AtUse).print(OS); 13081 OS << " S: "; 13082 SE.getSignedRange(AtUse).print(OS); 13083 } 13084 } 13085 13086 if (L) { 13087 OS << "\t\t" "Exits: "; 13088 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 13089 if (!SE.isLoopInvariant(ExitValue, L)) { 13090 OS << "<<Unknown>>"; 13091 } else { 13092 OS << *ExitValue; 13093 } 13094 13095 bool First = true; 13096 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 13097 if (First) { 13098 OS << "\t\t" "LoopDispositions: { "; 13099 First = false; 13100 } else { 13101 OS << ", "; 13102 } 13103 13104 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 13105 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 13106 } 13107 13108 for (auto *InnerL : depth_first(L)) { 13109 if (InnerL == L) 13110 continue; 13111 if (First) { 13112 OS << "\t\t" "LoopDispositions: { "; 13113 First = false; 13114 } else { 13115 OS << ", "; 13116 } 13117 13118 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 13119 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 13120 } 13121 13122 OS << " }"; 13123 } 13124 13125 OS << "\n"; 13126 } 13127 } 13128 13129 OS << "Determining loop execution counts for: "; 13130 F.printAsOperand(OS, /*PrintType=*/false); 13131 OS << "\n"; 13132 for (Loop *I : LI) 13133 PrintLoopInfo(OS, &SE, I); 13134 } 13135 13136 ScalarEvolution::LoopDisposition 13137 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 13138 auto &Values = LoopDispositions[S]; 13139 for (auto &V : Values) { 13140 if (V.getPointer() == L) 13141 return V.getInt(); 13142 } 13143 Values.emplace_back(L, LoopVariant); 13144 LoopDisposition D = computeLoopDisposition(S, L); 13145 auto &Values2 = LoopDispositions[S]; 13146 for (auto &V : llvm::reverse(Values2)) { 13147 if (V.getPointer() == L) { 13148 V.setInt(D); 13149 break; 13150 } 13151 } 13152 return D; 13153 } 13154 13155 ScalarEvolution::LoopDisposition 13156 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 13157 switch (S->getSCEVType()) { 13158 case scConstant: 13159 return LoopInvariant; 13160 case scPtrToInt: 13161 case scTruncate: 13162 case scZeroExtend: 13163 case scSignExtend: 13164 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 13165 case scAddRecExpr: { 13166 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 13167 13168 // If L is the addrec's loop, it's computable. 13169 if (AR->getLoop() == L) 13170 return LoopComputable; 13171 13172 // Add recurrences are never invariant in the function-body (null loop). 13173 if (!L) 13174 return LoopVariant; 13175 13176 // Everything that is not defined at loop entry is variant. 13177 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 13178 return LoopVariant; 13179 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 13180 " dominate the contained loop's header?"); 13181 13182 // This recurrence is invariant w.r.t. L if AR's loop contains L. 13183 if (AR->getLoop()->contains(L)) 13184 return LoopInvariant; 13185 13186 // This recurrence is variant w.r.t. L if any of its operands 13187 // are variant. 13188 for (auto *Op : AR->operands()) 13189 if (!isLoopInvariant(Op, L)) 13190 return LoopVariant; 13191 13192 // Otherwise it's loop-invariant. 13193 return LoopInvariant; 13194 } 13195 case scAddExpr: 13196 case scMulExpr: 13197 case scUMaxExpr: 13198 case scSMaxExpr: 13199 case scUMinExpr: 13200 case scSMinExpr: 13201 case scSequentialUMinExpr: { 13202 bool HasVarying = false; 13203 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 13204 LoopDisposition D = getLoopDisposition(Op, L); 13205 if (D == LoopVariant) 13206 return LoopVariant; 13207 if (D == LoopComputable) 13208 HasVarying = true; 13209 } 13210 return HasVarying ? LoopComputable : LoopInvariant; 13211 } 13212 case scUDivExpr: { 13213 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 13214 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 13215 if (LD == LoopVariant) 13216 return LoopVariant; 13217 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 13218 if (RD == LoopVariant) 13219 return LoopVariant; 13220 return (LD == LoopInvariant && RD == LoopInvariant) ? 13221 LoopInvariant : LoopComputable; 13222 } 13223 case scUnknown: 13224 // All non-instruction values are loop invariant. All instructions are loop 13225 // invariant if they are not contained in the specified loop. 13226 // Instructions are never considered invariant in the function body 13227 // (null loop) because they are defined within the "loop". 13228 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 13229 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 13230 return LoopInvariant; 13231 case scCouldNotCompute: 13232 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 13233 } 13234 llvm_unreachable("Unknown SCEV kind!"); 13235 } 13236 13237 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 13238 return getLoopDisposition(S, L) == LoopInvariant; 13239 } 13240 13241 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 13242 return getLoopDisposition(S, L) == LoopComputable; 13243 } 13244 13245 ScalarEvolution::BlockDisposition 13246 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13247 auto &Values = BlockDispositions[S]; 13248 for (auto &V : Values) { 13249 if (V.getPointer() == BB) 13250 return V.getInt(); 13251 } 13252 Values.emplace_back(BB, DoesNotDominateBlock); 13253 BlockDisposition D = computeBlockDisposition(S, BB); 13254 auto &Values2 = BlockDispositions[S]; 13255 for (auto &V : llvm::reverse(Values2)) { 13256 if (V.getPointer() == BB) { 13257 V.setInt(D); 13258 break; 13259 } 13260 } 13261 return D; 13262 } 13263 13264 ScalarEvolution::BlockDisposition 13265 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 13266 switch (S->getSCEVType()) { 13267 case scConstant: 13268 return ProperlyDominatesBlock; 13269 case scPtrToInt: 13270 case scTruncate: 13271 case scZeroExtend: 13272 case scSignExtend: 13273 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 13274 case scAddRecExpr: { 13275 // This uses a "dominates" query instead of "properly dominates" query 13276 // to test for proper dominance too, because the instruction which 13277 // produces the addrec's value is a PHI, and a PHI effectively properly 13278 // dominates its entire containing block. 13279 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 13280 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 13281 return DoesNotDominateBlock; 13282 13283 // Fall through into SCEVNAryExpr handling. 13284 LLVM_FALLTHROUGH; 13285 } 13286 case scAddExpr: 13287 case scMulExpr: 13288 case scUMaxExpr: 13289 case scSMaxExpr: 13290 case scUMinExpr: 13291 case scSMinExpr: 13292 case scSequentialUMinExpr: { 13293 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 13294 bool Proper = true; 13295 for (const SCEV *NAryOp : NAry->operands()) { 13296 BlockDisposition D = getBlockDisposition(NAryOp, BB); 13297 if (D == DoesNotDominateBlock) 13298 return DoesNotDominateBlock; 13299 if (D == DominatesBlock) 13300 Proper = false; 13301 } 13302 return Proper ? ProperlyDominatesBlock : DominatesBlock; 13303 } 13304 case scUDivExpr: { 13305 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 13306 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 13307 BlockDisposition LD = getBlockDisposition(LHS, BB); 13308 if (LD == DoesNotDominateBlock) 13309 return DoesNotDominateBlock; 13310 BlockDisposition RD = getBlockDisposition(RHS, BB); 13311 if (RD == DoesNotDominateBlock) 13312 return DoesNotDominateBlock; 13313 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 13314 ProperlyDominatesBlock : DominatesBlock; 13315 } 13316 case scUnknown: 13317 if (Instruction *I = 13318 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 13319 if (I->getParent() == BB) 13320 return DominatesBlock; 13321 if (DT.properlyDominates(I->getParent(), BB)) 13322 return ProperlyDominatesBlock; 13323 return DoesNotDominateBlock; 13324 } 13325 return ProperlyDominatesBlock; 13326 case scCouldNotCompute: 13327 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 13328 } 13329 llvm_unreachable("Unknown SCEV kind!"); 13330 } 13331 13332 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 13333 return getBlockDisposition(S, BB) >= DominatesBlock; 13334 } 13335 13336 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 13337 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 13338 } 13339 13340 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 13341 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 13342 } 13343 13344 void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L, 13345 bool Predicated) { 13346 auto &BECounts = 13347 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13348 auto It = BECounts.find(L); 13349 if (It != BECounts.end()) { 13350 for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) { 13351 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13352 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13353 assert(UserIt != BECountUsers.end()); 13354 UserIt->second.erase({L, Predicated}); 13355 } 13356 } 13357 BECounts.erase(It); 13358 } 13359 } 13360 13361 void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) { 13362 SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end()); 13363 SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end()); 13364 13365 while (!Worklist.empty()) { 13366 const SCEV *Curr = Worklist.pop_back_val(); 13367 auto Users = SCEVUsers.find(Curr); 13368 if (Users != SCEVUsers.end()) 13369 for (auto *User : Users->second) 13370 if (ToForget.insert(User).second) 13371 Worklist.push_back(User); 13372 } 13373 13374 for (auto *S : ToForget) 13375 forgetMemoizedResultsImpl(S); 13376 13377 for (auto I = PredicatedSCEVRewrites.begin(); 13378 I != PredicatedSCEVRewrites.end();) { 13379 std::pair<const SCEV *, const Loop *> Entry = I->first; 13380 if (ToForget.count(Entry.first)) 13381 PredicatedSCEVRewrites.erase(I++); 13382 else 13383 ++I; 13384 } 13385 } 13386 13387 void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) { 13388 LoopDispositions.erase(S); 13389 BlockDispositions.erase(S); 13390 UnsignedRanges.erase(S); 13391 SignedRanges.erase(S); 13392 HasRecMap.erase(S); 13393 MinTrailingZerosCache.erase(S); 13394 13395 auto ExprIt = ExprValueMap.find(S); 13396 if (ExprIt != ExprValueMap.end()) { 13397 for (auto &ValueAndOffset : ExprIt->second) { 13398 if (ValueAndOffset.second == nullptr) { 13399 auto ValueIt = ValueExprMap.find_as(ValueAndOffset.first); 13400 if (ValueIt != ValueExprMap.end()) 13401 ValueExprMap.erase(ValueIt); 13402 } 13403 } 13404 ExprValueMap.erase(ExprIt); 13405 } 13406 13407 auto ScopeIt = ValuesAtScopes.find(S); 13408 if (ScopeIt != ValuesAtScopes.end()) { 13409 for (const auto &Pair : ScopeIt->second) 13410 if (!isa_and_nonnull<SCEVConstant>(Pair.second)) 13411 erase_value(ValuesAtScopesUsers[Pair.second], 13412 std::make_pair(Pair.first, S)); 13413 ValuesAtScopes.erase(ScopeIt); 13414 } 13415 13416 auto ScopeUserIt = ValuesAtScopesUsers.find(S); 13417 if (ScopeUserIt != ValuesAtScopesUsers.end()) { 13418 for (const auto &Pair : ScopeUserIt->second) 13419 erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S)); 13420 ValuesAtScopesUsers.erase(ScopeUserIt); 13421 } 13422 13423 auto BEUsersIt = BECountUsers.find(S); 13424 if (BEUsersIt != BECountUsers.end()) { 13425 // Work on a copy, as forgetBackedgeTakenCounts() will modify the original. 13426 auto Copy = BEUsersIt->second; 13427 for (const auto &Pair : Copy) 13428 forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt()); 13429 BECountUsers.erase(BEUsersIt); 13430 } 13431 } 13432 13433 void 13434 ScalarEvolution::getUsedLoops(const SCEV *S, 13435 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 13436 struct FindUsedLoops { 13437 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 13438 : LoopsUsed(LoopsUsed) {} 13439 SmallPtrSetImpl<const Loop *> &LoopsUsed; 13440 bool follow(const SCEV *S) { 13441 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 13442 LoopsUsed.insert(AR->getLoop()); 13443 return true; 13444 } 13445 13446 bool isDone() const { return false; } 13447 }; 13448 13449 FindUsedLoops F(LoopsUsed); 13450 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 13451 } 13452 13453 void ScalarEvolution::verify() const { 13454 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 13455 ScalarEvolution SE2(F, TLI, AC, DT, LI); 13456 13457 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 13458 13459 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 13460 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 13461 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 13462 13463 const SCEV *visitConstant(const SCEVConstant *Constant) { 13464 return SE.getConstant(Constant->getAPInt()); 13465 } 13466 13467 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13468 return SE.getUnknown(Expr->getValue()); 13469 } 13470 13471 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 13472 return SE.getCouldNotCompute(); 13473 } 13474 }; 13475 13476 SCEVMapper SCM(SE2); 13477 13478 while (!LoopStack.empty()) { 13479 auto *L = LoopStack.pop_back_val(); 13480 llvm::append_range(LoopStack, *L); 13481 13482 auto *CurBECount = SCM.visit( 13483 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 13484 auto *NewBECount = SE2.getBackedgeTakenCount(L); 13485 13486 if (CurBECount == SE2.getCouldNotCompute() || 13487 NewBECount == SE2.getCouldNotCompute()) { 13488 // NB! This situation is legal, but is very suspicious -- whatever pass 13489 // change the loop to make a trip count go from could not compute to 13490 // computable or vice-versa *should have* invalidated SCEV. However, we 13491 // choose not to assert here (for now) since we don't want false 13492 // positives. 13493 continue; 13494 } 13495 13496 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 13497 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 13498 // not propagate undef aggressively). This means we can (and do) fail 13499 // verification in cases where a transform makes the trip count of a loop 13500 // go from "undef" to "undef+1" (say). The transform is fine, since in 13501 // both cases the loop iterates "undef" times, but SCEV thinks we 13502 // increased the trip count of the loop by 1 incorrectly. 13503 continue; 13504 } 13505 13506 if (SE.getTypeSizeInBits(CurBECount->getType()) > 13507 SE.getTypeSizeInBits(NewBECount->getType())) 13508 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 13509 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 13510 SE.getTypeSizeInBits(NewBECount->getType())) 13511 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 13512 13513 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 13514 13515 // Unless VerifySCEVStrict is set, we only compare constant deltas. 13516 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 13517 dbgs() << "Trip Count for " << *L << " Changed!\n"; 13518 dbgs() << "Old: " << *CurBECount << "\n"; 13519 dbgs() << "New: " << *NewBECount << "\n"; 13520 dbgs() << "Delta: " << *Delta << "\n"; 13521 std::abort(); 13522 } 13523 } 13524 13525 // Collect all valid loops currently in LoopInfo. 13526 SmallPtrSet<Loop *, 32> ValidLoops; 13527 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 13528 while (!Worklist.empty()) { 13529 Loop *L = Worklist.pop_back_val(); 13530 if (ValidLoops.contains(L)) 13531 continue; 13532 ValidLoops.insert(L); 13533 Worklist.append(L->begin(), L->end()); 13534 } 13535 for (auto &KV : ValueExprMap) { 13536 #ifndef NDEBUG 13537 // Check for SCEV expressions referencing invalid/deleted loops. 13538 if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) { 13539 assert(ValidLoops.contains(AR->getLoop()) && 13540 "AddRec references invalid loop"); 13541 } 13542 #endif 13543 13544 // Check that the value is also part of the reverse map. 13545 auto It = ExprValueMap.find(KV.second); 13546 if (It == ExprValueMap.end() || !It->second.contains({KV.first, nullptr})) { 13547 dbgs() << "Value " << *KV.first 13548 << " is in ValueExprMap but not in ExprValueMap\n"; 13549 std::abort(); 13550 } 13551 } 13552 13553 for (const auto &KV : ExprValueMap) { 13554 for (const auto &ValueAndOffset : KV.second) { 13555 if (ValueAndOffset.second != nullptr) 13556 continue; 13557 13558 auto It = ValueExprMap.find_as(ValueAndOffset.first); 13559 if (It == ValueExprMap.end()) { 13560 dbgs() << "Value " << *ValueAndOffset.first 13561 << " is in ExprValueMap but not in ValueExprMap\n"; 13562 std::abort(); 13563 } 13564 if (It->second != KV.first) { 13565 dbgs() << "Value " << *ValueAndOffset.first 13566 << " mapped to " << *It->second 13567 << " rather than " << *KV.first << "\n"; 13568 std::abort(); 13569 } 13570 } 13571 } 13572 13573 // Verify integrity of SCEV users. 13574 for (const auto &S : UniqueSCEVs) { 13575 SmallVector<const SCEV *, 4> Ops; 13576 collectUniqueOps(&S, Ops); 13577 for (const auto *Op : Ops) { 13578 // We do not store dependencies of constants. 13579 if (isa<SCEVConstant>(Op)) 13580 continue; 13581 auto It = SCEVUsers.find(Op); 13582 if (It != SCEVUsers.end() && It->second.count(&S)) 13583 continue; 13584 dbgs() << "Use of operand " << *Op << " by user " << S 13585 << " is not being tracked!\n"; 13586 std::abort(); 13587 } 13588 } 13589 13590 // Verify integrity of ValuesAtScopes users. 13591 for (const auto &ValueAndVec : ValuesAtScopes) { 13592 const SCEV *Value = ValueAndVec.first; 13593 for (const auto &LoopAndValueAtScope : ValueAndVec.second) { 13594 const Loop *L = LoopAndValueAtScope.first; 13595 const SCEV *ValueAtScope = LoopAndValueAtScope.second; 13596 if (!isa<SCEVConstant>(ValueAtScope)) { 13597 auto It = ValuesAtScopesUsers.find(ValueAtScope); 13598 if (It != ValuesAtScopesUsers.end() && 13599 is_contained(It->second, std::make_pair(L, Value))) 13600 continue; 13601 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13602 << *ValueAtScope << " missing in ValuesAtScopesUsers\n"; 13603 std::abort(); 13604 } 13605 } 13606 } 13607 13608 for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) { 13609 const SCEV *ValueAtScope = ValueAtScopeAndVec.first; 13610 for (const auto &LoopAndValue : ValueAtScopeAndVec.second) { 13611 const Loop *L = LoopAndValue.first; 13612 const SCEV *Value = LoopAndValue.second; 13613 assert(!isa<SCEVConstant>(Value)); 13614 auto It = ValuesAtScopes.find(Value); 13615 if (It != ValuesAtScopes.end() && 13616 is_contained(It->second, std::make_pair(L, ValueAtScope))) 13617 continue; 13618 dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: " 13619 << *ValueAtScope << " missing in ValuesAtScopes\n"; 13620 std::abort(); 13621 } 13622 } 13623 13624 // Verify integrity of BECountUsers. 13625 auto VerifyBECountUsers = [&](bool Predicated) { 13626 auto &BECounts = 13627 Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts; 13628 for (const auto &LoopAndBEInfo : BECounts) { 13629 for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) { 13630 if (!isa<SCEVConstant>(ENT.ExactNotTaken)) { 13631 auto UserIt = BECountUsers.find(ENT.ExactNotTaken); 13632 if (UserIt != BECountUsers.end() && 13633 UserIt->second.contains({ LoopAndBEInfo.first, Predicated })) 13634 continue; 13635 dbgs() << "Value " << *ENT.ExactNotTaken << " for loop " 13636 << *LoopAndBEInfo.first << " missing from BECountUsers\n"; 13637 std::abort(); 13638 } 13639 } 13640 } 13641 }; 13642 VerifyBECountUsers(/* Predicated */ false); 13643 VerifyBECountUsers(/* Predicated */ true); 13644 } 13645 13646 bool ScalarEvolution::invalidate( 13647 Function &F, const PreservedAnalyses &PA, 13648 FunctionAnalysisManager::Invalidator &Inv) { 13649 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 13650 // of its dependencies is invalidated. 13651 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 13652 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 13653 Inv.invalidate<AssumptionAnalysis>(F, PA) || 13654 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 13655 Inv.invalidate<LoopAnalysis>(F, PA); 13656 } 13657 13658 AnalysisKey ScalarEvolutionAnalysis::Key; 13659 13660 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 13661 FunctionAnalysisManager &AM) { 13662 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 13663 AM.getResult<AssumptionAnalysis>(F), 13664 AM.getResult<DominatorTreeAnalysis>(F), 13665 AM.getResult<LoopAnalysis>(F)); 13666 } 13667 13668 PreservedAnalyses 13669 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 13670 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 13671 return PreservedAnalyses::all(); 13672 } 13673 13674 PreservedAnalyses 13675 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 13676 // For compatibility with opt's -analyze feature under legacy pass manager 13677 // which was not ported to NPM. This keeps tests using 13678 // update_analyze_test_checks.py working. 13679 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 13680 << F.getName() << "':\n"; 13681 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 13682 return PreservedAnalyses::all(); 13683 } 13684 13685 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 13686 "Scalar Evolution Analysis", false, true) 13687 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 13688 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 13689 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 13690 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 13691 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 13692 "Scalar Evolution Analysis", false, true) 13693 13694 char ScalarEvolutionWrapperPass::ID = 0; 13695 13696 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 13697 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 13698 } 13699 13700 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 13701 SE.reset(new ScalarEvolution( 13702 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 13703 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 13704 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 13705 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 13706 return false; 13707 } 13708 13709 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 13710 13711 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 13712 SE->print(OS); 13713 } 13714 13715 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 13716 if (!VerifySCEV) 13717 return; 13718 13719 SE->verify(); 13720 } 13721 13722 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 13723 AU.setPreservesAll(); 13724 AU.addRequiredTransitive<AssumptionCacheTracker>(); 13725 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 13726 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 13727 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 13728 } 13729 13730 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 13731 const SCEV *RHS) { 13732 return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS); 13733 } 13734 13735 const SCEVPredicate * 13736 ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred, 13737 const SCEV *LHS, const SCEV *RHS) { 13738 FoldingSetNodeID ID; 13739 assert(LHS->getType() == RHS->getType() && 13740 "Type mismatch between LHS and RHS"); 13741 // Unique this node based on the arguments 13742 ID.AddInteger(SCEVPredicate::P_Compare); 13743 ID.AddInteger(Pred); 13744 ID.AddPointer(LHS); 13745 ID.AddPointer(RHS); 13746 void *IP = nullptr; 13747 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13748 return S; 13749 SCEVComparePredicate *Eq = new (SCEVAllocator) 13750 SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS); 13751 UniquePreds.InsertNode(Eq, IP); 13752 return Eq; 13753 } 13754 13755 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 13756 const SCEVAddRecExpr *AR, 13757 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13758 FoldingSetNodeID ID; 13759 // Unique this node based on the arguments 13760 ID.AddInteger(SCEVPredicate::P_Wrap); 13761 ID.AddPointer(AR); 13762 ID.AddInteger(AddedFlags); 13763 void *IP = nullptr; 13764 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 13765 return S; 13766 auto *OF = new (SCEVAllocator) 13767 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 13768 UniquePreds.InsertNode(OF, IP); 13769 return OF; 13770 } 13771 13772 namespace { 13773 13774 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 13775 public: 13776 13777 /// Rewrites \p S in the context of a loop L and the SCEV predication 13778 /// infrastructure. 13779 /// 13780 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 13781 /// equivalences present in \p Pred. 13782 /// 13783 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 13784 /// \p NewPreds such that the result will be an AddRecExpr. 13785 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 13786 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13787 const SCEVPredicate *Pred) { 13788 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 13789 return Rewriter.visit(S); 13790 } 13791 13792 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13793 if (Pred) { 13794 if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) { 13795 for (auto *Pred : U->getPredicates()) 13796 if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) 13797 if (IPred->getLHS() == Expr && 13798 IPred->getPredicate() == ICmpInst::ICMP_EQ) 13799 return IPred->getRHS(); 13800 } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) { 13801 if (IPred->getLHS() == Expr && 13802 IPred->getPredicate() == ICmpInst::ICMP_EQ) 13803 return IPred->getRHS(); 13804 } 13805 } 13806 return convertToAddRecWithPreds(Expr); 13807 } 13808 13809 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 13810 const SCEV *Operand = visit(Expr->getOperand()); 13811 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13812 if (AR && AR->getLoop() == L && AR->isAffine()) { 13813 // This couldn't be folded because the operand didn't have the nuw 13814 // flag. Add the nusw flag as an assumption that we could make. 13815 const SCEV *Step = AR->getStepRecurrence(SE); 13816 Type *Ty = Expr->getType(); 13817 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 13818 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 13819 SE.getSignExtendExpr(Step, Ty), L, 13820 AR->getNoWrapFlags()); 13821 } 13822 return SE.getZeroExtendExpr(Operand, Expr->getType()); 13823 } 13824 13825 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 13826 const SCEV *Operand = visit(Expr->getOperand()); 13827 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 13828 if (AR && AR->getLoop() == L && AR->isAffine()) { 13829 // This couldn't be folded because the operand didn't have the nsw 13830 // flag. Add the nssw flag as an assumption that we could make. 13831 const SCEV *Step = AR->getStepRecurrence(SE); 13832 Type *Ty = Expr->getType(); 13833 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 13834 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 13835 SE.getSignExtendExpr(Step, Ty), L, 13836 AR->getNoWrapFlags()); 13837 } 13838 return SE.getSignExtendExpr(Operand, Expr->getType()); 13839 } 13840 13841 private: 13842 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 13843 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 13844 const SCEVPredicate *Pred) 13845 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 13846 13847 bool addOverflowAssumption(const SCEVPredicate *P) { 13848 if (!NewPreds) { 13849 // Check if we've already made this assumption. 13850 return Pred && Pred->implies(P); 13851 } 13852 NewPreds->insert(P); 13853 return true; 13854 } 13855 13856 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 13857 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 13858 auto *A = SE.getWrapPredicate(AR, AddedFlags); 13859 return addOverflowAssumption(A); 13860 } 13861 13862 // If \p Expr represents a PHINode, we try to see if it can be represented 13863 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 13864 // to add this predicate as a runtime overflow check, we return the AddRec. 13865 // If \p Expr does not meet these conditions (is not a PHI node, or we 13866 // couldn't create an AddRec for it, or couldn't add the predicate), we just 13867 // return \p Expr. 13868 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 13869 if (!isa<PHINode>(Expr->getValue())) 13870 return Expr; 13871 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 13872 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 13873 if (!PredicatedRewrite) 13874 return Expr; 13875 for (auto *P : PredicatedRewrite->second){ 13876 // Wrap predicates from outer loops are not supported. 13877 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 13878 if (L != WP->getExpr()->getLoop()) 13879 return Expr; 13880 } 13881 if (!addOverflowAssumption(P)) 13882 return Expr; 13883 } 13884 return PredicatedRewrite->first; 13885 } 13886 13887 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 13888 const SCEVPredicate *Pred; 13889 const Loop *L; 13890 }; 13891 13892 } // end anonymous namespace 13893 13894 const SCEV * 13895 ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 13896 const SCEVPredicate &Preds) { 13897 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 13898 } 13899 13900 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 13901 const SCEV *S, const Loop *L, 13902 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 13903 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 13904 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 13905 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 13906 13907 if (!AddRec) 13908 return nullptr; 13909 13910 // Since the transformation was successful, we can now transfer the SCEV 13911 // predicates. 13912 for (auto *P : TransformPreds) 13913 Preds.insert(P); 13914 13915 return AddRec; 13916 } 13917 13918 /// SCEV predicates 13919 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 13920 SCEVPredicateKind Kind) 13921 : FastID(ID), Kind(Kind) {} 13922 13923 SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID, 13924 const ICmpInst::Predicate Pred, 13925 const SCEV *LHS, const SCEV *RHS) 13926 : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) { 13927 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 13928 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 13929 } 13930 13931 bool SCEVComparePredicate::implies(const SCEVPredicate *N) const { 13932 const auto *Op = dyn_cast<SCEVComparePredicate>(N); 13933 13934 if (!Op) 13935 return false; 13936 13937 if (Pred != ICmpInst::ICMP_EQ) 13938 return false; 13939 13940 return Op->LHS == LHS && Op->RHS == RHS; 13941 } 13942 13943 bool SCEVComparePredicate::isAlwaysTrue() const { return false; } 13944 13945 void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const { 13946 if (Pred == ICmpInst::ICMP_EQ) 13947 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 13948 else 13949 OS.indent(Depth) << "Compare predicate: " << *LHS 13950 << " " << CmpInst::getPredicateName(Pred) << ") " 13951 << *RHS << "\n"; 13952 13953 } 13954 13955 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 13956 const SCEVAddRecExpr *AR, 13957 IncrementWrapFlags Flags) 13958 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 13959 13960 const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; } 13961 13962 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 13963 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 13964 13965 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 13966 } 13967 13968 bool SCEVWrapPredicate::isAlwaysTrue() const { 13969 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 13970 IncrementWrapFlags IFlags = Flags; 13971 13972 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 13973 IFlags = clearFlags(IFlags, IncrementNSSW); 13974 13975 return IFlags == IncrementAnyWrap; 13976 } 13977 13978 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 13979 OS.indent(Depth) << *getExpr() << " Added Flags: "; 13980 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 13981 OS << "<nusw>"; 13982 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 13983 OS << "<nssw>"; 13984 OS << "\n"; 13985 } 13986 13987 SCEVWrapPredicate::IncrementWrapFlags 13988 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 13989 ScalarEvolution &SE) { 13990 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 13991 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 13992 13993 // We can safely transfer the NSW flag as NSSW. 13994 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 13995 ImpliedFlags = IncrementNSSW; 13996 13997 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 13998 // If the increment is positive, the SCEV NUW flag will also imply the 13999 // WrapPredicate NUSW flag. 14000 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 14001 if (Step->getValue()->getValue().isNonNegative()) 14002 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 14003 } 14004 14005 return ImpliedFlags; 14006 } 14007 14008 /// Union predicates don't get cached so create a dummy set ID for it. 14009 SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds) 14010 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) { 14011 for (auto *P : Preds) 14012 add(P); 14013 } 14014 14015 bool SCEVUnionPredicate::isAlwaysTrue() const { 14016 return all_of(Preds, 14017 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 14018 } 14019 14020 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 14021 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 14022 return all_of(Set->Preds, 14023 [this](const SCEVPredicate *I) { return this->implies(I); }); 14024 14025 return any_of(Preds, 14026 [N](const SCEVPredicate *I) { return I->implies(N); }); 14027 } 14028 14029 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 14030 for (auto Pred : Preds) 14031 Pred->print(OS, Depth); 14032 } 14033 14034 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 14035 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 14036 for (auto Pred : Set->Preds) 14037 add(Pred); 14038 return; 14039 } 14040 14041 Preds.push_back(N); 14042 } 14043 14044 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 14045 Loop &L) 14046 : SE(SE), L(L) { 14047 SmallVector<const SCEVPredicate*, 4> Empty; 14048 Preds = std::make_unique<SCEVUnionPredicate>(Empty); 14049 } 14050 14051 void ScalarEvolution::registerUser(const SCEV *User, 14052 ArrayRef<const SCEV *> Ops) { 14053 for (auto *Op : Ops) 14054 // We do not expect that forgetting cached data for SCEVConstants will ever 14055 // open any prospects for sharpening or introduce any correctness issues, 14056 // so we don't bother storing their dependencies. 14057 if (!isa<SCEVConstant>(Op)) 14058 SCEVUsers[Op].insert(User); 14059 } 14060 14061 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 14062 const SCEV *Expr = SE.getSCEV(V); 14063 RewriteEntry &Entry = RewriteMap[Expr]; 14064 14065 // If we already have an entry and the version matches, return it. 14066 if (Entry.second && Generation == Entry.first) 14067 return Entry.second; 14068 14069 // We found an entry but it's stale. Rewrite the stale entry 14070 // according to the current predicate. 14071 if (Entry.second) 14072 Expr = Entry.second; 14073 14074 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds); 14075 Entry = {Generation, NewSCEV}; 14076 14077 return NewSCEV; 14078 } 14079 14080 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 14081 if (!BackedgeCount) { 14082 SmallVector<const SCEVPredicate *, 4> Preds; 14083 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds); 14084 for (auto *P : Preds) 14085 addPredicate(*P); 14086 } 14087 return BackedgeCount; 14088 } 14089 14090 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 14091 if (Preds->implies(&Pred)) 14092 return; 14093 14094 auto &OldPreds = Preds->getPredicates(); 14095 SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end()); 14096 NewPreds.push_back(&Pred); 14097 Preds = std::make_unique<SCEVUnionPredicate>(NewPreds); 14098 updateGeneration(); 14099 } 14100 14101 const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const { 14102 return *Preds; 14103 } 14104 14105 void PredicatedScalarEvolution::updateGeneration() { 14106 // If the generation number wrapped recompute everything. 14107 if (++Generation == 0) { 14108 for (auto &II : RewriteMap) { 14109 const SCEV *Rewritten = II.second.second; 14110 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)}; 14111 } 14112 } 14113 } 14114 14115 void PredicatedScalarEvolution::setNoOverflow( 14116 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 14117 const SCEV *Expr = getSCEV(V); 14118 const auto *AR = cast<SCEVAddRecExpr>(Expr); 14119 14120 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 14121 14122 // Clear the statically implied flags. 14123 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 14124 addPredicate(*SE.getWrapPredicate(AR, Flags)); 14125 14126 auto II = FlagsMap.insert({V, Flags}); 14127 if (!II.second) 14128 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 14129 } 14130 14131 bool PredicatedScalarEvolution::hasNoOverflow( 14132 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 14133 const SCEV *Expr = getSCEV(V); 14134 const auto *AR = cast<SCEVAddRecExpr>(Expr); 14135 14136 Flags = SCEVWrapPredicate::clearFlags( 14137 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 14138 14139 auto II = FlagsMap.find(V); 14140 14141 if (II != FlagsMap.end()) 14142 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 14143 14144 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 14145 } 14146 14147 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 14148 const SCEV *Expr = this->getSCEV(V); 14149 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 14150 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 14151 14152 if (!New) 14153 return nullptr; 14154 14155 for (auto *P : NewPreds) 14156 addPredicate(*P); 14157 14158 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 14159 return New; 14160 } 14161 14162 PredicatedScalarEvolution::PredicatedScalarEvolution( 14163 const PredicatedScalarEvolution &Init) 14164 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), 14165 Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())), 14166 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 14167 for (auto I : Init.FlagsMap) 14168 FlagsMap.insert(I); 14169 } 14170 14171 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 14172 // For each block. 14173 for (auto *BB : L.getBlocks()) 14174 for (auto &I : *BB) { 14175 if (!SE.isSCEVable(I.getType())) 14176 continue; 14177 14178 auto *Expr = SE.getSCEV(&I); 14179 auto II = RewriteMap.find(Expr); 14180 14181 if (II == RewriteMap.end()) 14182 continue; 14183 14184 // Don't print things that are not interesting. 14185 if (II->second.second == Expr) 14186 continue; 14187 14188 OS.indent(Depth) << "[PSE]" << I << ":\n"; 14189 OS.indent(Depth + 2) << *Expr << "\n"; 14190 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 14191 } 14192 } 14193 14194 // Match the mathematical pattern A - (A / B) * B, where A and B can be 14195 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 14196 // for URem with constant power-of-2 second operands. 14197 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 14198 // 4, A / B becomes X / 8). 14199 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 14200 const SCEV *&RHS) { 14201 // Try to match 'zext (trunc A to iB) to iY', which is used 14202 // for URem with constant power-of-2 second operands. Make sure the size of 14203 // the operand A matches the size of the whole expressions. 14204 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 14205 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 14206 LHS = Trunc->getOperand(); 14207 // Bail out if the type of the LHS is larger than the type of the 14208 // expression for now. 14209 if (getTypeSizeInBits(LHS->getType()) > 14210 getTypeSizeInBits(Expr->getType())) 14211 return false; 14212 if (LHS->getType() != Expr->getType()) 14213 LHS = getZeroExtendExpr(LHS, Expr->getType()); 14214 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 14215 << getTypeSizeInBits(Trunc->getType())); 14216 return true; 14217 } 14218 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 14219 if (Add == nullptr || Add->getNumOperands() != 2) 14220 return false; 14221 14222 const SCEV *A = Add->getOperand(1); 14223 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 14224 14225 if (Mul == nullptr) 14226 return false; 14227 14228 const auto MatchURemWithDivisor = [&](const SCEV *B) { 14229 // (SomeExpr + (-(SomeExpr / B) * B)). 14230 if (Expr == getURemExpr(A, B)) { 14231 LHS = A; 14232 RHS = B; 14233 return true; 14234 } 14235 return false; 14236 }; 14237 14238 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 14239 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 14240 return MatchURemWithDivisor(Mul->getOperand(1)) || 14241 MatchURemWithDivisor(Mul->getOperand(2)); 14242 14243 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 14244 if (Mul->getNumOperands() == 2) 14245 return MatchURemWithDivisor(Mul->getOperand(1)) || 14246 MatchURemWithDivisor(Mul->getOperand(0)) || 14247 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 14248 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 14249 return false; 14250 } 14251 14252 const SCEV * 14253 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 14254 SmallVector<BasicBlock*, 16> ExitingBlocks; 14255 L->getExitingBlocks(ExitingBlocks); 14256 14257 // Form an expression for the maximum exit count possible for this loop. We 14258 // merge the max and exact information to approximate a version of 14259 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 14260 SmallVector<const SCEV*, 4> ExitCounts; 14261 for (BasicBlock *ExitingBB : ExitingBlocks) { 14262 const SCEV *ExitCount = getExitCount(L, ExitingBB); 14263 if (isa<SCEVCouldNotCompute>(ExitCount)) 14264 ExitCount = getExitCount(L, ExitingBB, 14265 ScalarEvolution::ConstantMaximum); 14266 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 14267 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 14268 "We should only have known counts for exiting blocks that " 14269 "dominate latch!"); 14270 ExitCounts.push_back(ExitCount); 14271 } 14272 } 14273 if (ExitCounts.empty()) 14274 return getCouldNotCompute(); 14275 return getUMinFromMismatchedTypes(ExitCounts); 14276 } 14277 14278 /// A rewriter to replace SCEV expressions in Map with the corresponding entry 14279 /// in the map. It skips AddRecExpr because we cannot guarantee that the 14280 /// replacement is loop invariant in the loop of the AddRec. 14281 /// 14282 /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is 14283 /// supported. 14284 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 14285 const DenseMap<const SCEV *, const SCEV *> ⤅ 14286 14287 public: 14288 SCEVLoopGuardRewriter(ScalarEvolution &SE, 14289 DenseMap<const SCEV *, const SCEV *> &M) 14290 : SCEVRewriteVisitor(SE), Map(M) {} 14291 14292 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 14293 14294 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 14295 auto I = Map.find(Expr); 14296 if (I == Map.end()) 14297 return Expr; 14298 return I->second; 14299 } 14300 14301 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 14302 auto I = Map.find(Expr); 14303 if (I == Map.end()) 14304 return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr( 14305 Expr); 14306 return I->second; 14307 } 14308 }; 14309 14310 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 14311 SmallVector<const SCEV *> ExprsToRewrite; 14312 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 14313 const SCEV *RHS, 14314 DenseMap<const SCEV *, const SCEV *> 14315 &RewriteMap) { 14316 // WARNING: It is generally unsound to apply any wrap flags to the proposed 14317 // replacement SCEV which isn't directly implied by the structure of that 14318 // SCEV. In particular, using contextual facts to imply flags is *NOT* 14319 // legal. See the scoping rules for flags in the header to understand why. 14320 14321 // If LHS is a constant, apply information to the other expression. 14322 if (isa<SCEVConstant>(LHS)) { 14323 std::swap(LHS, RHS); 14324 Predicate = CmpInst::getSwappedPredicate(Predicate); 14325 } 14326 14327 // Check for a condition of the form (-C1 + X < C2). InstCombine will 14328 // create this form when combining two checks of the form (X u< C2 + C1) and 14329 // (X >=u C1). 14330 auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap, 14331 &ExprsToRewrite]() { 14332 auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS); 14333 if (!AddExpr || AddExpr->getNumOperands() != 2) 14334 return false; 14335 14336 auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0)); 14337 auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1)); 14338 auto *C2 = dyn_cast<SCEVConstant>(RHS); 14339 if (!C1 || !C2 || !LHSUnknown) 14340 return false; 14341 14342 auto ExactRegion = 14343 ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt()) 14344 .sub(C1->getAPInt()); 14345 14346 // Bail out, unless we have a non-wrapping, monotonic range. 14347 if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet()) 14348 return false; 14349 auto I = RewriteMap.find(LHSUnknown); 14350 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown; 14351 RewriteMap[LHSUnknown] = getUMaxExpr( 14352 getConstant(ExactRegion.getUnsignedMin()), 14353 getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax()))); 14354 ExprsToRewrite.push_back(LHSUnknown); 14355 return true; 14356 }; 14357 if (MatchRangeCheckIdiom()) 14358 return; 14359 14360 // If we have LHS == 0, check if LHS is computing a property of some unknown 14361 // SCEV %v which we can rewrite %v to express explicitly. 14362 const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS); 14363 if (Predicate == CmpInst::ICMP_EQ && RHSC && 14364 RHSC->getValue()->isNullValue()) { 14365 // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to 14366 // explicitly express that. 14367 const SCEV *URemLHS = nullptr; 14368 const SCEV *URemRHS = nullptr; 14369 if (matchURem(LHS, URemLHS, URemRHS)) { 14370 if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) { 14371 auto Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS); 14372 RewriteMap[LHSUnknown] = Multiple; 14373 ExprsToRewrite.push_back(LHSUnknown); 14374 return; 14375 } 14376 } 14377 } 14378 14379 // Do not apply information for constants or if RHS contains an AddRec. 14380 if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS)) 14381 return; 14382 14383 // If RHS is SCEVUnknown, make sure the information is applied to it. 14384 if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) { 14385 std::swap(LHS, RHS); 14386 Predicate = CmpInst::getSwappedPredicate(Predicate); 14387 } 14388 14389 // Limit to expressions that can be rewritten. 14390 if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS)) 14391 return; 14392 14393 // Check whether LHS has already been rewritten. In that case we want to 14394 // chain further rewrites onto the already rewritten value. 14395 auto I = RewriteMap.find(LHS); 14396 const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS; 14397 14398 const SCEV *RewrittenRHS = nullptr; 14399 switch (Predicate) { 14400 case CmpInst::ICMP_ULT: 14401 RewrittenRHS = 14402 getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14403 break; 14404 case CmpInst::ICMP_SLT: 14405 RewrittenRHS = 14406 getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType()))); 14407 break; 14408 case CmpInst::ICMP_ULE: 14409 RewrittenRHS = getUMinExpr(RewrittenLHS, RHS); 14410 break; 14411 case CmpInst::ICMP_SLE: 14412 RewrittenRHS = getSMinExpr(RewrittenLHS, RHS); 14413 break; 14414 case CmpInst::ICMP_UGT: 14415 RewrittenRHS = 14416 getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14417 break; 14418 case CmpInst::ICMP_SGT: 14419 RewrittenRHS = 14420 getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType()))); 14421 break; 14422 case CmpInst::ICMP_UGE: 14423 RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS); 14424 break; 14425 case CmpInst::ICMP_SGE: 14426 RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS); 14427 break; 14428 case CmpInst::ICMP_EQ: 14429 if (isa<SCEVConstant>(RHS)) 14430 RewrittenRHS = RHS; 14431 break; 14432 case CmpInst::ICMP_NE: 14433 if (isa<SCEVConstant>(RHS) && 14434 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 14435 RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType())); 14436 break; 14437 default: 14438 break; 14439 } 14440 14441 if (RewrittenRHS) { 14442 RewriteMap[LHS] = RewrittenRHS; 14443 if (LHS == RewrittenLHS) 14444 ExprsToRewrite.push_back(LHS); 14445 } 14446 }; 14447 // First, collect conditions from dominating branches. Starting at the loop 14448 // predecessor, climb up the predecessor chain, as long as there are 14449 // predecessors that can be found that have unique successors leading to the 14450 // original header. 14451 // TODO: share this logic with isLoopEntryGuardedByCond. 14452 SmallVector<std::pair<Value *, bool>> Terms; 14453 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 14454 L->getLoopPredecessor(), L->getHeader()); 14455 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 14456 14457 const BranchInst *LoopEntryPredicate = 14458 dyn_cast<BranchInst>(Pair.first->getTerminator()); 14459 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 14460 continue; 14461 14462 Terms.emplace_back(LoopEntryPredicate->getCondition(), 14463 LoopEntryPredicate->getSuccessor(0) == Pair.second); 14464 } 14465 14466 // Now apply the information from the collected conditions to RewriteMap. 14467 // Conditions are processed in reverse order, so the earliest conditions is 14468 // processed first. This ensures the SCEVs with the shortest dependency chains 14469 // are constructed first. 14470 DenseMap<const SCEV *, const SCEV *> RewriteMap; 14471 for (auto &E : reverse(Terms)) { 14472 bool EnterIfTrue = E.second; 14473 SmallVector<Value *, 8> Worklist; 14474 SmallPtrSet<Value *, 8> Visited; 14475 Worklist.push_back(E.first); 14476 while (!Worklist.empty()) { 14477 Value *Cond = Worklist.pop_back_val(); 14478 if (!Visited.insert(Cond).second) 14479 continue; 14480 14481 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) { 14482 auto Predicate = 14483 EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate(); 14484 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 14485 getSCEV(Cmp->getOperand(1)), RewriteMap); 14486 continue; 14487 } 14488 14489 Value *L, *R; 14490 if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))) 14491 : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) { 14492 Worklist.push_back(L); 14493 Worklist.push_back(R); 14494 } 14495 } 14496 } 14497 14498 // Also collect information from assumptions dominating the loop. 14499 for (auto &AssumeVH : AC.assumptions()) { 14500 if (!AssumeVH) 14501 continue; 14502 auto *AssumeI = cast<CallInst>(AssumeVH); 14503 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 14504 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 14505 continue; 14506 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 14507 getSCEV(Cmp->getOperand(1)), RewriteMap); 14508 } 14509 14510 if (RewriteMap.empty()) 14511 return Expr; 14512 14513 // Now that all rewrite information is collect, rewrite the collected 14514 // expressions with the information in the map. This applies information to 14515 // sub-expressions. 14516 if (ExprsToRewrite.size() > 1) { 14517 for (const SCEV *Expr : ExprsToRewrite) { 14518 const SCEV *RewriteTo = RewriteMap[Expr]; 14519 RewriteMap.erase(Expr); 14520 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14521 RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)}); 14522 } 14523 } 14524 14525 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 14526 return Rewriter.visit(Expr); 14527 } 14528