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 139 #define DEBUG_TYPE "scalar-evolution" 140 141 STATISTIC(NumArrayLenItCounts, 142 "Number of trip counts computed with array length"); 143 STATISTIC(NumTripCountsComputed, 144 "Number of loops with predictable loop counts"); 145 STATISTIC(NumTripCountsNotComputed, 146 "Number of loops without predictable loop counts"); 147 STATISTIC(NumBruteForceTripCountsComputed, 148 "Number of loops with trip counts computed by force"); 149 150 static cl::opt<unsigned> 151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 152 cl::ZeroOrMore, 153 cl::desc("Maximum number of iterations SCEV will " 154 "symbolically execute a constant " 155 "derived loop"), 156 cl::init(100)); 157 158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 159 static cl::opt<bool> VerifySCEV( 160 "verify-scev", cl::Hidden, 161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 162 static cl::opt<bool> VerifySCEVStrict( 163 "verify-scev-strict", cl::Hidden, 164 cl::desc("Enable stricter verification with -verify-scev is passed")); 165 static cl::opt<bool> 166 VerifySCEVMap("verify-scev-maps", cl::Hidden, 167 cl::desc("Verify no dangling value in ScalarEvolution's " 168 "ExprValueMap (slow)")); 169 170 static cl::opt<bool> VerifyIR( 171 "scev-verify-ir", cl::Hidden, 172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 173 cl::init(false)); 174 175 static cl::opt<unsigned> MulOpsInlineThreshold( 176 "scev-mulops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> AddOpsInlineThreshold( 181 "scev-addops-inline-threshold", cl::Hidden, 182 cl::desc("Threshold for inlining addition operands into a SCEV"), 183 cl::init(500)); 184 185 static cl::opt<unsigned> MaxSCEVCompareDepth( 186 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 188 cl::init(32)); 189 190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> MaxValueCompareDepth( 196 "scalar-evolution-max-value-compare-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive value complexity comparisons"), 198 cl::init(2)); 199 200 static cl::opt<unsigned> 201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive arithmetics"), 203 cl::init(32)); 204 205 static cl::opt<unsigned> MaxConstantEvolvingDepth( 206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 208 209 static cl::opt<unsigned> 210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 216 cl::desc("Max coefficients in AddRec during evolving"), 217 cl::init(8)); 218 219 static cl::opt<unsigned> 220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 221 cl::desc("Size of the expression which is considered huge"), 222 cl::init(4096)); 223 224 static cl::opt<bool> 225 ClassifyExpressions("scalar-evolution-classify-expressions", 226 cl::Hidden, cl::init(true), 227 cl::desc("When printing analysis, include information on every instruction")); 228 229 230 //===----------------------------------------------------------------------===// 231 // SCEV class definitions 232 //===----------------------------------------------------------------------===// 233 234 //===----------------------------------------------------------------------===// 235 // Implementation of the SCEV class. 236 // 237 238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 239 LLVM_DUMP_METHOD void SCEV::dump() const { 240 print(dbgs()); 241 dbgs() << '\n'; 242 } 243 #endif 244 245 void SCEV::print(raw_ostream &OS) const { 246 switch (static_cast<SCEVTypes>(getSCEVType())) { 247 case scConstant: 248 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 249 return; 250 case scTruncate: { 251 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 252 const SCEV *Op = Trunc->getOperand(); 253 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 254 << *Trunc->getType() << ")"; 255 return; 256 } 257 case scZeroExtend: { 258 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 259 const SCEV *Op = ZExt->getOperand(); 260 OS << "(zext " << *Op->getType() << " " << *Op << " to " 261 << *ZExt->getType() << ")"; 262 return; 263 } 264 case scSignExtend: { 265 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 266 const SCEV *Op = SExt->getOperand(); 267 OS << "(sext " << *Op->getType() << " " << *Op << " to " 268 << *SExt->getType() << ")"; 269 return; 270 } 271 case scAddRecExpr: { 272 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 273 OS << "{" << *AR->getOperand(0); 274 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 275 OS << ",+," << *AR->getOperand(i); 276 OS << "}<"; 277 if (AR->hasNoUnsignedWrap()) 278 OS << "nuw><"; 279 if (AR->hasNoSignedWrap()) 280 OS << "nsw><"; 281 if (AR->hasNoSelfWrap() && 282 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 283 OS << "nw><"; 284 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 285 OS << ">"; 286 return; 287 } 288 case scAddExpr: 289 case scMulExpr: 290 case scUMaxExpr: 291 case scSMaxExpr: 292 case scUMinExpr: 293 case scSMinExpr: { 294 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 295 const char *OpStr = nullptr; 296 switch (NAry->getSCEVType()) { 297 case scAddExpr: OpStr = " + "; break; 298 case scMulExpr: OpStr = " * "; break; 299 case scUMaxExpr: OpStr = " umax "; break; 300 case scSMaxExpr: OpStr = " smax "; break; 301 case scUMinExpr: 302 OpStr = " umin "; 303 break; 304 case scSMinExpr: 305 OpStr = " smin "; 306 break; 307 } 308 OS << "("; 309 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 310 I != E; ++I) { 311 OS << **I; 312 if (std::next(I) != E) 313 OS << OpStr; 314 } 315 OS << ")"; 316 switch (NAry->getSCEVType()) { 317 case scAddExpr: 318 case scMulExpr: 319 if (NAry->hasNoUnsignedWrap()) 320 OS << "<nuw>"; 321 if (NAry->hasNoSignedWrap()) 322 OS << "<nsw>"; 323 } 324 return; 325 } 326 case scUDivExpr: { 327 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 328 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 329 return; 330 } 331 case scUnknown: { 332 const SCEVUnknown *U = cast<SCEVUnknown>(this); 333 Type *AllocTy; 334 if (U->isSizeOf(AllocTy)) { 335 OS << "sizeof(" << *AllocTy << ")"; 336 return; 337 } 338 if (U->isAlignOf(AllocTy)) { 339 OS << "alignof(" << *AllocTy << ")"; 340 return; 341 } 342 343 Type *CTy; 344 Constant *FieldNo; 345 if (U->isOffsetOf(CTy, FieldNo)) { 346 OS << "offsetof(" << *CTy << ", "; 347 FieldNo->printAsOperand(OS, false); 348 OS << ")"; 349 return; 350 } 351 352 // Otherwise just print it normally. 353 U->getValue()->printAsOperand(OS, false); 354 return; 355 } 356 case scCouldNotCompute: 357 OS << "***COULDNOTCOMPUTE***"; 358 return; 359 } 360 llvm_unreachable("Unknown SCEV kind!"); 361 } 362 363 Type *SCEV::getType() const { 364 switch (static_cast<SCEVTypes>(getSCEVType())) { 365 case scConstant: 366 return cast<SCEVConstant>(this)->getType(); 367 case scTruncate: 368 case scZeroExtend: 369 case scSignExtend: 370 return cast<SCEVCastExpr>(this)->getType(); 371 case scAddRecExpr: 372 case scMulExpr: 373 case scUMaxExpr: 374 case scSMaxExpr: 375 case scUMinExpr: 376 case scSMinExpr: 377 return cast<SCEVNAryExpr>(this)->getType(); 378 case scAddExpr: 379 return cast<SCEVAddExpr>(this)->getType(); 380 case scUDivExpr: 381 return cast<SCEVUDivExpr>(this)->getType(); 382 case scUnknown: 383 return cast<SCEVUnknown>(this)->getType(); 384 case scCouldNotCompute: 385 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 386 } 387 llvm_unreachable("Unknown SCEV kind!"); 388 } 389 390 bool SCEV::isZero() const { 391 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 392 return SC->getValue()->isZero(); 393 return false; 394 } 395 396 bool SCEV::isOne() const { 397 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 398 return SC->getValue()->isOne(); 399 return false; 400 } 401 402 bool SCEV::isAllOnesValue() const { 403 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 404 return SC->getValue()->isMinusOne(); 405 return false; 406 } 407 408 bool SCEV::isNonConstantNegative() const { 409 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 410 if (!Mul) return false; 411 412 // If there is a constant factor, it will be first. 413 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 414 if (!SC) return false; 415 416 // Return true if the value is negative, this matches things like (-42 * V). 417 return SC->getAPInt().isNegative(); 418 } 419 420 SCEVCouldNotCompute::SCEVCouldNotCompute() : 421 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 422 423 bool SCEVCouldNotCompute::classof(const SCEV *S) { 424 return S->getSCEVType() == scCouldNotCompute; 425 } 426 427 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 428 FoldingSetNodeID ID; 429 ID.AddInteger(scConstant); 430 ID.AddPointer(V); 431 void *IP = nullptr; 432 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 433 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 434 UniqueSCEVs.InsertNode(S, IP); 435 return S; 436 } 437 438 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 439 return getConstant(ConstantInt::get(getContext(), Val)); 440 } 441 442 const SCEV * 443 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 444 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 445 return getConstant(ConstantInt::get(ITy, V, isSigned)); 446 } 447 448 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 449 unsigned SCEVTy, const SCEV *op, Type *ty) 450 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 451 452 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 453 const SCEV *op, Type *ty) 454 : SCEVCastExpr(ID, scTruncate, op, ty) { 455 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 456 "Cannot truncate non-integer value!"); 457 } 458 459 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 460 const SCEV *op, Type *ty) 461 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 462 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 463 "Cannot zero extend non-integer value!"); 464 } 465 466 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 467 const SCEV *op, Type *ty) 468 : SCEVCastExpr(ID, scSignExtend, op, ty) { 469 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 470 "Cannot sign extend non-integer value!"); 471 } 472 473 void SCEVUnknown::deleted() { 474 // Clear this SCEVUnknown from various maps. 475 SE->forgetMemoizedResults(this); 476 477 // Remove this SCEVUnknown from the uniquing map. 478 SE->UniqueSCEVs.RemoveNode(this); 479 480 // Release the value. 481 setValPtr(nullptr); 482 } 483 484 void SCEVUnknown::allUsesReplacedWith(Value *New) { 485 // Remove this SCEVUnknown from the uniquing map. 486 SE->UniqueSCEVs.RemoveNode(this); 487 488 // Update this SCEVUnknown to point to the new value. This is needed 489 // because there may still be outstanding SCEVs which still point to 490 // this SCEVUnknown. 491 setValPtr(New); 492 } 493 494 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 495 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 496 if (VCE->getOpcode() == Instruction::PtrToInt) 497 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 498 if (CE->getOpcode() == Instruction::GetElementPtr && 499 CE->getOperand(0)->isNullValue() && 500 CE->getNumOperands() == 2) 501 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 502 if (CI->isOne()) { 503 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 504 ->getElementType(); 505 return true; 506 } 507 508 return false; 509 } 510 511 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 512 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 513 if (VCE->getOpcode() == Instruction::PtrToInt) 514 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 515 if (CE->getOpcode() == Instruction::GetElementPtr && 516 CE->getOperand(0)->isNullValue()) { 517 Type *Ty = 518 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 519 if (StructType *STy = dyn_cast<StructType>(Ty)) 520 if (!STy->isPacked() && 521 CE->getNumOperands() == 3 && 522 CE->getOperand(1)->isNullValue()) { 523 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 524 if (CI->isOne() && 525 STy->getNumElements() == 2 && 526 STy->getElementType(0)->isIntegerTy(1)) { 527 AllocTy = STy->getElementType(1); 528 return true; 529 } 530 } 531 } 532 533 return false; 534 } 535 536 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 537 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 538 if (VCE->getOpcode() == Instruction::PtrToInt) 539 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 540 if (CE->getOpcode() == Instruction::GetElementPtr && 541 CE->getNumOperands() == 3 && 542 CE->getOperand(0)->isNullValue() && 543 CE->getOperand(1)->isNullValue()) { 544 Type *Ty = 545 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 546 // Ignore vector types here so that ScalarEvolutionExpander doesn't 547 // emit getelementptrs that index into vectors. 548 if (Ty->isStructTy() || Ty->isArrayTy()) { 549 CTy = Ty; 550 FieldNo = CE->getOperand(2); 551 return true; 552 } 553 } 554 555 return false; 556 } 557 558 //===----------------------------------------------------------------------===// 559 // SCEV Utilities 560 //===----------------------------------------------------------------------===// 561 562 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 563 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 564 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 565 /// have been previously deemed to be "equally complex" by this routine. It is 566 /// intended to avoid exponential time complexity in cases like: 567 /// 568 /// %a = f(%x, %y) 569 /// %b = f(%a, %a) 570 /// %c = f(%b, %b) 571 /// 572 /// %d = f(%x, %y) 573 /// %e = f(%d, %d) 574 /// %f = f(%e, %e) 575 /// 576 /// CompareValueComplexity(%f, %c) 577 /// 578 /// Since we do not continue running this routine on expression trees once we 579 /// have seen unequal values, there is no need to track them in the cache. 580 static int 581 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 582 const LoopInfo *const LI, Value *LV, Value *RV, 583 unsigned Depth) { 584 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 585 return 0; 586 587 // Order pointer values after integer values. This helps SCEVExpander form 588 // GEPs. 589 bool LIsPointer = LV->getType()->isPointerTy(), 590 RIsPointer = RV->getType()->isPointerTy(); 591 if (LIsPointer != RIsPointer) 592 return (int)LIsPointer - (int)RIsPointer; 593 594 // Compare getValueID values. 595 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 596 if (LID != RID) 597 return (int)LID - (int)RID; 598 599 // Sort arguments by their position. 600 if (const auto *LA = dyn_cast<Argument>(LV)) { 601 const auto *RA = cast<Argument>(RV); 602 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 603 return (int)LArgNo - (int)RArgNo; 604 } 605 606 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 607 const auto *RGV = cast<GlobalValue>(RV); 608 609 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 610 auto LT = GV->getLinkage(); 611 return !(GlobalValue::isPrivateLinkage(LT) || 612 GlobalValue::isInternalLinkage(LT)); 613 }; 614 615 // Use the names to distinguish the two values, but only if the 616 // names are semantically important. 617 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 618 return LGV->getName().compare(RGV->getName()); 619 } 620 621 // For instructions, compare their loop depth, and their operand count. This 622 // is pretty loose. 623 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 624 const auto *RInst = cast<Instruction>(RV); 625 626 // Compare loop depths. 627 const BasicBlock *LParent = LInst->getParent(), 628 *RParent = RInst->getParent(); 629 if (LParent != RParent) { 630 unsigned LDepth = LI->getLoopDepth(LParent), 631 RDepth = LI->getLoopDepth(RParent); 632 if (LDepth != RDepth) 633 return (int)LDepth - (int)RDepth; 634 } 635 636 // Compare the number of operands. 637 unsigned LNumOps = LInst->getNumOperands(), 638 RNumOps = RInst->getNumOperands(); 639 if (LNumOps != RNumOps) 640 return (int)LNumOps - (int)RNumOps; 641 642 for (unsigned Idx : seq(0u, LNumOps)) { 643 int Result = 644 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 645 RInst->getOperand(Idx), Depth + 1); 646 if (Result != 0) 647 return Result; 648 } 649 } 650 651 EqCacheValue.unionSets(LV, RV); 652 return 0; 653 } 654 655 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 656 // than RHS, respectively. A three-way result allows recursive comparisons to be 657 // more efficient. 658 static int CompareSCEVComplexity( 659 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 660 EquivalenceClasses<const Value *> &EqCacheValue, 661 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 662 DominatorTree &DT, unsigned Depth = 0) { 663 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 664 if (LHS == RHS) 665 return 0; 666 667 // Primarily, sort the SCEVs by their getSCEVType(). 668 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 669 if (LType != RType) 670 return (int)LType - (int)RType; 671 672 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 673 return 0; 674 // Aside from the getSCEVType() ordering, the particular ordering 675 // isn't very important except that it's beneficial to be consistent, 676 // so that (a + b) and (b + a) don't end up as different expressions. 677 switch (static_cast<SCEVTypes>(LType)) { 678 case scUnknown: { 679 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 680 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 681 682 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 683 RU->getValue(), Depth + 1); 684 if (X == 0) 685 EqCacheSCEV.unionSets(LHS, RHS); 686 return X; 687 } 688 689 case scConstant: { 690 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 691 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 692 693 // Compare constant values. 694 const APInt &LA = LC->getAPInt(); 695 const APInt &RA = RC->getAPInt(); 696 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 697 if (LBitWidth != RBitWidth) 698 return (int)LBitWidth - (int)RBitWidth; 699 return LA.ult(RA) ? -1 : 1; 700 } 701 702 case scAddRecExpr: { 703 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 704 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 705 706 // There is always a dominance between two recs that are used by one SCEV, 707 // so we can safely sort recs by loop header dominance. We require such 708 // order in getAddExpr. 709 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 710 if (LLoop != RLoop) { 711 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 712 assert(LHead != RHead && "Two loops share the same header?"); 713 if (DT.dominates(LHead, RHead)) 714 return 1; 715 else 716 assert(DT.dominates(RHead, LHead) && 717 "No dominance between recurrences used by one SCEV?"); 718 return -1; 719 } 720 721 // Addrec complexity grows with operand count. 722 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 723 if (LNumOps != RNumOps) 724 return (int)LNumOps - (int)RNumOps; 725 726 // Lexicographically compare. 727 for (unsigned i = 0; i != LNumOps; ++i) { 728 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 729 LA->getOperand(i), RA->getOperand(i), DT, 730 Depth + 1); 731 if (X != 0) 732 return X; 733 } 734 EqCacheSCEV.unionSets(LHS, RHS); 735 return 0; 736 } 737 738 case scAddExpr: 739 case scMulExpr: 740 case scSMaxExpr: 741 case scUMaxExpr: 742 case scSMinExpr: 743 case scUMinExpr: { 744 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 745 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 746 747 // Lexicographically compare n-ary expressions. 748 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 749 if (LNumOps != RNumOps) 750 return (int)LNumOps - (int)RNumOps; 751 752 for (unsigned i = 0; i != LNumOps; ++i) { 753 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 754 LC->getOperand(i), RC->getOperand(i), DT, 755 Depth + 1); 756 if (X != 0) 757 return X; 758 } 759 EqCacheSCEV.unionSets(LHS, RHS); 760 return 0; 761 } 762 763 case scUDivExpr: { 764 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 765 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 766 767 // Lexicographically compare udiv expressions. 768 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 769 RC->getLHS(), DT, Depth + 1); 770 if (X != 0) 771 return X; 772 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 773 RC->getRHS(), DT, Depth + 1); 774 if (X == 0) 775 EqCacheSCEV.unionSets(LHS, RHS); 776 return X; 777 } 778 779 case scTruncate: 780 case scZeroExtend: 781 case scSignExtend: { 782 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 783 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 784 785 // Compare cast expressions by operand. 786 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 787 LC->getOperand(), RC->getOperand(), DT, 788 Depth + 1); 789 if (X == 0) 790 EqCacheSCEV.unionSets(LHS, RHS); 791 return X; 792 } 793 794 case scCouldNotCompute: 795 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 796 } 797 llvm_unreachable("Unknown SCEV kind!"); 798 } 799 800 /// Given a list of SCEV objects, order them by their complexity, and group 801 /// objects of the same complexity together by value. When this routine is 802 /// finished, we know that any duplicates in the vector are consecutive and that 803 /// complexity is monotonically increasing. 804 /// 805 /// Note that we go take special precautions to ensure that we get deterministic 806 /// results from this routine. In other words, we don't want the results of 807 /// this to depend on where the addresses of various SCEV objects happened to 808 /// land in memory. 809 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 810 LoopInfo *LI, DominatorTree &DT) { 811 if (Ops.size() < 2) return; // Noop 812 813 EquivalenceClasses<const SCEV *> EqCacheSCEV; 814 EquivalenceClasses<const Value *> EqCacheValue; 815 if (Ops.size() == 2) { 816 // This is the common case, which also happens to be trivially simple. 817 // Special case it. 818 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 819 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 820 std::swap(LHS, RHS); 821 return; 822 } 823 824 // Do the rough sort by complexity. 825 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 826 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 827 0; 828 }); 829 830 // Now that we are sorted by complexity, group elements of the same 831 // complexity. Note that this is, at worst, N^2, but the vector is likely to 832 // be extremely short in practice. Note that we take this approach because we 833 // do not want to depend on the addresses of the objects we are grouping. 834 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 835 const SCEV *S = Ops[i]; 836 unsigned Complexity = S->getSCEVType(); 837 838 // If there are any objects of the same complexity and same value as this 839 // one, group them. 840 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 841 if (Ops[j] == S) { // Found a duplicate. 842 // Move it to immediately after i'th element. 843 std::swap(Ops[i+1], Ops[j]); 844 ++i; // no need to rescan it. 845 if (i == e-2) return; // Done! 846 } 847 } 848 } 849 } 850 851 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 852 /// least HugeExprThreshold nodes). 853 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 854 return any_of(Ops, [](const SCEV *S) { 855 return S->getExpressionSize() >= HugeExprThreshold; 856 }); 857 } 858 859 //===----------------------------------------------------------------------===// 860 // Simple SCEV method implementations 861 //===----------------------------------------------------------------------===// 862 863 /// Compute BC(It, K). The result has width W. Assume, K > 0. 864 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 865 ScalarEvolution &SE, 866 Type *ResultTy) { 867 // Handle the simplest case efficiently. 868 if (K == 1) 869 return SE.getTruncateOrZeroExtend(It, ResultTy); 870 871 // We are using the following formula for BC(It, K): 872 // 873 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 874 // 875 // Suppose, W is the bitwidth of the return value. We must be prepared for 876 // overflow. Hence, we must assure that the result of our computation is 877 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 878 // safe in modular arithmetic. 879 // 880 // However, this code doesn't use exactly that formula; the formula it uses 881 // is something like the following, where T is the number of factors of 2 in 882 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 883 // exponentiation: 884 // 885 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 886 // 887 // This formula is trivially equivalent to the previous formula. However, 888 // this formula can be implemented much more efficiently. The trick is that 889 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 890 // arithmetic. To do exact division in modular arithmetic, all we have 891 // to do is multiply by the inverse. Therefore, this step can be done at 892 // width W. 893 // 894 // The next issue is how to safely do the division by 2^T. The way this 895 // is done is by doing the multiplication step at a width of at least W + T 896 // bits. This way, the bottom W+T bits of the product are accurate. Then, 897 // when we perform the division by 2^T (which is equivalent to a right shift 898 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 899 // truncated out after the division by 2^T. 900 // 901 // In comparison to just directly using the first formula, this technique 902 // is much more efficient; using the first formula requires W * K bits, 903 // but this formula less than W + K bits. Also, the first formula requires 904 // a division step, whereas this formula only requires multiplies and shifts. 905 // 906 // It doesn't matter whether the subtraction step is done in the calculation 907 // width or the input iteration count's width; if the subtraction overflows, 908 // the result must be zero anyway. We prefer here to do it in the width of 909 // the induction variable because it helps a lot for certain cases; CodeGen 910 // isn't smart enough to ignore the overflow, which leads to much less 911 // efficient code if the width of the subtraction is wider than the native 912 // register width. 913 // 914 // (It's possible to not widen at all by pulling out factors of 2 before 915 // the multiplication; for example, K=2 can be calculated as 916 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 917 // extra arithmetic, so it's not an obvious win, and it gets 918 // much more complicated for K > 3.) 919 920 // Protection from insane SCEVs; this bound is conservative, 921 // but it probably doesn't matter. 922 if (K > 1000) 923 return SE.getCouldNotCompute(); 924 925 unsigned W = SE.getTypeSizeInBits(ResultTy); 926 927 // Calculate K! / 2^T and T; we divide out the factors of two before 928 // multiplying for calculating K! / 2^T to avoid overflow. 929 // Other overflow doesn't matter because we only care about the bottom 930 // W bits of the result. 931 APInt OddFactorial(W, 1); 932 unsigned T = 1; 933 for (unsigned i = 3; i <= K; ++i) { 934 APInt Mult(W, i); 935 unsigned TwoFactors = Mult.countTrailingZeros(); 936 T += TwoFactors; 937 Mult.lshrInPlace(TwoFactors); 938 OddFactorial *= Mult; 939 } 940 941 // We need at least W + T bits for the multiplication step 942 unsigned CalculationBits = W + T; 943 944 // Calculate 2^T, at width T+W. 945 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 946 947 // Calculate the multiplicative inverse of K! / 2^T; 948 // this multiplication factor will perform the exact division by 949 // K! / 2^T. 950 APInt Mod = APInt::getSignedMinValue(W+1); 951 APInt MultiplyFactor = OddFactorial.zext(W+1); 952 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 953 MultiplyFactor = MultiplyFactor.trunc(W); 954 955 // Calculate the product, at width T+W 956 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 957 CalculationBits); 958 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 959 for (unsigned i = 1; i != K; ++i) { 960 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 961 Dividend = SE.getMulExpr(Dividend, 962 SE.getTruncateOrZeroExtend(S, CalculationTy)); 963 } 964 965 // Divide by 2^T 966 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 967 968 // Truncate the result, and divide by K! / 2^T. 969 970 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 971 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 972 } 973 974 /// Return the value of this chain of recurrences at the specified iteration 975 /// number. We can evaluate this recurrence by multiplying each element in the 976 /// chain by the binomial coefficient corresponding to it. In other words, we 977 /// can evaluate {A,+,B,+,C,+,D} as: 978 /// 979 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 980 /// 981 /// where BC(It, k) stands for binomial coefficient. 982 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 983 ScalarEvolution &SE) const { 984 const SCEV *Result = getStart(); 985 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 986 // The computation is correct in the face of overflow provided that the 987 // multiplication is performed _after_ the evaluation of the binomial 988 // coefficient. 989 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 990 if (isa<SCEVCouldNotCompute>(Coeff)) 991 return Coeff; 992 993 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 994 } 995 return Result; 996 } 997 998 //===----------------------------------------------------------------------===// 999 // SCEV Expression folder implementations 1000 //===----------------------------------------------------------------------===// 1001 1002 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1003 unsigned Depth) { 1004 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1005 "This is not a truncating conversion!"); 1006 assert(isSCEVable(Ty) && 1007 "This is not a conversion to a SCEVable type!"); 1008 Ty = getEffectiveSCEVType(Ty); 1009 1010 FoldingSetNodeID ID; 1011 ID.AddInteger(scTruncate); 1012 ID.AddPointer(Op); 1013 ID.AddPointer(Ty); 1014 void *IP = nullptr; 1015 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1016 1017 // Fold if the operand is constant. 1018 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1019 return getConstant( 1020 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1021 1022 // trunc(trunc(x)) --> trunc(x) 1023 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1024 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1025 1026 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1027 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1028 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1029 1030 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1031 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1032 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1033 1034 if (Depth > MaxCastDepth) { 1035 SCEV *S = 1036 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1037 UniqueSCEVs.InsertNode(S, IP); 1038 addToLoopUseLists(S); 1039 return S; 1040 } 1041 1042 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1043 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1044 // if after transforming we have at most one truncate, not counting truncates 1045 // that replace other casts. 1046 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1047 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1048 SmallVector<const SCEV *, 4> Operands; 1049 unsigned numTruncs = 0; 1050 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1051 ++i) { 1052 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1053 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1054 numTruncs++; 1055 Operands.push_back(S); 1056 } 1057 if (numTruncs < 2) { 1058 if (isa<SCEVAddExpr>(Op)) 1059 return getAddExpr(Operands); 1060 else if (isa<SCEVMulExpr>(Op)) 1061 return getMulExpr(Operands); 1062 else 1063 llvm_unreachable("Unexpected SCEV type for Op."); 1064 } 1065 // Although we checked in the beginning that ID is not in the cache, it is 1066 // possible that during recursion and different modification ID was inserted 1067 // into the cache. So if we find it, just return it. 1068 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1069 return S; 1070 } 1071 1072 // If the input value is a chrec scev, truncate the chrec's operands. 1073 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1074 SmallVector<const SCEV *, 4> Operands; 1075 for (const SCEV *Op : AddRec->operands()) 1076 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1077 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1078 } 1079 1080 // The cast wasn't folded; create an explicit cast node. We can reuse 1081 // the existing insert position since if we get here, we won't have 1082 // made any changes which would invalidate it. 1083 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1084 Op, Ty); 1085 UniqueSCEVs.InsertNode(S, IP); 1086 addToLoopUseLists(S); 1087 return S; 1088 } 1089 1090 // Get the limit of a recurrence such that incrementing by Step cannot cause 1091 // signed overflow as long as the value of the recurrence within the 1092 // loop does not exceed this limit before incrementing. 1093 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1094 ICmpInst::Predicate *Pred, 1095 ScalarEvolution *SE) { 1096 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1097 if (SE->isKnownPositive(Step)) { 1098 *Pred = ICmpInst::ICMP_SLT; 1099 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1100 SE->getSignedRangeMax(Step)); 1101 } 1102 if (SE->isKnownNegative(Step)) { 1103 *Pred = ICmpInst::ICMP_SGT; 1104 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1105 SE->getSignedRangeMin(Step)); 1106 } 1107 return nullptr; 1108 } 1109 1110 // Get the limit of a recurrence such that incrementing by Step cannot cause 1111 // unsigned overflow as long as the value of the recurrence within the loop does 1112 // not exceed this limit before incrementing. 1113 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1114 ICmpInst::Predicate *Pred, 1115 ScalarEvolution *SE) { 1116 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1117 *Pred = ICmpInst::ICMP_ULT; 1118 1119 return SE->getConstant(APInt::getMinValue(BitWidth) - 1120 SE->getUnsignedRangeMax(Step)); 1121 } 1122 1123 namespace { 1124 1125 struct ExtendOpTraitsBase { 1126 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1127 unsigned); 1128 }; 1129 1130 // Used to make code generic over signed and unsigned overflow. 1131 template <typename ExtendOp> struct ExtendOpTraits { 1132 // Members present: 1133 // 1134 // static const SCEV::NoWrapFlags WrapType; 1135 // 1136 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1137 // 1138 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1139 // ICmpInst::Predicate *Pred, 1140 // ScalarEvolution *SE); 1141 }; 1142 1143 template <> 1144 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1145 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1146 1147 static const GetExtendExprTy GetExtendExpr; 1148 1149 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1150 ICmpInst::Predicate *Pred, 1151 ScalarEvolution *SE) { 1152 return getSignedOverflowLimitForStep(Step, Pred, SE); 1153 } 1154 }; 1155 1156 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1157 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1158 1159 template <> 1160 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1161 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1162 1163 static const GetExtendExprTy GetExtendExpr; 1164 1165 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1166 ICmpInst::Predicate *Pred, 1167 ScalarEvolution *SE) { 1168 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1169 } 1170 }; 1171 1172 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1173 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1174 1175 } // end anonymous namespace 1176 1177 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1178 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1179 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1180 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1181 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1182 // expression "Step + sext/zext(PreIncAR)" is congruent with 1183 // "sext/zext(PostIncAR)" 1184 template <typename ExtendOpTy> 1185 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1186 ScalarEvolution *SE, unsigned Depth) { 1187 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1188 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1189 1190 const Loop *L = AR->getLoop(); 1191 const SCEV *Start = AR->getStart(); 1192 const SCEV *Step = AR->getStepRecurrence(*SE); 1193 1194 // Check for a simple looking step prior to loop entry. 1195 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1196 if (!SA) 1197 return nullptr; 1198 1199 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1200 // subtraction is expensive. For this purpose, perform a quick and dirty 1201 // difference, by checking for Step in the operand list. 1202 SmallVector<const SCEV *, 4> DiffOps; 1203 for (const SCEV *Op : SA->operands()) 1204 if (Op != Step) 1205 DiffOps.push_back(Op); 1206 1207 if (DiffOps.size() == SA->getNumOperands()) 1208 return nullptr; 1209 1210 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1211 // `Step`: 1212 1213 // 1. NSW/NUW flags on the step increment. 1214 auto PreStartFlags = 1215 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1216 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1217 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1218 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1219 1220 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1221 // "S+X does not sign/unsign-overflow". 1222 // 1223 1224 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1225 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1226 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1227 return PreStart; 1228 1229 // 2. Direct overflow check on the step operation's expression. 1230 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1231 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1232 const SCEV *OperandExtendedStart = 1233 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1234 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1235 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1236 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1237 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1238 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1239 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1240 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1241 } 1242 return PreStart; 1243 } 1244 1245 // 3. Loop precondition. 1246 ICmpInst::Predicate Pred; 1247 const SCEV *OverflowLimit = 1248 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1249 1250 if (OverflowLimit && 1251 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1252 return PreStart; 1253 1254 return nullptr; 1255 } 1256 1257 // Get the normalized zero or sign extended expression for this AddRec's Start. 1258 template <typename ExtendOpTy> 1259 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1260 ScalarEvolution *SE, 1261 unsigned Depth) { 1262 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1263 1264 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1265 if (!PreStart) 1266 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1267 1268 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1269 Depth), 1270 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1271 } 1272 1273 // Try to prove away overflow by looking at "nearby" add recurrences. A 1274 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1275 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1276 // 1277 // Formally: 1278 // 1279 // {S,+,X} == {S-T,+,X} + T 1280 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1281 // 1282 // If ({S-T,+,X} + T) does not overflow ... (1) 1283 // 1284 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1285 // 1286 // If {S-T,+,X} does not overflow ... (2) 1287 // 1288 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1289 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1290 // 1291 // If (S-T)+T does not overflow ... (3) 1292 // 1293 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1294 // == {Ext(S),+,Ext(X)} == LHS 1295 // 1296 // Thus, if (1), (2) and (3) are true for some T, then 1297 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1298 // 1299 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1300 // does not overflow" restricted to the 0th iteration. Therefore we only need 1301 // to check for (1) and (2). 1302 // 1303 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1304 // is `Delta` (defined below). 1305 template <typename ExtendOpTy> 1306 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1307 const SCEV *Step, 1308 const Loop *L) { 1309 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1310 1311 // We restrict `Start` to a constant to prevent SCEV from spending too much 1312 // time here. It is correct (but more expensive) to continue with a 1313 // non-constant `Start` and do a general SCEV subtraction to compute 1314 // `PreStart` below. 1315 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1316 if (!StartC) 1317 return false; 1318 1319 APInt StartAI = StartC->getAPInt(); 1320 1321 for (unsigned Delta : {-2, -1, 1, 2}) { 1322 const SCEV *PreStart = getConstant(StartAI - Delta); 1323 1324 FoldingSetNodeID ID; 1325 ID.AddInteger(scAddRecExpr); 1326 ID.AddPointer(PreStart); 1327 ID.AddPointer(Step); 1328 ID.AddPointer(L); 1329 void *IP = nullptr; 1330 const auto *PreAR = 1331 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1332 1333 // Give up if we don't already have the add recurrence we need because 1334 // actually constructing an add recurrence is relatively expensive. 1335 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1336 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1337 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1338 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1339 DeltaS, &Pred, this); 1340 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1341 return true; 1342 } 1343 } 1344 1345 return false; 1346 } 1347 1348 // Finds an integer D for an expression (C + x + y + ...) such that the top 1349 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1350 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1351 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1352 // the (C + x + y + ...) expression is \p WholeAddExpr. 1353 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1354 const SCEVConstant *ConstantTerm, 1355 const SCEVAddExpr *WholeAddExpr) { 1356 const APInt C = ConstantTerm->getAPInt(); 1357 const unsigned BitWidth = C.getBitWidth(); 1358 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1359 uint32_t TZ = BitWidth; 1360 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1361 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1362 if (TZ) { 1363 // Set D to be as many least significant bits of C as possible while still 1364 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1365 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1366 } 1367 return APInt(BitWidth, 0); 1368 } 1369 1370 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1371 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1372 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1373 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1374 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1375 const APInt &ConstantStart, 1376 const SCEV *Step) { 1377 const unsigned BitWidth = ConstantStart.getBitWidth(); 1378 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1379 if (TZ) 1380 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1381 : ConstantStart; 1382 return APInt(BitWidth, 0); 1383 } 1384 1385 const SCEV * 1386 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1387 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1388 "This is not an extending conversion!"); 1389 assert(isSCEVable(Ty) && 1390 "This is not a conversion to a SCEVable type!"); 1391 Ty = getEffectiveSCEVType(Ty); 1392 1393 // Fold if the operand is constant. 1394 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1395 return getConstant( 1396 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1397 1398 // zext(zext(x)) --> zext(x) 1399 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1400 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1401 1402 // Before doing any expensive analysis, check to see if we've already 1403 // computed a SCEV for this Op and Ty. 1404 FoldingSetNodeID ID; 1405 ID.AddInteger(scZeroExtend); 1406 ID.AddPointer(Op); 1407 ID.AddPointer(Ty); 1408 void *IP = nullptr; 1409 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1410 if (Depth > MaxCastDepth) { 1411 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1412 Op, Ty); 1413 UniqueSCEVs.InsertNode(S, IP); 1414 addToLoopUseLists(S); 1415 return S; 1416 } 1417 1418 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1419 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1420 // It's possible the bits taken off by the truncate were all zero bits. If 1421 // so, we should be able to simplify this further. 1422 const SCEV *X = ST->getOperand(); 1423 ConstantRange CR = getUnsignedRange(X); 1424 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1425 unsigned NewBits = getTypeSizeInBits(Ty); 1426 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1427 CR.zextOrTrunc(NewBits))) 1428 return getTruncateOrZeroExtend(X, Ty, Depth); 1429 } 1430 1431 // If the input value is a chrec scev, and we can prove that the value 1432 // did not overflow the old, smaller, value, we can zero extend all of the 1433 // operands (often constants). This allows analysis of something like 1434 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1435 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1436 if (AR->isAffine()) { 1437 const SCEV *Start = AR->getStart(); 1438 const SCEV *Step = AR->getStepRecurrence(*this); 1439 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1440 const Loop *L = AR->getLoop(); 1441 1442 if (!AR->hasNoUnsignedWrap()) { 1443 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1444 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1445 } 1446 1447 // If we have special knowledge that this addrec won't overflow, 1448 // we don't need to do any further analysis. 1449 if (AR->hasNoUnsignedWrap()) 1450 return getAddRecExpr( 1451 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1452 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1453 1454 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1455 // Note that this serves two purposes: It filters out loops that are 1456 // simply not analyzable, and it covers the case where this code is 1457 // being called from within backedge-taken count analysis, such that 1458 // attempting to ask for the backedge-taken count would likely result 1459 // in infinite recursion. In the later case, the analysis code will 1460 // cope with a conservative value, and it will take care to purge 1461 // that value once it has finished. 1462 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1463 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1464 // Manually compute the final value for AR, checking for 1465 // overflow. 1466 1467 // Check whether the backedge-taken count can be losslessly casted to 1468 // the addrec's type. The count is always unsigned. 1469 const SCEV *CastedMaxBECount = 1470 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1471 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1472 CastedMaxBECount, MaxBECount->getType(), Depth); 1473 if (MaxBECount == RecastedMaxBECount) { 1474 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1475 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1476 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1477 SCEV::FlagAnyWrap, Depth + 1); 1478 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1479 SCEV::FlagAnyWrap, 1480 Depth + 1), 1481 WideTy, Depth + 1); 1482 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1483 const SCEV *WideMaxBECount = 1484 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1485 const SCEV *OperandExtendedAdd = 1486 getAddExpr(WideStart, 1487 getMulExpr(WideMaxBECount, 1488 getZeroExtendExpr(Step, WideTy, Depth + 1), 1489 SCEV::FlagAnyWrap, Depth + 1), 1490 SCEV::FlagAnyWrap, Depth + 1); 1491 if (ZAdd == OperandExtendedAdd) { 1492 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1493 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1494 // Return the expression with the addrec on the outside. 1495 return getAddRecExpr( 1496 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1497 Depth + 1), 1498 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1499 AR->getNoWrapFlags()); 1500 } 1501 // Similar to above, only this time treat the step value as signed. 1502 // This covers loops that count down. 1503 OperandExtendedAdd = 1504 getAddExpr(WideStart, 1505 getMulExpr(WideMaxBECount, 1506 getSignExtendExpr(Step, WideTy, Depth + 1), 1507 SCEV::FlagAnyWrap, Depth + 1), 1508 SCEV::FlagAnyWrap, Depth + 1); 1509 if (ZAdd == OperandExtendedAdd) { 1510 // Cache knowledge of AR NW, which is propagated to this AddRec. 1511 // Negative step causes unsigned wrap, but it still can't self-wrap. 1512 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1513 // Return the expression with the addrec on the outside. 1514 return getAddRecExpr( 1515 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1516 Depth + 1), 1517 getSignExtendExpr(Step, Ty, Depth + 1), L, 1518 AR->getNoWrapFlags()); 1519 } 1520 } 1521 } 1522 1523 // Normally, in the cases we can prove no-overflow via a 1524 // backedge guarding condition, we can also compute a backedge 1525 // taken count for the loop. The exceptions are assumptions and 1526 // guards present in the loop -- SCEV is not great at exploiting 1527 // these to compute max backedge taken counts, but can still use 1528 // these to prove lack of overflow. Use this fact to avoid 1529 // doing extra work that may not pay off. 1530 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1531 !AC.assumptions().empty()) { 1532 // If the backedge is guarded by a comparison with the pre-inc 1533 // value the addrec is safe. Also, if the entry is guarded by 1534 // a comparison with the start value and the backedge is 1535 // guarded by a comparison with the post-inc value, the addrec 1536 // is safe. 1537 if (isKnownPositive(Step)) { 1538 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1539 getUnsignedRangeMax(Step)); 1540 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1541 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1542 // Cache knowledge of AR NUW, which is propagated to this 1543 // AddRec. 1544 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1545 // Return the expression with the addrec on the outside. 1546 return getAddRecExpr( 1547 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1548 Depth + 1), 1549 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1550 AR->getNoWrapFlags()); 1551 } 1552 } else if (isKnownNegative(Step)) { 1553 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1554 getSignedRangeMin(Step)); 1555 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1556 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1557 // Cache knowledge of AR NW, which is propagated to this 1558 // AddRec. Negative step causes unsigned wrap, but it 1559 // still can't self-wrap. 1560 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1561 // Return the expression with the addrec on the outside. 1562 return getAddRecExpr( 1563 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1564 Depth + 1), 1565 getSignExtendExpr(Step, Ty, Depth + 1), L, 1566 AR->getNoWrapFlags()); 1567 } 1568 } 1569 } 1570 1571 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1572 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1573 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1574 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1575 const APInt &C = SC->getAPInt(); 1576 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1577 if (D != 0) { 1578 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1579 const SCEV *SResidual = 1580 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1581 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1582 return getAddExpr(SZExtD, SZExtR, 1583 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1584 Depth + 1); 1585 } 1586 } 1587 1588 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1589 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1590 return getAddRecExpr( 1591 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1592 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1593 } 1594 } 1595 1596 // zext(A % B) --> zext(A) % zext(B) 1597 { 1598 const SCEV *LHS; 1599 const SCEV *RHS; 1600 if (matchURem(Op, LHS, RHS)) 1601 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1602 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1603 } 1604 1605 // zext(A / B) --> zext(A) / zext(B). 1606 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1607 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1608 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1609 1610 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1611 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1612 if (SA->hasNoUnsignedWrap()) { 1613 // If the addition does not unsign overflow then we can, by definition, 1614 // commute the zero extension with the addition operation. 1615 SmallVector<const SCEV *, 4> Ops; 1616 for (const auto *Op : SA->operands()) 1617 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1618 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1619 } 1620 1621 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1622 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1623 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1624 // 1625 // Often address arithmetics contain expressions like 1626 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1627 // This transformation is useful while proving that such expressions are 1628 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1629 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1630 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1631 if (D != 0) { 1632 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1633 const SCEV *SResidual = 1634 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1635 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1636 return getAddExpr(SZExtD, SZExtR, 1637 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1638 Depth + 1); 1639 } 1640 } 1641 } 1642 1643 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1644 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1645 if (SM->hasNoUnsignedWrap()) { 1646 // If the multiply does not unsign overflow then we can, by definition, 1647 // commute the zero extension with the multiply operation. 1648 SmallVector<const SCEV *, 4> Ops; 1649 for (const auto *Op : SM->operands()) 1650 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1651 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1652 } 1653 1654 // zext(2^K * (trunc X to iN)) to iM -> 1655 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1656 // 1657 // Proof: 1658 // 1659 // zext(2^K * (trunc X to iN)) to iM 1660 // = zext((trunc X to iN) << K) to iM 1661 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1662 // (because shl removes the top K bits) 1663 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1664 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1665 // 1666 if (SM->getNumOperands() == 2) 1667 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1668 if (MulLHS->getAPInt().isPowerOf2()) 1669 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1670 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1671 MulLHS->getAPInt().logBase2(); 1672 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1673 return getMulExpr( 1674 getZeroExtendExpr(MulLHS, Ty), 1675 getZeroExtendExpr( 1676 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1677 SCEV::FlagNUW, Depth + 1); 1678 } 1679 } 1680 1681 // The cast wasn't folded; create an explicit cast node. 1682 // Recompute the insert position, as it may have been invalidated. 1683 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1684 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1685 Op, Ty); 1686 UniqueSCEVs.InsertNode(S, IP); 1687 addToLoopUseLists(S); 1688 return S; 1689 } 1690 1691 const SCEV * 1692 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1693 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1694 "This is not an extending conversion!"); 1695 assert(isSCEVable(Ty) && 1696 "This is not a conversion to a SCEVable type!"); 1697 Ty = getEffectiveSCEVType(Ty); 1698 1699 // Fold if the operand is constant. 1700 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1701 return getConstant( 1702 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1703 1704 // sext(sext(x)) --> sext(x) 1705 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1706 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1707 1708 // sext(zext(x)) --> zext(x) 1709 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1710 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1711 1712 // Before doing any expensive analysis, check to see if we've already 1713 // computed a SCEV for this Op and Ty. 1714 FoldingSetNodeID ID; 1715 ID.AddInteger(scSignExtend); 1716 ID.AddPointer(Op); 1717 ID.AddPointer(Ty); 1718 void *IP = nullptr; 1719 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1720 // Limit recursion depth. 1721 if (Depth > MaxCastDepth) { 1722 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1723 Op, Ty); 1724 UniqueSCEVs.InsertNode(S, IP); 1725 addToLoopUseLists(S); 1726 return S; 1727 } 1728 1729 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1730 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1731 // It's possible the bits taken off by the truncate were all sign bits. If 1732 // so, we should be able to simplify this further. 1733 const SCEV *X = ST->getOperand(); 1734 ConstantRange CR = getSignedRange(X); 1735 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1736 unsigned NewBits = getTypeSizeInBits(Ty); 1737 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1738 CR.sextOrTrunc(NewBits))) 1739 return getTruncateOrSignExtend(X, Ty, Depth); 1740 } 1741 1742 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1743 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1744 if (SA->hasNoSignedWrap()) { 1745 // If the addition does not sign overflow then we can, by definition, 1746 // commute the sign extension with the addition operation. 1747 SmallVector<const SCEV *, 4> Ops; 1748 for (const auto *Op : SA->operands()) 1749 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1750 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1751 } 1752 1753 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1754 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1755 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1756 // 1757 // For instance, this will bring two seemingly different expressions: 1758 // 1 + sext(5 + 20 * %x + 24 * %y) and 1759 // sext(6 + 20 * %x + 24 * %y) 1760 // to the same form: 1761 // 2 + sext(4 + 20 * %x + 24 * %y) 1762 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1763 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1764 if (D != 0) { 1765 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1766 const SCEV *SResidual = 1767 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1768 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1769 return getAddExpr(SSExtD, SSExtR, 1770 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1771 Depth + 1); 1772 } 1773 } 1774 } 1775 // If the input value is a chrec scev, and we can prove that the value 1776 // did not overflow the old, smaller, value, we can sign extend all of the 1777 // operands (often constants). This allows analysis of something like 1778 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1779 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1780 if (AR->isAffine()) { 1781 const SCEV *Start = AR->getStart(); 1782 const SCEV *Step = AR->getStepRecurrence(*this); 1783 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1784 const Loop *L = AR->getLoop(); 1785 1786 if (!AR->hasNoSignedWrap()) { 1787 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1788 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1789 } 1790 1791 // If we have special knowledge that this addrec won't overflow, 1792 // we don't need to do any further analysis. 1793 if (AR->hasNoSignedWrap()) 1794 return getAddRecExpr( 1795 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1796 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1797 1798 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1799 // Note that this serves two purposes: It filters out loops that are 1800 // simply not analyzable, and it covers the case where this code is 1801 // being called from within backedge-taken count analysis, such that 1802 // attempting to ask for the backedge-taken count would likely result 1803 // in infinite recursion. In the later case, the analysis code will 1804 // cope with a conservative value, and it will take care to purge 1805 // that value once it has finished. 1806 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1807 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1808 // Manually compute the final value for AR, checking for 1809 // overflow. 1810 1811 // Check whether the backedge-taken count can be losslessly casted to 1812 // the addrec's type. The count is always unsigned. 1813 const SCEV *CastedMaxBECount = 1814 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1815 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1816 CastedMaxBECount, MaxBECount->getType(), Depth); 1817 if (MaxBECount == RecastedMaxBECount) { 1818 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1819 // Check whether Start+Step*MaxBECount has no signed overflow. 1820 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1821 SCEV::FlagAnyWrap, Depth + 1); 1822 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1823 SCEV::FlagAnyWrap, 1824 Depth + 1), 1825 WideTy, Depth + 1); 1826 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1827 const SCEV *WideMaxBECount = 1828 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1829 const SCEV *OperandExtendedAdd = 1830 getAddExpr(WideStart, 1831 getMulExpr(WideMaxBECount, 1832 getSignExtendExpr(Step, WideTy, Depth + 1), 1833 SCEV::FlagAnyWrap, Depth + 1), 1834 SCEV::FlagAnyWrap, Depth + 1); 1835 if (SAdd == OperandExtendedAdd) { 1836 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1837 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1838 // Return the expression with the addrec on the outside. 1839 return getAddRecExpr( 1840 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1841 Depth + 1), 1842 getSignExtendExpr(Step, Ty, Depth + 1), L, 1843 AR->getNoWrapFlags()); 1844 } 1845 // Similar to above, only this time treat the step value as unsigned. 1846 // This covers loops that count up with an unsigned step. 1847 OperandExtendedAdd = 1848 getAddExpr(WideStart, 1849 getMulExpr(WideMaxBECount, 1850 getZeroExtendExpr(Step, WideTy, Depth + 1), 1851 SCEV::FlagAnyWrap, Depth + 1), 1852 SCEV::FlagAnyWrap, Depth + 1); 1853 if (SAdd == OperandExtendedAdd) { 1854 // If AR wraps around then 1855 // 1856 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 1857 // => SAdd != OperandExtendedAdd 1858 // 1859 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 1860 // (SAdd == OperandExtendedAdd => AR is NW) 1861 1862 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1863 1864 // Return the expression with the addrec on the outside. 1865 return getAddRecExpr( 1866 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1867 Depth + 1), 1868 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1869 AR->getNoWrapFlags()); 1870 } 1871 } 1872 } 1873 1874 // Normally, in the cases we can prove no-overflow via a 1875 // backedge guarding condition, we can also compute a backedge 1876 // taken count for the loop. The exceptions are assumptions and 1877 // guards present in the loop -- SCEV is not great at exploiting 1878 // these to compute max backedge taken counts, but can still use 1879 // these to prove lack of overflow. Use this fact to avoid 1880 // doing extra work that may not pay off. 1881 1882 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1883 !AC.assumptions().empty()) { 1884 // If the backedge is guarded by a comparison with the pre-inc 1885 // value the addrec is safe. Also, if the entry is guarded by 1886 // a comparison with the start value and the backedge is 1887 // guarded by a comparison with the post-inc value, the addrec 1888 // is safe. 1889 ICmpInst::Predicate Pred; 1890 const SCEV *OverflowLimit = 1891 getSignedOverflowLimitForStep(Step, &Pred, this); 1892 if (OverflowLimit && 1893 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 1894 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 1895 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 1896 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1897 return getAddRecExpr( 1898 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1899 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1900 } 1901 } 1902 1903 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 1904 // if D + (C - D + Step * n) could be proven to not signed wrap 1905 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1906 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1907 const APInt &C = SC->getAPInt(); 1908 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1909 if (D != 0) { 1910 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1911 const SCEV *SResidual = 1912 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1913 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1914 return getAddExpr(SSExtD, SSExtR, 1915 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1916 Depth + 1); 1917 } 1918 } 1919 1920 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 1921 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1922 return getAddRecExpr( 1923 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1924 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1925 } 1926 } 1927 1928 // If the input value is provably positive and we could not simplify 1929 // away the sext build a zext instead. 1930 if (isKnownNonNegative(Op)) 1931 return getZeroExtendExpr(Op, Ty, Depth + 1); 1932 1933 // The cast wasn't folded; create an explicit cast node. 1934 // Recompute the insert position, as it may have been invalidated. 1935 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1936 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1937 Op, Ty); 1938 UniqueSCEVs.InsertNode(S, IP); 1939 addToLoopUseLists(S); 1940 return S; 1941 } 1942 1943 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 1944 /// unspecified bits out to the given type. 1945 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 1946 Type *Ty) { 1947 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1948 "This is not an extending conversion!"); 1949 assert(isSCEVable(Ty) && 1950 "This is not a conversion to a SCEVable type!"); 1951 Ty = getEffectiveSCEVType(Ty); 1952 1953 // Sign-extend negative constants. 1954 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1955 if (SC->getAPInt().isNegative()) 1956 return getSignExtendExpr(Op, Ty); 1957 1958 // Peel off a truncate cast. 1959 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 1960 const SCEV *NewOp = T->getOperand(); 1961 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 1962 return getAnyExtendExpr(NewOp, Ty); 1963 return getTruncateOrNoop(NewOp, Ty); 1964 } 1965 1966 // Next try a zext cast. If the cast is folded, use it. 1967 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 1968 if (!isa<SCEVZeroExtendExpr>(ZExt)) 1969 return ZExt; 1970 1971 // Next try a sext cast. If the cast is folded, use it. 1972 const SCEV *SExt = getSignExtendExpr(Op, Ty); 1973 if (!isa<SCEVSignExtendExpr>(SExt)) 1974 return SExt; 1975 1976 // Force the cast to be folded into the operands of an addrec. 1977 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 1978 SmallVector<const SCEV *, 4> Ops; 1979 for (const SCEV *Op : AR->operands()) 1980 Ops.push_back(getAnyExtendExpr(Op, Ty)); 1981 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 1982 } 1983 1984 // If the expression is obviously signed, use the sext cast value. 1985 if (isa<SCEVSMaxExpr>(Op)) 1986 return SExt; 1987 1988 // Absent any other information, use the zext cast value. 1989 return ZExt; 1990 } 1991 1992 /// Process the given Ops list, which is a list of operands to be added under 1993 /// the given scale, update the given map. This is a helper function for 1994 /// getAddRecExpr. As an example of what it does, given a sequence of operands 1995 /// that would form an add expression like this: 1996 /// 1997 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 1998 /// 1999 /// where A and B are constants, update the map with these values: 2000 /// 2001 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2002 /// 2003 /// and add 13 + A*B*29 to AccumulatedConstant. 2004 /// This will allow getAddRecExpr to produce this: 2005 /// 2006 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2007 /// 2008 /// This form often exposes folding opportunities that are hidden in 2009 /// the original operand list. 2010 /// 2011 /// Return true iff it appears that any interesting folding opportunities 2012 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2013 /// the common case where no interesting opportunities are present, and 2014 /// is also used as a check to avoid infinite recursion. 2015 static bool 2016 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2017 SmallVectorImpl<const SCEV *> &NewOps, 2018 APInt &AccumulatedConstant, 2019 const SCEV *const *Ops, size_t NumOperands, 2020 const APInt &Scale, 2021 ScalarEvolution &SE) { 2022 bool Interesting = false; 2023 2024 // Iterate over the add operands. They are sorted, with constants first. 2025 unsigned i = 0; 2026 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2027 ++i; 2028 // Pull a buried constant out to the outside. 2029 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2030 Interesting = true; 2031 AccumulatedConstant += Scale * C->getAPInt(); 2032 } 2033 2034 // Next comes everything else. We're especially interested in multiplies 2035 // here, but they're in the middle, so just visit the rest with one loop. 2036 for (; i != NumOperands; ++i) { 2037 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2038 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2039 APInt NewScale = 2040 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2041 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2042 // A multiplication of a constant with another add; recurse. 2043 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2044 Interesting |= 2045 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2046 Add->op_begin(), Add->getNumOperands(), 2047 NewScale, SE); 2048 } else { 2049 // A multiplication of a constant with some other value. Update 2050 // the map. 2051 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2052 const SCEV *Key = SE.getMulExpr(MulOps); 2053 auto Pair = M.insert({Key, NewScale}); 2054 if (Pair.second) { 2055 NewOps.push_back(Pair.first->first); 2056 } else { 2057 Pair.first->second += NewScale; 2058 // The map already had an entry for this value, which may indicate 2059 // a folding opportunity. 2060 Interesting = true; 2061 } 2062 } 2063 } else { 2064 // An ordinary operand. Update the map. 2065 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2066 M.insert({Ops[i], Scale}); 2067 if (Pair.second) { 2068 NewOps.push_back(Pair.first->first); 2069 } else { 2070 Pair.first->second += Scale; 2071 // The map already had an entry for this value, which may indicate 2072 // a folding opportunity. 2073 Interesting = true; 2074 } 2075 } 2076 } 2077 2078 return Interesting; 2079 } 2080 2081 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2082 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2083 // can't-overflow flags for the operation if possible. 2084 static SCEV::NoWrapFlags 2085 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2086 const ArrayRef<const SCEV *> Ops, 2087 SCEV::NoWrapFlags Flags) { 2088 using namespace std::placeholders; 2089 2090 using OBO = OverflowingBinaryOperator; 2091 2092 bool CanAnalyze = 2093 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2094 (void)CanAnalyze; 2095 assert(CanAnalyze && "don't call from other places!"); 2096 2097 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2098 SCEV::NoWrapFlags SignOrUnsignWrap = 2099 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2100 2101 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2102 auto IsKnownNonNegative = [&](const SCEV *S) { 2103 return SE->isKnownNonNegative(S); 2104 }; 2105 2106 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2107 Flags = 2108 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2109 2110 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2111 2112 if (SignOrUnsignWrap != SignOrUnsignMask && 2113 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2114 isa<SCEVConstant>(Ops[0])) { 2115 2116 auto Opcode = [&] { 2117 switch (Type) { 2118 case scAddExpr: 2119 return Instruction::Add; 2120 case scMulExpr: 2121 return Instruction::Mul; 2122 default: 2123 llvm_unreachable("Unexpected SCEV op."); 2124 } 2125 }(); 2126 2127 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2128 2129 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2130 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2131 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2132 Opcode, C, OBO::NoSignedWrap); 2133 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2134 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2135 } 2136 2137 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2138 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2139 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2140 Opcode, C, OBO::NoUnsignedWrap); 2141 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2142 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2143 } 2144 } 2145 2146 return Flags; 2147 } 2148 2149 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2150 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2151 } 2152 2153 /// Get a canonical add expression, or something simpler if possible. 2154 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2155 SCEV::NoWrapFlags Flags, 2156 unsigned Depth) { 2157 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2158 "only nuw or nsw allowed"); 2159 assert(!Ops.empty() && "Cannot get empty add!"); 2160 if (Ops.size() == 1) return Ops[0]; 2161 #ifndef NDEBUG 2162 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2163 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2164 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2165 "SCEVAddExpr operand types don't match!"); 2166 #endif 2167 2168 // Sort by complexity, this groups all similar expression types together. 2169 GroupByComplexity(Ops, &LI, DT); 2170 2171 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2172 2173 // If there are any constants, fold them together. 2174 unsigned Idx = 0; 2175 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2176 ++Idx; 2177 assert(Idx < Ops.size()); 2178 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2179 // We found two constants, fold them together! 2180 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2181 if (Ops.size() == 2) return Ops[0]; 2182 Ops.erase(Ops.begin()+1); // Erase the folded element 2183 LHSC = cast<SCEVConstant>(Ops[0]); 2184 } 2185 2186 // If we are left with a constant zero being added, strip it off. 2187 if (LHSC->getValue()->isZero()) { 2188 Ops.erase(Ops.begin()); 2189 --Idx; 2190 } 2191 2192 if (Ops.size() == 1) return Ops[0]; 2193 } 2194 2195 // Limit recursion calls depth. 2196 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2197 return getOrCreateAddExpr(Ops, Flags); 2198 2199 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2200 static_cast<SCEVAddExpr *>(S)->setNoWrapFlags(Flags); 2201 return S; 2202 } 2203 2204 // Okay, check to see if the same value occurs in the operand list more than 2205 // once. If so, merge them together into an multiply expression. Since we 2206 // sorted the list, these values are required to be adjacent. 2207 Type *Ty = Ops[0]->getType(); 2208 bool FoundMatch = false; 2209 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2210 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2211 // Scan ahead to count how many equal operands there are. 2212 unsigned Count = 2; 2213 while (i+Count != e && Ops[i+Count] == Ops[i]) 2214 ++Count; 2215 // Merge the values into a multiply. 2216 const SCEV *Scale = getConstant(Ty, Count); 2217 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2218 if (Ops.size() == Count) 2219 return Mul; 2220 Ops[i] = Mul; 2221 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2222 --i; e -= Count - 1; 2223 FoundMatch = true; 2224 } 2225 if (FoundMatch) 2226 return getAddExpr(Ops, Flags, Depth + 1); 2227 2228 // Check for truncates. If all the operands are truncated from the same 2229 // type, see if factoring out the truncate would permit the result to be 2230 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2231 // if the contents of the resulting outer trunc fold to something simple. 2232 auto FindTruncSrcType = [&]() -> Type * { 2233 // We're ultimately looking to fold an addrec of truncs and muls of only 2234 // constants and truncs, so if we find any other types of SCEV 2235 // as operands of the addrec then we bail and return nullptr here. 2236 // Otherwise, we return the type of the operand of a trunc that we find. 2237 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2238 return T->getOperand()->getType(); 2239 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2240 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2241 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2242 return T->getOperand()->getType(); 2243 } 2244 return nullptr; 2245 }; 2246 if (auto *SrcType = FindTruncSrcType()) { 2247 SmallVector<const SCEV *, 8> LargeOps; 2248 bool Ok = true; 2249 // Check all the operands to see if they can be represented in the 2250 // source type of the truncate. 2251 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2252 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2253 if (T->getOperand()->getType() != SrcType) { 2254 Ok = false; 2255 break; 2256 } 2257 LargeOps.push_back(T->getOperand()); 2258 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2259 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2260 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2261 SmallVector<const SCEV *, 8> LargeMulOps; 2262 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2263 if (const SCEVTruncateExpr *T = 2264 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2265 if (T->getOperand()->getType() != SrcType) { 2266 Ok = false; 2267 break; 2268 } 2269 LargeMulOps.push_back(T->getOperand()); 2270 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2271 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2272 } else { 2273 Ok = false; 2274 break; 2275 } 2276 } 2277 if (Ok) 2278 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2279 } else { 2280 Ok = false; 2281 break; 2282 } 2283 } 2284 if (Ok) { 2285 // Evaluate the expression in the larger type. 2286 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2287 // If it folds to something simple, use it. Otherwise, don't. 2288 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2289 return getTruncateExpr(Fold, Ty); 2290 } 2291 } 2292 2293 // Skip past any other cast SCEVs. 2294 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2295 ++Idx; 2296 2297 // If there are add operands they would be next. 2298 if (Idx < Ops.size()) { 2299 bool DeletedAdd = false; 2300 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2301 if (Ops.size() > AddOpsInlineThreshold || 2302 Add->getNumOperands() > AddOpsInlineThreshold) 2303 break; 2304 // If we have an add, expand the add operands onto the end of the operands 2305 // list. 2306 Ops.erase(Ops.begin()+Idx); 2307 Ops.append(Add->op_begin(), Add->op_end()); 2308 DeletedAdd = true; 2309 } 2310 2311 // If we deleted at least one add, we added operands to the end of the list, 2312 // and they are not necessarily sorted. Recurse to resort and resimplify 2313 // any operands we just acquired. 2314 if (DeletedAdd) 2315 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2316 } 2317 2318 // Skip over the add expression until we get to a multiply. 2319 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2320 ++Idx; 2321 2322 // Check to see if there are any folding opportunities present with 2323 // operands multiplied by constant values. 2324 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2325 uint64_t BitWidth = getTypeSizeInBits(Ty); 2326 DenseMap<const SCEV *, APInt> M; 2327 SmallVector<const SCEV *, 8> NewOps; 2328 APInt AccumulatedConstant(BitWidth, 0); 2329 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2330 Ops.data(), Ops.size(), 2331 APInt(BitWidth, 1), *this)) { 2332 struct APIntCompare { 2333 bool operator()(const APInt &LHS, const APInt &RHS) const { 2334 return LHS.ult(RHS); 2335 } 2336 }; 2337 2338 // Some interesting folding opportunity is present, so its worthwhile to 2339 // re-generate the operands list. Group the operands by constant scale, 2340 // to avoid multiplying by the same constant scale multiple times. 2341 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2342 for (const SCEV *NewOp : NewOps) 2343 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2344 // Re-generate the operands list. 2345 Ops.clear(); 2346 if (AccumulatedConstant != 0) 2347 Ops.push_back(getConstant(AccumulatedConstant)); 2348 for (auto &MulOp : MulOpLists) 2349 if (MulOp.first != 0) 2350 Ops.push_back(getMulExpr( 2351 getConstant(MulOp.first), 2352 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2353 SCEV::FlagAnyWrap, Depth + 1)); 2354 if (Ops.empty()) 2355 return getZero(Ty); 2356 if (Ops.size() == 1) 2357 return Ops[0]; 2358 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2359 } 2360 } 2361 2362 // If we are adding something to a multiply expression, make sure the 2363 // something is not already an operand of the multiply. If so, merge it into 2364 // the multiply. 2365 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2366 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2367 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2368 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2369 if (isa<SCEVConstant>(MulOpSCEV)) 2370 continue; 2371 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2372 if (MulOpSCEV == Ops[AddOp]) { 2373 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2374 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2375 if (Mul->getNumOperands() != 2) { 2376 // If the multiply has more than two operands, we must get the 2377 // Y*Z term. 2378 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2379 Mul->op_begin()+MulOp); 2380 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2381 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2382 } 2383 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2384 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2385 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2386 SCEV::FlagAnyWrap, Depth + 1); 2387 if (Ops.size() == 2) return OuterMul; 2388 if (AddOp < Idx) { 2389 Ops.erase(Ops.begin()+AddOp); 2390 Ops.erase(Ops.begin()+Idx-1); 2391 } else { 2392 Ops.erase(Ops.begin()+Idx); 2393 Ops.erase(Ops.begin()+AddOp-1); 2394 } 2395 Ops.push_back(OuterMul); 2396 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2397 } 2398 2399 // Check this multiply against other multiplies being added together. 2400 for (unsigned OtherMulIdx = Idx+1; 2401 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2402 ++OtherMulIdx) { 2403 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2404 // If MulOp occurs in OtherMul, we can fold the two multiplies 2405 // together. 2406 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2407 OMulOp != e; ++OMulOp) 2408 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2409 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2410 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2411 if (Mul->getNumOperands() != 2) { 2412 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2413 Mul->op_begin()+MulOp); 2414 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2415 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2416 } 2417 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2418 if (OtherMul->getNumOperands() != 2) { 2419 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2420 OtherMul->op_begin()+OMulOp); 2421 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2422 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2423 } 2424 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2425 const SCEV *InnerMulSum = 2426 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2427 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2428 SCEV::FlagAnyWrap, Depth + 1); 2429 if (Ops.size() == 2) return OuterMul; 2430 Ops.erase(Ops.begin()+Idx); 2431 Ops.erase(Ops.begin()+OtherMulIdx-1); 2432 Ops.push_back(OuterMul); 2433 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2434 } 2435 } 2436 } 2437 } 2438 2439 // If there are any add recurrences in the operands list, see if any other 2440 // added values are loop invariant. If so, we can fold them into the 2441 // recurrence. 2442 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2443 ++Idx; 2444 2445 // Scan over all recurrences, trying to fold loop invariants into them. 2446 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2447 // Scan all of the other operands to this add and add them to the vector if 2448 // they are loop invariant w.r.t. the recurrence. 2449 SmallVector<const SCEV *, 8> LIOps; 2450 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2451 const Loop *AddRecLoop = AddRec->getLoop(); 2452 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2453 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2454 LIOps.push_back(Ops[i]); 2455 Ops.erase(Ops.begin()+i); 2456 --i; --e; 2457 } 2458 2459 // If we found some loop invariants, fold them into the recurrence. 2460 if (!LIOps.empty()) { 2461 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2462 LIOps.push_back(AddRec->getStart()); 2463 2464 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2465 AddRec->op_end()); 2466 // This follows from the fact that the no-wrap flags on the outer add 2467 // expression are applicable on the 0th iteration, when the add recurrence 2468 // will be equal to its start value. 2469 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2470 2471 // Build the new addrec. Propagate the NUW and NSW flags if both the 2472 // outer add and the inner addrec are guaranteed to have no overflow. 2473 // Always propagate NW. 2474 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2475 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2476 2477 // If all of the other operands were loop invariant, we are done. 2478 if (Ops.size() == 1) return NewRec; 2479 2480 // Otherwise, add the folded AddRec by the non-invariant parts. 2481 for (unsigned i = 0;; ++i) 2482 if (Ops[i] == AddRec) { 2483 Ops[i] = NewRec; 2484 break; 2485 } 2486 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2487 } 2488 2489 // Okay, if there weren't any loop invariants to be folded, check to see if 2490 // there are multiple AddRec's with the same loop induction variable being 2491 // added together. If so, we can fold them. 2492 for (unsigned OtherIdx = Idx+1; 2493 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2494 ++OtherIdx) { 2495 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2496 // so that the 1st found AddRecExpr is dominated by all others. 2497 assert(DT.dominates( 2498 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2499 AddRec->getLoop()->getHeader()) && 2500 "AddRecExprs are not sorted in reverse dominance order?"); 2501 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2502 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2503 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2504 AddRec->op_end()); 2505 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2506 ++OtherIdx) { 2507 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2508 if (OtherAddRec->getLoop() == AddRecLoop) { 2509 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2510 i != e; ++i) { 2511 if (i >= AddRecOps.size()) { 2512 AddRecOps.append(OtherAddRec->op_begin()+i, 2513 OtherAddRec->op_end()); 2514 break; 2515 } 2516 SmallVector<const SCEV *, 2> TwoOps = { 2517 AddRecOps[i], OtherAddRec->getOperand(i)}; 2518 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2519 } 2520 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2521 } 2522 } 2523 // Step size has changed, so we cannot guarantee no self-wraparound. 2524 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2525 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2526 } 2527 } 2528 2529 // Otherwise couldn't fold anything into this recurrence. Move onto the 2530 // next one. 2531 } 2532 2533 // Okay, it looks like we really DO need an add expr. Check to see if we 2534 // already have one, otherwise create a new one. 2535 return getOrCreateAddExpr(Ops, Flags); 2536 } 2537 2538 const SCEV * 2539 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2540 SCEV::NoWrapFlags Flags) { 2541 FoldingSetNodeID ID; 2542 ID.AddInteger(scAddExpr); 2543 for (const SCEV *Op : Ops) 2544 ID.AddPointer(Op); 2545 void *IP = nullptr; 2546 SCEVAddExpr *S = 2547 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2548 if (!S) { 2549 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2550 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2551 S = new (SCEVAllocator) 2552 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2553 UniqueSCEVs.InsertNode(S, IP); 2554 addToLoopUseLists(S); 2555 } 2556 S->setNoWrapFlags(Flags); 2557 return S; 2558 } 2559 2560 const SCEV * 2561 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2562 const Loop *L, SCEV::NoWrapFlags Flags) { 2563 FoldingSetNodeID ID; 2564 ID.AddInteger(scAddRecExpr); 2565 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2566 ID.AddPointer(Ops[i]); 2567 ID.AddPointer(L); 2568 void *IP = nullptr; 2569 SCEVAddRecExpr *S = 2570 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2571 if (!S) { 2572 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2573 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2574 S = new (SCEVAllocator) 2575 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2576 UniqueSCEVs.InsertNode(S, IP); 2577 addToLoopUseLists(S); 2578 } 2579 S->setNoWrapFlags(Flags); 2580 return S; 2581 } 2582 2583 const SCEV * 2584 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2585 SCEV::NoWrapFlags Flags) { 2586 FoldingSetNodeID ID; 2587 ID.AddInteger(scMulExpr); 2588 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2589 ID.AddPointer(Ops[i]); 2590 void *IP = nullptr; 2591 SCEVMulExpr *S = 2592 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2593 if (!S) { 2594 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2595 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2596 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2597 O, Ops.size()); 2598 UniqueSCEVs.InsertNode(S, IP); 2599 addToLoopUseLists(S); 2600 } 2601 S->setNoWrapFlags(Flags); 2602 return S; 2603 } 2604 2605 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2606 uint64_t k = i*j; 2607 if (j > 1 && k / j != i) Overflow = true; 2608 return k; 2609 } 2610 2611 /// Compute the result of "n choose k", the binomial coefficient. If an 2612 /// intermediate computation overflows, Overflow will be set and the return will 2613 /// be garbage. Overflow is not cleared on absence of overflow. 2614 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2615 // We use the multiplicative formula: 2616 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2617 // At each iteration, we take the n-th term of the numeral and divide by the 2618 // (k-n)th term of the denominator. This division will always produce an 2619 // integral result, and helps reduce the chance of overflow in the 2620 // intermediate computations. However, we can still overflow even when the 2621 // final result would fit. 2622 2623 if (n == 0 || n == k) return 1; 2624 if (k > n) return 0; 2625 2626 if (k > n/2) 2627 k = n-k; 2628 2629 uint64_t r = 1; 2630 for (uint64_t i = 1; i <= k; ++i) { 2631 r = umul_ov(r, n-(i-1), Overflow); 2632 r /= i; 2633 } 2634 return r; 2635 } 2636 2637 /// Determine if any of the operands in this SCEV are a constant or if 2638 /// any of the add or multiply expressions in this SCEV contain a constant. 2639 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2640 struct FindConstantInAddMulChain { 2641 bool FoundConstant = false; 2642 2643 bool follow(const SCEV *S) { 2644 FoundConstant |= isa<SCEVConstant>(S); 2645 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2646 } 2647 2648 bool isDone() const { 2649 return FoundConstant; 2650 } 2651 }; 2652 2653 FindConstantInAddMulChain F; 2654 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2655 ST.visitAll(StartExpr); 2656 return F.FoundConstant; 2657 } 2658 2659 /// Get a canonical multiply expression, or something simpler if possible. 2660 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2661 SCEV::NoWrapFlags Flags, 2662 unsigned Depth) { 2663 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2664 "only nuw or nsw allowed"); 2665 assert(!Ops.empty() && "Cannot get empty mul!"); 2666 if (Ops.size() == 1) return Ops[0]; 2667 #ifndef NDEBUG 2668 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2669 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2670 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2671 "SCEVMulExpr operand types don't match!"); 2672 #endif 2673 2674 // Sort by complexity, this groups all similar expression types together. 2675 GroupByComplexity(Ops, &LI, DT); 2676 2677 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2678 2679 // Limit recursion calls depth, but fold all-constant expressions. 2680 // `Ops` is sorted, so it's enough to check just last one. 2681 if ((Depth > MaxArithDepth || hasHugeExpression(Ops)) && 2682 !isa<SCEVConstant>(Ops.back())) 2683 return getOrCreateMulExpr(Ops, Flags); 2684 2685 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2686 static_cast<SCEVMulExpr *>(S)->setNoWrapFlags(Flags); 2687 return S; 2688 } 2689 2690 // If there are any constants, fold them together. 2691 unsigned Idx = 0; 2692 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2693 2694 if (Ops.size() == 2) 2695 // C1*(C2+V) -> C1*C2 + C1*V 2696 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2697 // If any of Add's ops are Adds or Muls with a constant, apply this 2698 // transformation as well. 2699 // 2700 // TODO: There are some cases where this transformation is not 2701 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2702 // this transformation should be narrowed down. 2703 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2704 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2705 SCEV::FlagAnyWrap, Depth + 1), 2706 getMulExpr(LHSC, Add->getOperand(1), 2707 SCEV::FlagAnyWrap, Depth + 1), 2708 SCEV::FlagAnyWrap, Depth + 1); 2709 2710 ++Idx; 2711 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2712 // We found two constants, fold them together! 2713 ConstantInt *Fold = 2714 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2715 Ops[0] = getConstant(Fold); 2716 Ops.erase(Ops.begin()+1); // Erase the folded element 2717 if (Ops.size() == 1) return Ops[0]; 2718 LHSC = cast<SCEVConstant>(Ops[0]); 2719 } 2720 2721 // If we are left with a constant one being multiplied, strip it off. 2722 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2723 Ops.erase(Ops.begin()); 2724 --Idx; 2725 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2726 // If we have a multiply of zero, it will always be zero. 2727 return Ops[0]; 2728 } else if (Ops[0]->isAllOnesValue()) { 2729 // If we have a mul by -1 of an add, try distributing the -1 among the 2730 // add operands. 2731 if (Ops.size() == 2) { 2732 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2733 SmallVector<const SCEV *, 4> NewOps; 2734 bool AnyFolded = false; 2735 for (const SCEV *AddOp : Add->operands()) { 2736 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2737 Depth + 1); 2738 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2739 NewOps.push_back(Mul); 2740 } 2741 if (AnyFolded) 2742 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2743 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2744 // Negation preserves a recurrence's no self-wrap property. 2745 SmallVector<const SCEV *, 4> Operands; 2746 for (const SCEV *AddRecOp : AddRec->operands()) 2747 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2748 Depth + 1)); 2749 2750 return getAddRecExpr(Operands, AddRec->getLoop(), 2751 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2752 } 2753 } 2754 } 2755 2756 if (Ops.size() == 1) 2757 return Ops[0]; 2758 } 2759 2760 // Skip over the add expression until we get to a multiply. 2761 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2762 ++Idx; 2763 2764 // If there are mul operands inline them all into this expression. 2765 if (Idx < Ops.size()) { 2766 bool DeletedMul = false; 2767 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2768 if (Ops.size() > MulOpsInlineThreshold) 2769 break; 2770 // If we have an mul, expand the mul operands onto the end of the 2771 // operands list. 2772 Ops.erase(Ops.begin()+Idx); 2773 Ops.append(Mul->op_begin(), Mul->op_end()); 2774 DeletedMul = true; 2775 } 2776 2777 // If we deleted at least one mul, we added operands to the end of the 2778 // list, and they are not necessarily sorted. Recurse to resort and 2779 // resimplify any operands we just acquired. 2780 if (DeletedMul) 2781 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2782 } 2783 2784 // If there are any add recurrences in the operands list, see if any other 2785 // added values are loop invariant. If so, we can fold them into the 2786 // recurrence. 2787 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2788 ++Idx; 2789 2790 // Scan over all recurrences, trying to fold loop invariants into them. 2791 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2792 // Scan all of the other operands to this mul and add them to the vector 2793 // if they are loop invariant w.r.t. the recurrence. 2794 SmallVector<const SCEV *, 8> LIOps; 2795 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2796 const Loop *AddRecLoop = AddRec->getLoop(); 2797 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2798 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2799 LIOps.push_back(Ops[i]); 2800 Ops.erase(Ops.begin()+i); 2801 --i; --e; 2802 } 2803 2804 // If we found some loop invariants, fold them into the recurrence. 2805 if (!LIOps.empty()) { 2806 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2807 SmallVector<const SCEV *, 4> NewOps; 2808 NewOps.reserve(AddRec->getNumOperands()); 2809 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2810 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2811 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2812 SCEV::FlagAnyWrap, Depth + 1)); 2813 2814 // Build the new addrec. Propagate the NUW and NSW flags if both the 2815 // outer mul and the inner addrec are guaranteed to have no overflow. 2816 // 2817 // No self-wrap cannot be guaranteed after changing the step size, but 2818 // will be inferred if either NUW or NSW is true. 2819 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2820 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2821 2822 // If all of the other operands were loop invariant, we are done. 2823 if (Ops.size() == 1) return NewRec; 2824 2825 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2826 for (unsigned i = 0;; ++i) 2827 if (Ops[i] == AddRec) { 2828 Ops[i] = NewRec; 2829 break; 2830 } 2831 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2832 } 2833 2834 // Okay, if there weren't any loop invariants to be folded, check to see 2835 // if there are multiple AddRec's with the same loop induction variable 2836 // being multiplied together. If so, we can fold them. 2837 2838 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2839 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2840 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2841 // ]]],+,...up to x=2n}. 2842 // Note that the arguments to choose() are always integers with values 2843 // known at compile time, never SCEV objects. 2844 // 2845 // The implementation avoids pointless extra computations when the two 2846 // addrec's are of different length (mathematically, it's equivalent to 2847 // an infinite stream of zeros on the right). 2848 bool OpsModified = false; 2849 for (unsigned OtherIdx = Idx+1; 2850 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2851 ++OtherIdx) { 2852 const SCEVAddRecExpr *OtherAddRec = 2853 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2854 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2855 continue; 2856 2857 // Limit max number of arguments to avoid creation of unreasonably big 2858 // SCEVAddRecs with very complex operands. 2859 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 2860 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 2861 continue; 2862 2863 bool Overflow = false; 2864 Type *Ty = AddRec->getType(); 2865 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 2866 SmallVector<const SCEV*, 7> AddRecOps; 2867 for (int x = 0, xe = AddRec->getNumOperands() + 2868 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 2869 SmallVector <const SCEV *, 7> SumOps; 2870 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 2871 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 2872 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 2873 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 2874 z < ze && !Overflow; ++z) { 2875 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 2876 uint64_t Coeff; 2877 if (LargerThan64Bits) 2878 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 2879 else 2880 Coeff = Coeff1*Coeff2; 2881 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 2882 const SCEV *Term1 = AddRec->getOperand(y-z); 2883 const SCEV *Term2 = OtherAddRec->getOperand(z); 2884 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 2885 SCEV::FlagAnyWrap, Depth + 1)); 2886 } 2887 } 2888 if (SumOps.empty()) 2889 SumOps.push_back(getZero(Ty)); 2890 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 2891 } 2892 if (!Overflow) { 2893 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 2894 SCEV::FlagAnyWrap); 2895 if (Ops.size() == 2) return NewAddRec; 2896 Ops[Idx] = NewAddRec; 2897 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2898 OpsModified = true; 2899 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 2900 if (!AddRec) 2901 break; 2902 } 2903 } 2904 if (OpsModified) 2905 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2906 2907 // Otherwise couldn't fold anything into this recurrence. Move onto the 2908 // next one. 2909 } 2910 2911 // Okay, it looks like we really DO need an mul expr. Check to see if we 2912 // already have one, otherwise create a new one. 2913 return getOrCreateMulExpr(Ops, Flags); 2914 } 2915 2916 /// Represents an unsigned remainder expression based on unsigned division. 2917 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 2918 const SCEV *RHS) { 2919 assert(getEffectiveSCEVType(LHS->getType()) == 2920 getEffectiveSCEVType(RHS->getType()) && 2921 "SCEVURemExpr operand types don't match!"); 2922 2923 // Short-circuit easy cases 2924 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2925 // If constant is one, the result is trivial 2926 if (RHSC->getValue()->isOne()) 2927 return getZero(LHS->getType()); // X urem 1 --> 0 2928 2929 // If constant is a power of two, fold into a zext(trunc(LHS)). 2930 if (RHSC->getAPInt().isPowerOf2()) { 2931 Type *FullTy = LHS->getType(); 2932 Type *TruncTy = 2933 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 2934 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 2935 } 2936 } 2937 2938 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 2939 const SCEV *UDiv = getUDivExpr(LHS, RHS); 2940 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 2941 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 2942 } 2943 2944 /// Get a canonical unsigned division expression, or something simpler if 2945 /// possible. 2946 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 2947 const SCEV *RHS) { 2948 assert(getEffectiveSCEVType(LHS->getType()) == 2949 getEffectiveSCEVType(RHS->getType()) && 2950 "SCEVUDivExpr operand types don't match!"); 2951 2952 FoldingSetNodeID ID; 2953 ID.AddInteger(scUDivExpr); 2954 ID.AddPointer(LHS); 2955 ID.AddPointer(RHS); 2956 void *IP = nullptr; 2957 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 2958 return S; 2959 2960 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 2961 if (RHSC->getValue()->isOne()) 2962 return LHS; // X udiv 1 --> x 2963 // If the denominator is zero, the result of the udiv is undefined. Don't 2964 // try to analyze it, because the resolution chosen here may differ from 2965 // the resolution chosen in other parts of the compiler. 2966 if (!RHSC->getValue()->isZero()) { 2967 // Determine if the division can be folded into the operands of 2968 // its operands. 2969 // TODO: Generalize this to non-constants by using known-bits information. 2970 Type *Ty = LHS->getType(); 2971 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 2972 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 2973 // For non-power-of-two values, effectively round the value up to the 2974 // nearest power of two. 2975 if (!RHSC->getAPInt().isPowerOf2()) 2976 ++MaxShiftAmt; 2977 IntegerType *ExtTy = 2978 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 2979 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 2980 if (const SCEVConstant *Step = 2981 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 2982 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 2983 const APInt &StepInt = Step->getAPInt(); 2984 const APInt &DivInt = RHSC->getAPInt(); 2985 if (!StepInt.urem(DivInt) && 2986 getZeroExtendExpr(AR, ExtTy) == 2987 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 2988 getZeroExtendExpr(Step, ExtTy), 2989 AR->getLoop(), SCEV::FlagAnyWrap)) { 2990 SmallVector<const SCEV *, 4> Operands; 2991 for (const SCEV *Op : AR->operands()) 2992 Operands.push_back(getUDivExpr(Op, RHS)); 2993 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 2994 } 2995 /// Get a canonical UDivExpr for a recurrence. 2996 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 2997 // We can currently only fold X%N if X is constant. 2998 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 2999 if (StartC && !DivInt.urem(StepInt) && 3000 getZeroExtendExpr(AR, ExtTy) == 3001 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3002 getZeroExtendExpr(Step, ExtTy), 3003 AR->getLoop(), SCEV::FlagAnyWrap)) { 3004 const APInt &StartInt = StartC->getAPInt(); 3005 const APInt &StartRem = StartInt.urem(StepInt); 3006 if (StartRem != 0) { 3007 const SCEV *NewLHS = 3008 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3009 AR->getLoop(), SCEV::FlagNW); 3010 if (LHS != NewLHS) { 3011 LHS = NewLHS; 3012 3013 // Reset the ID to include the new LHS, and check if it is 3014 // already cached. 3015 ID.clear(); 3016 ID.AddInteger(scUDivExpr); 3017 ID.AddPointer(LHS); 3018 ID.AddPointer(RHS); 3019 IP = nullptr; 3020 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3021 return S; 3022 } 3023 } 3024 } 3025 } 3026 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3027 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3028 SmallVector<const SCEV *, 4> Operands; 3029 for (const SCEV *Op : M->operands()) 3030 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3031 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3032 // Find an operand that's safely divisible. 3033 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3034 const SCEV *Op = M->getOperand(i); 3035 const SCEV *Div = getUDivExpr(Op, RHSC); 3036 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3037 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3038 M->op_end()); 3039 Operands[i] = Div; 3040 return getMulExpr(Operands); 3041 } 3042 } 3043 } 3044 3045 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3046 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3047 if (auto *DivisorConstant = 3048 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3049 bool Overflow = false; 3050 APInt NewRHS = 3051 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3052 if (Overflow) { 3053 return getConstant(RHSC->getType(), 0, false); 3054 } 3055 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3056 } 3057 } 3058 3059 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3060 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3061 SmallVector<const SCEV *, 4> Operands; 3062 for (const SCEV *Op : A->operands()) 3063 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3064 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3065 Operands.clear(); 3066 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3067 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3068 if (isa<SCEVUDivExpr>(Op) || 3069 getMulExpr(Op, RHS) != A->getOperand(i)) 3070 break; 3071 Operands.push_back(Op); 3072 } 3073 if (Operands.size() == A->getNumOperands()) 3074 return getAddExpr(Operands); 3075 } 3076 } 3077 3078 // Fold if both operands are constant. 3079 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3080 Constant *LHSCV = LHSC->getValue(); 3081 Constant *RHSCV = RHSC->getValue(); 3082 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3083 RHSCV))); 3084 } 3085 } 3086 } 3087 3088 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3089 // changes). Make sure we get a new one. 3090 IP = nullptr; 3091 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3092 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3093 LHS, RHS); 3094 UniqueSCEVs.InsertNode(S, IP); 3095 addToLoopUseLists(S); 3096 return S; 3097 } 3098 3099 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3100 APInt A = C1->getAPInt().abs(); 3101 APInt B = C2->getAPInt().abs(); 3102 uint32_t ABW = A.getBitWidth(); 3103 uint32_t BBW = B.getBitWidth(); 3104 3105 if (ABW > BBW) 3106 B = B.zext(ABW); 3107 else if (ABW < BBW) 3108 A = A.zext(BBW); 3109 3110 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3111 } 3112 3113 /// Get a canonical unsigned division expression, or something simpler if 3114 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3115 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3116 /// it's not exact because the udiv may be clearing bits. 3117 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3118 const SCEV *RHS) { 3119 // TODO: we could try to find factors in all sorts of things, but for now we 3120 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3121 // end of this file for inspiration. 3122 3123 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3124 if (!Mul || !Mul->hasNoUnsignedWrap()) 3125 return getUDivExpr(LHS, RHS); 3126 3127 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3128 // If the mulexpr multiplies by a constant, then that constant must be the 3129 // first element of the mulexpr. 3130 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3131 if (LHSCst == RHSCst) { 3132 SmallVector<const SCEV *, 2> Operands; 3133 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3134 return getMulExpr(Operands); 3135 } 3136 3137 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3138 // that there's a factor provided by one of the other terms. We need to 3139 // check. 3140 APInt Factor = gcd(LHSCst, RHSCst); 3141 if (!Factor.isIntN(1)) { 3142 LHSCst = 3143 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3144 RHSCst = 3145 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3146 SmallVector<const SCEV *, 2> Operands; 3147 Operands.push_back(LHSCst); 3148 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3149 LHS = getMulExpr(Operands); 3150 RHS = RHSCst; 3151 Mul = dyn_cast<SCEVMulExpr>(LHS); 3152 if (!Mul) 3153 return getUDivExactExpr(LHS, RHS); 3154 } 3155 } 3156 } 3157 3158 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3159 if (Mul->getOperand(i) == RHS) { 3160 SmallVector<const SCEV *, 2> Operands; 3161 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3162 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3163 return getMulExpr(Operands); 3164 } 3165 } 3166 3167 return getUDivExpr(LHS, RHS); 3168 } 3169 3170 /// Get an add recurrence expression for the specified loop. Simplify the 3171 /// expression as much as possible. 3172 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3173 const Loop *L, 3174 SCEV::NoWrapFlags Flags) { 3175 SmallVector<const SCEV *, 4> Operands; 3176 Operands.push_back(Start); 3177 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3178 if (StepChrec->getLoop() == L) { 3179 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3180 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3181 } 3182 3183 Operands.push_back(Step); 3184 return getAddRecExpr(Operands, L, Flags); 3185 } 3186 3187 /// Get an add recurrence expression for the specified loop. Simplify the 3188 /// expression as much as possible. 3189 const SCEV * 3190 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3191 const Loop *L, SCEV::NoWrapFlags Flags) { 3192 if (Operands.size() == 1) return Operands[0]; 3193 #ifndef NDEBUG 3194 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3195 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3196 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3197 "SCEVAddRecExpr operand types don't match!"); 3198 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3199 assert(isLoopInvariant(Operands[i], L) && 3200 "SCEVAddRecExpr operand is not loop-invariant!"); 3201 #endif 3202 3203 if (Operands.back()->isZero()) { 3204 Operands.pop_back(); 3205 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3206 } 3207 3208 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3209 // use that information to infer NUW and NSW flags. However, computing a 3210 // BE count requires calling getAddRecExpr, so we may not yet have a 3211 // meaningful BE count at this point (and if we don't, we'd be stuck 3212 // with a SCEVCouldNotCompute as the cached BE count). 3213 3214 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3215 3216 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3217 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3218 const Loop *NestedLoop = NestedAR->getLoop(); 3219 if (L->contains(NestedLoop) 3220 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3221 : (!NestedLoop->contains(L) && 3222 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3223 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3224 NestedAR->op_end()); 3225 Operands[0] = NestedAR->getStart(); 3226 // AddRecs require their operands be loop-invariant with respect to their 3227 // loops. Don't perform this transformation if it would break this 3228 // requirement. 3229 bool AllInvariant = all_of( 3230 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3231 3232 if (AllInvariant) { 3233 // Create a recurrence for the outer loop with the same step size. 3234 // 3235 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3236 // inner recurrence has the same property. 3237 SCEV::NoWrapFlags OuterFlags = 3238 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3239 3240 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3241 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3242 return isLoopInvariant(Op, NestedLoop); 3243 }); 3244 3245 if (AllInvariant) { 3246 // Ok, both add recurrences are valid after the transformation. 3247 // 3248 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3249 // the outer recurrence has the same property. 3250 SCEV::NoWrapFlags InnerFlags = 3251 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3252 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3253 } 3254 } 3255 // Reset Operands to its original state. 3256 Operands[0] = NestedAR; 3257 } 3258 } 3259 3260 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3261 // already have one, otherwise create a new one. 3262 return getOrCreateAddRecExpr(Operands, L, Flags); 3263 } 3264 3265 const SCEV * 3266 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3267 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3268 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3269 // getSCEV(Base)->getType() has the same address space as Base->getType() 3270 // because SCEV::getType() preserves the address space. 3271 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3272 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3273 // instruction to its SCEV, because the Instruction may be guarded by control 3274 // flow and the no-overflow bits may not be valid for the expression in any 3275 // context. This can be fixed similarly to how these flags are handled for 3276 // adds. 3277 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3278 : SCEV::FlagAnyWrap; 3279 3280 const SCEV *TotalOffset = getZero(IntIdxTy); 3281 Type *CurTy = GEP->getType(); 3282 bool FirstIter = true; 3283 for (const SCEV *IndexExpr : IndexExprs) { 3284 // Compute the (potentially symbolic) offset in bytes for this index. 3285 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3286 // For a struct, add the member offset. 3287 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3288 unsigned FieldNo = Index->getZExtValue(); 3289 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3290 3291 // Add the field offset to the running total offset. 3292 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3293 3294 // Update CurTy to the type of the field at Index. 3295 CurTy = STy->getTypeAtIndex(Index); 3296 } else { 3297 // Update CurTy to its element type. 3298 if (FirstIter) { 3299 assert(isa<PointerType>(CurTy) && 3300 "The first index of a GEP indexes a pointer"); 3301 CurTy = GEP->getSourceElementType(); 3302 FirstIter = false; 3303 } else { 3304 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3305 } 3306 // For an array, add the element offset, explicitly scaled. 3307 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3308 // Getelementptr indices are signed. 3309 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3310 3311 // Multiply the index by the element size to compute the element offset. 3312 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3313 3314 // Add the element offset to the running total offset. 3315 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3316 } 3317 } 3318 3319 // Add the total offset from all the GEP indices to the base. 3320 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3321 } 3322 3323 std::tuple<SCEV *, FoldingSetNodeID, void *> 3324 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3325 ArrayRef<const SCEV *> Ops) { 3326 FoldingSetNodeID ID; 3327 void *IP = nullptr; 3328 ID.AddInteger(SCEVType); 3329 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3330 ID.AddPointer(Ops[i]); 3331 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3332 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3333 } 3334 3335 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3336 SmallVectorImpl<const SCEV *> &Ops) { 3337 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3338 if (Ops.size() == 1) return Ops[0]; 3339 #ifndef NDEBUG 3340 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3341 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3342 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3343 "Operand types don't match!"); 3344 #endif 3345 3346 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3347 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3348 3349 // Sort by complexity, this groups all similar expression types together. 3350 GroupByComplexity(Ops, &LI, DT); 3351 3352 // Check if we have created the same expression before. 3353 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3354 return S; 3355 } 3356 3357 // If there are any constants, fold them together. 3358 unsigned Idx = 0; 3359 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3360 ++Idx; 3361 assert(Idx < Ops.size()); 3362 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3363 if (Kind == scSMaxExpr) 3364 return APIntOps::smax(LHS, RHS); 3365 else if (Kind == scSMinExpr) 3366 return APIntOps::smin(LHS, RHS); 3367 else if (Kind == scUMaxExpr) 3368 return APIntOps::umax(LHS, RHS); 3369 else if (Kind == scUMinExpr) 3370 return APIntOps::umin(LHS, RHS); 3371 llvm_unreachable("Unknown SCEV min/max opcode"); 3372 }; 3373 3374 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3375 // We found two constants, fold them together! 3376 ConstantInt *Fold = ConstantInt::get( 3377 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3378 Ops[0] = getConstant(Fold); 3379 Ops.erase(Ops.begin()+1); // Erase the folded element 3380 if (Ops.size() == 1) return Ops[0]; 3381 LHSC = cast<SCEVConstant>(Ops[0]); 3382 } 3383 3384 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3385 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3386 3387 if (IsMax ? IsMinV : IsMaxV) { 3388 // If we are left with a constant minimum(/maximum)-int, strip it off. 3389 Ops.erase(Ops.begin()); 3390 --Idx; 3391 } else if (IsMax ? IsMaxV : IsMinV) { 3392 // If we have a max(/min) with a constant maximum(/minimum)-int, 3393 // it will always be the extremum. 3394 return LHSC; 3395 } 3396 3397 if (Ops.size() == 1) return Ops[0]; 3398 } 3399 3400 // Find the first operation of the same kind 3401 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3402 ++Idx; 3403 3404 // Check to see if one of the operands is of the same kind. If so, expand its 3405 // operands onto our operand list, and recurse to simplify. 3406 if (Idx < Ops.size()) { 3407 bool DeletedAny = false; 3408 while (Ops[Idx]->getSCEVType() == Kind) { 3409 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3410 Ops.erase(Ops.begin()+Idx); 3411 Ops.append(SMME->op_begin(), SMME->op_end()); 3412 DeletedAny = true; 3413 } 3414 3415 if (DeletedAny) 3416 return getMinMaxExpr(Kind, Ops); 3417 } 3418 3419 // Okay, check to see if the same value occurs in the operand list twice. If 3420 // so, delete one. Since we sorted the list, these values are required to 3421 // be adjacent. 3422 llvm::CmpInst::Predicate GEPred = 3423 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3424 llvm::CmpInst::Predicate LEPred = 3425 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3426 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3427 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3428 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3429 if (Ops[i] == Ops[i + 1] || 3430 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3431 // X op Y op Y --> X op Y 3432 // X op Y --> X, if we know X, Y are ordered appropriately 3433 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3434 --i; 3435 --e; 3436 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3437 Ops[i + 1])) { 3438 // X op Y --> Y, if we know X, Y are ordered appropriately 3439 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3440 --i; 3441 --e; 3442 } 3443 } 3444 3445 if (Ops.size() == 1) return Ops[0]; 3446 3447 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3448 3449 // Okay, it looks like we really DO need an expr. Check to see if we 3450 // already have one, otherwise create a new one. 3451 const SCEV *ExistingSCEV; 3452 FoldingSetNodeID ID; 3453 void *IP; 3454 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3455 if (ExistingSCEV) 3456 return ExistingSCEV; 3457 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3458 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3459 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3460 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3461 3462 UniqueSCEVs.InsertNode(S, IP); 3463 addToLoopUseLists(S); 3464 return S; 3465 } 3466 3467 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3468 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3469 return getSMaxExpr(Ops); 3470 } 3471 3472 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3473 return getMinMaxExpr(scSMaxExpr, Ops); 3474 } 3475 3476 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3477 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3478 return getUMaxExpr(Ops); 3479 } 3480 3481 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3482 return getMinMaxExpr(scUMaxExpr, Ops); 3483 } 3484 3485 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3486 const SCEV *RHS) { 3487 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3488 return getSMinExpr(Ops); 3489 } 3490 3491 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3492 return getMinMaxExpr(scSMinExpr, Ops); 3493 } 3494 3495 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3496 const SCEV *RHS) { 3497 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3498 return getUMinExpr(Ops); 3499 } 3500 3501 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3502 return getMinMaxExpr(scUMinExpr, Ops); 3503 } 3504 3505 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3506 // We can bypass creating a target-independent 3507 // constant expression and then folding it back into a ConstantInt. 3508 // This is just a compile-time optimization. 3509 if (isa<ScalableVectorType>(AllocTy)) { 3510 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); 3511 Constant *One = ConstantInt::get(IntTy, 1); 3512 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); 3513 return getSCEV(ConstantExpr::getPtrToInt(GEP, IntTy)); 3514 } 3515 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3516 } 3517 3518 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3519 StructType *STy, 3520 unsigned FieldNo) { 3521 // We can bypass creating a target-independent 3522 // constant expression and then folding it back into a ConstantInt. 3523 // This is just a compile-time optimization. 3524 return getConstant( 3525 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3526 } 3527 3528 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3529 // Don't attempt to do anything other than create a SCEVUnknown object 3530 // here. createSCEV only calls getUnknown after checking for all other 3531 // interesting possibilities, and any other code that calls getUnknown 3532 // is doing so in order to hide a value from SCEV canonicalization. 3533 3534 FoldingSetNodeID ID; 3535 ID.AddInteger(scUnknown); 3536 ID.AddPointer(V); 3537 void *IP = nullptr; 3538 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3539 assert(cast<SCEVUnknown>(S)->getValue() == V && 3540 "Stale SCEVUnknown in uniquing map!"); 3541 return S; 3542 } 3543 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3544 FirstUnknown); 3545 FirstUnknown = cast<SCEVUnknown>(S); 3546 UniqueSCEVs.InsertNode(S, IP); 3547 return S; 3548 } 3549 3550 //===----------------------------------------------------------------------===// 3551 // Basic SCEV Analysis and PHI Idiom Recognition Code 3552 // 3553 3554 /// Test if values of the given type are analyzable within the SCEV 3555 /// framework. This primarily includes integer types, and it can optionally 3556 /// include pointer types if the ScalarEvolution class has access to 3557 /// target-specific information. 3558 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3559 // Integers and pointers are always SCEVable. 3560 return Ty->isIntOrPtrTy(); 3561 } 3562 3563 /// Return the size in bits of the specified type, for which isSCEVable must 3564 /// return true. 3565 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3566 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3567 if (Ty->isPointerTy()) 3568 return getDataLayout().getIndexTypeSizeInBits(Ty); 3569 return getDataLayout().getTypeSizeInBits(Ty); 3570 } 3571 3572 /// Return a type with the same bitwidth as the given type and which represents 3573 /// how SCEV will treat the given type, for which isSCEVable must return 3574 /// true. For pointer types, this is the pointer index sized integer type. 3575 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3576 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3577 3578 if (Ty->isIntegerTy()) 3579 return Ty; 3580 3581 // The only other support type is pointer. 3582 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3583 return getDataLayout().getIndexType(Ty); 3584 } 3585 3586 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3587 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3588 } 3589 3590 const SCEV *ScalarEvolution::getCouldNotCompute() { 3591 return CouldNotCompute.get(); 3592 } 3593 3594 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3595 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3596 auto *SU = dyn_cast<SCEVUnknown>(S); 3597 return SU && SU->getValue() == nullptr; 3598 }); 3599 3600 return !ContainsNulls; 3601 } 3602 3603 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3604 HasRecMapType::iterator I = HasRecMap.find(S); 3605 if (I != HasRecMap.end()) 3606 return I->second; 3607 3608 bool FoundAddRec = 3609 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3610 HasRecMap.insert({S, FoundAddRec}); 3611 return FoundAddRec; 3612 } 3613 3614 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3615 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3616 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3617 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3618 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3619 if (!Add) 3620 return {S, nullptr}; 3621 3622 if (Add->getNumOperands() != 2) 3623 return {S, nullptr}; 3624 3625 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3626 if (!ConstOp) 3627 return {S, nullptr}; 3628 3629 return {Add->getOperand(1), ConstOp->getValue()}; 3630 } 3631 3632 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3633 /// by the value and offset from any ValueOffsetPair in the set. 3634 SetVector<ScalarEvolution::ValueOffsetPair> * 3635 ScalarEvolution::getSCEVValues(const SCEV *S) { 3636 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3637 if (SI == ExprValueMap.end()) 3638 return nullptr; 3639 #ifndef NDEBUG 3640 if (VerifySCEVMap) { 3641 // Check there is no dangling Value in the set returned. 3642 for (const auto &VE : SI->second) 3643 assert(ValueExprMap.count(VE.first)); 3644 } 3645 #endif 3646 return &SI->second; 3647 } 3648 3649 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3650 /// cannot be used separately. eraseValueFromMap should be used to remove 3651 /// V from ValueExprMap and ExprValueMap at the same time. 3652 void ScalarEvolution::eraseValueFromMap(Value *V) { 3653 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3654 if (I != ValueExprMap.end()) { 3655 const SCEV *S = I->second; 3656 // Remove {V, 0} from the set of ExprValueMap[S] 3657 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3658 SV->remove({V, nullptr}); 3659 3660 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3661 const SCEV *Stripped; 3662 ConstantInt *Offset; 3663 std::tie(Stripped, Offset) = splitAddExpr(S); 3664 if (Offset != nullptr) { 3665 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3666 SV->remove({V, Offset}); 3667 } 3668 ValueExprMap.erase(V); 3669 } 3670 } 3671 3672 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3673 /// TODO: In reality it is better to check the poison recursively 3674 /// but this is better than nothing. 3675 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3676 if (auto *I = dyn_cast<Instruction>(V)) { 3677 if (isa<OverflowingBinaryOperator>(I)) { 3678 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3679 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3680 return true; 3681 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3682 return true; 3683 } 3684 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3685 return true; 3686 } 3687 return false; 3688 } 3689 3690 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3691 /// create a new one. 3692 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3693 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3694 3695 const SCEV *S = getExistingSCEV(V); 3696 if (S == nullptr) { 3697 S = createSCEV(V); 3698 // During PHI resolution, it is possible to create two SCEVs for the same 3699 // V, so it is needed to double check whether V->S is inserted into 3700 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3701 std::pair<ValueExprMapType::iterator, bool> Pair = 3702 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3703 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3704 ExprValueMap[S].insert({V, nullptr}); 3705 3706 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3707 // ExprValueMap. 3708 const SCEV *Stripped = S; 3709 ConstantInt *Offset = nullptr; 3710 std::tie(Stripped, Offset) = splitAddExpr(S); 3711 // If stripped is SCEVUnknown, don't bother to save 3712 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3713 // increase the complexity of the expansion code. 3714 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3715 // because it may generate add/sub instead of GEP in SCEV expansion. 3716 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3717 !isa<GetElementPtrInst>(V)) 3718 ExprValueMap[Stripped].insert({V, Offset}); 3719 } 3720 } 3721 return S; 3722 } 3723 3724 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3725 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3726 3727 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3728 if (I != ValueExprMap.end()) { 3729 const SCEV *S = I->second; 3730 if (checkValidity(S)) 3731 return S; 3732 eraseValueFromMap(V); 3733 forgetMemoizedResults(S); 3734 } 3735 return nullptr; 3736 } 3737 3738 /// Return a SCEV corresponding to -V = -1*V 3739 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3740 SCEV::NoWrapFlags Flags) { 3741 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3742 return getConstant( 3743 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3744 3745 Type *Ty = V->getType(); 3746 Ty = getEffectiveSCEVType(Ty); 3747 return getMulExpr( 3748 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3749 } 3750 3751 /// If Expr computes ~A, return A else return nullptr 3752 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3753 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3754 if (!Add || Add->getNumOperands() != 2 || 3755 !Add->getOperand(0)->isAllOnesValue()) 3756 return nullptr; 3757 3758 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3759 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3760 !AddRHS->getOperand(0)->isAllOnesValue()) 3761 return nullptr; 3762 3763 return AddRHS->getOperand(1); 3764 } 3765 3766 /// Return a SCEV corresponding to ~V = -1-V 3767 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3768 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3769 return getConstant( 3770 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3771 3772 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3773 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3774 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3775 SmallVector<const SCEV *, 2> MatchedOperands; 3776 for (const SCEV *Operand : MME->operands()) { 3777 const SCEV *Matched = MatchNotExpr(Operand); 3778 if (!Matched) 3779 return (const SCEV *)nullptr; 3780 MatchedOperands.push_back(Matched); 3781 } 3782 return getMinMaxExpr( 3783 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 3784 MatchedOperands); 3785 }; 3786 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3787 return Replaced; 3788 } 3789 3790 Type *Ty = V->getType(); 3791 Ty = getEffectiveSCEVType(Ty); 3792 const SCEV *AllOnes = 3793 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 3794 return getMinusSCEV(AllOnes, V); 3795 } 3796 3797 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3798 SCEV::NoWrapFlags Flags, 3799 unsigned Depth) { 3800 // Fast path: X - X --> 0. 3801 if (LHS == RHS) 3802 return getZero(LHS->getType()); 3803 3804 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3805 // makes it so that we cannot make much use of NUW. 3806 auto AddFlags = SCEV::FlagAnyWrap; 3807 const bool RHSIsNotMinSigned = 3808 !getSignedRangeMin(RHS).isMinSignedValue(); 3809 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3810 // Let M be the minimum representable signed value. Then (-1)*RHS 3811 // signed-wraps if and only if RHS is M. That can happen even for 3812 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3813 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3814 // (-1)*RHS, we need to prove that RHS != M. 3815 // 3816 // If LHS is non-negative and we know that LHS - RHS does not 3817 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3818 // either by proving that RHS > M or that LHS >= 0. 3819 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3820 AddFlags = SCEV::FlagNSW; 3821 } 3822 } 3823 3824 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3825 // RHS is NSW and LHS >= 0. 3826 // 3827 // The difficulty here is that the NSW flag may have been proven 3828 // relative to a loop that is to be found in a recurrence in LHS and 3829 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3830 // larger scope than intended. 3831 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3832 3833 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3834 } 3835 3836 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 3837 unsigned Depth) { 3838 Type *SrcTy = V->getType(); 3839 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3840 "Cannot truncate or zero extend with non-integer arguments!"); 3841 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3842 return V; // No conversion 3843 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3844 return getTruncateExpr(V, Ty, Depth); 3845 return getZeroExtendExpr(V, Ty, Depth); 3846 } 3847 3848 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 3849 unsigned Depth) { 3850 Type *SrcTy = V->getType(); 3851 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3852 "Cannot truncate or zero extend with non-integer arguments!"); 3853 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3854 return V; // No conversion 3855 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3856 return getTruncateExpr(V, Ty, Depth); 3857 return getSignExtendExpr(V, Ty, Depth); 3858 } 3859 3860 const SCEV * 3861 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 3862 Type *SrcTy = V->getType(); 3863 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3864 "Cannot noop or zero extend with non-integer arguments!"); 3865 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3866 "getNoopOrZeroExtend cannot truncate!"); 3867 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3868 return V; // No conversion 3869 return getZeroExtendExpr(V, Ty); 3870 } 3871 3872 const SCEV * 3873 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 3874 Type *SrcTy = V->getType(); 3875 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3876 "Cannot noop or sign extend with non-integer arguments!"); 3877 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3878 "getNoopOrSignExtend cannot truncate!"); 3879 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3880 return V; // No conversion 3881 return getSignExtendExpr(V, Ty); 3882 } 3883 3884 const SCEV * 3885 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 3886 Type *SrcTy = V->getType(); 3887 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3888 "Cannot noop or any extend with non-integer arguments!"); 3889 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 3890 "getNoopOrAnyExtend cannot truncate!"); 3891 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3892 return V; // No conversion 3893 return getAnyExtendExpr(V, Ty); 3894 } 3895 3896 const SCEV * 3897 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 3898 Type *SrcTy = V->getType(); 3899 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3900 "Cannot truncate or noop with non-integer arguments!"); 3901 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 3902 "getTruncateOrNoop cannot extend!"); 3903 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3904 return V; // No conversion 3905 return getTruncateExpr(V, Ty); 3906 } 3907 3908 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 3909 const SCEV *RHS) { 3910 const SCEV *PromotedLHS = LHS; 3911 const SCEV *PromotedRHS = RHS; 3912 3913 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 3914 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 3915 else 3916 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 3917 3918 return getUMaxExpr(PromotedLHS, PromotedRHS); 3919 } 3920 3921 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 3922 const SCEV *RHS) { 3923 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3924 return getUMinFromMismatchedTypes(Ops); 3925 } 3926 3927 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 3928 SmallVectorImpl<const SCEV *> &Ops) { 3929 assert(!Ops.empty() && "At least one operand must be!"); 3930 // Trivial case. 3931 if (Ops.size() == 1) 3932 return Ops[0]; 3933 3934 // Find the max type first. 3935 Type *MaxType = nullptr; 3936 for (auto *S : Ops) 3937 if (MaxType) 3938 MaxType = getWiderType(MaxType, S->getType()); 3939 else 3940 MaxType = S->getType(); 3941 3942 // Extend all ops to max type. 3943 SmallVector<const SCEV *, 2> PromotedOps; 3944 for (auto *S : Ops) 3945 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 3946 3947 // Generate umin. 3948 return getUMinExpr(PromotedOps); 3949 } 3950 3951 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 3952 // A pointer operand may evaluate to a nonpointer expression, such as null. 3953 if (!V->getType()->isPointerTy()) 3954 return V; 3955 3956 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 3957 return getPointerBase(Cast->getOperand()); 3958 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 3959 const SCEV *PtrOp = nullptr; 3960 for (const SCEV *NAryOp : NAry->operands()) { 3961 if (NAryOp->getType()->isPointerTy()) { 3962 // Cannot find the base of an expression with multiple pointer operands. 3963 if (PtrOp) 3964 return V; 3965 PtrOp = NAryOp; 3966 } 3967 } 3968 if (!PtrOp) 3969 return V; 3970 return getPointerBase(PtrOp); 3971 } 3972 return V; 3973 } 3974 3975 /// Push users of the given Instruction onto the given Worklist. 3976 static void 3977 PushDefUseChildren(Instruction *I, 3978 SmallVectorImpl<Instruction *> &Worklist) { 3979 // Push the def-use children onto the Worklist stack. 3980 for (User *U : I->users()) 3981 Worklist.push_back(cast<Instruction>(U)); 3982 } 3983 3984 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 3985 SmallVector<Instruction *, 16> Worklist; 3986 PushDefUseChildren(PN, Worklist); 3987 3988 SmallPtrSet<Instruction *, 8> Visited; 3989 Visited.insert(PN); 3990 while (!Worklist.empty()) { 3991 Instruction *I = Worklist.pop_back_val(); 3992 if (!Visited.insert(I).second) 3993 continue; 3994 3995 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 3996 if (It != ValueExprMap.end()) { 3997 const SCEV *Old = It->second; 3998 3999 // Short-circuit the def-use traversal if the symbolic name 4000 // ceases to appear in expressions. 4001 if (Old != SymName && !hasOperand(Old, SymName)) 4002 continue; 4003 4004 // SCEVUnknown for a PHI either means that it has an unrecognized 4005 // structure, it's a PHI that's in the progress of being computed 4006 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4007 // additional loop trip count information isn't going to change anything. 4008 // In the second case, createNodeForPHI will perform the necessary 4009 // updates on its own when it gets to that point. In the third, we do 4010 // want to forget the SCEVUnknown. 4011 if (!isa<PHINode>(I) || 4012 !isa<SCEVUnknown>(Old) || 4013 (I != PN && Old == SymName)) { 4014 eraseValueFromMap(It->first); 4015 forgetMemoizedResults(Old); 4016 } 4017 } 4018 4019 PushDefUseChildren(I, Worklist); 4020 } 4021 } 4022 4023 namespace { 4024 4025 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4026 /// expression in case its Loop is L. If it is not L then 4027 /// if IgnoreOtherLoops is true then use AddRec itself 4028 /// otherwise rewrite cannot be done. 4029 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4030 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4031 public: 4032 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4033 bool IgnoreOtherLoops = true) { 4034 SCEVInitRewriter Rewriter(L, SE); 4035 const SCEV *Result = Rewriter.visit(S); 4036 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4037 return SE.getCouldNotCompute(); 4038 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4039 ? SE.getCouldNotCompute() 4040 : Result; 4041 } 4042 4043 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4044 if (!SE.isLoopInvariant(Expr, L)) 4045 SeenLoopVariantSCEVUnknown = true; 4046 return Expr; 4047 } 4048 4049 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4050 // Only re-write AddRecExprs for this loop. 4051 if (Expr->getLoop() == L) 4052 return Expr->getStart(); 4053 SeenOtherLoops = true; 4054 return Expr; 4055 } 4056 4057 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4058 4059 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4060 4061 private: 4062 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4063 : SCEVRewriteVisitor(SE), L(L) {} 4064 4065 const Loop *L; 4066 bool SeenLoopVariantSCEVUnknown = false; 4067 bool SeenOtherLoops = false; 4068 }; 4069 4070 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4071 /// increment expression in case its Loop is L. If it is not L then 4072 /// use AddRec itself. 4073 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4074 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4075 public: 4076 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4077 SCEVPostIncRewriter Rewriter(L, SE); 4078 const SCEV *Result = Rewriter.visit(S); 4079 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4080 ? SE.getCouldNotCompute() 4081 : Result; 4082 } 4083 4084 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4085 if (!SE.isLoopInvariant(Expr, L)) 4086 SeenLoopVariantSCEVUnknown = true; 4087 return Expr; 4088 } 4089 4090 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4091 // Only re-write AddRecExprs for this loop. 4092 if (Expr->getLoop() == L) 4093 return Expr->getPostIncExpr(SE); 4094 SeenOtherLoops = true; 4095 return Expr; 4096 } 4097 4098 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4099 4100 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4101 4102 private: 4103 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4104 : SCEVRewriteVisitor(SE), L(L) {} 4105 4106 const Loop *L; 4107 bool SeenLoopVariantSCEVUnknown = false; 4108 bool SeenOtherLoops = false; 4109 }; 4110 4111 /// This class evaluates the compare condition by matching it against the 4112 /// condition of loop latch. If there is a match we assume a true value 4113 /// for the condition while building SCEV nodes. 4114 class SCEVBackedgeConditionFolder 4115 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4116 public: 4117 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4118 ScalarEvolution &SE) { 4119 bool IsPosBECond = false; 4120 Value *BECond = nullptr; 4121 if (BasicBlock *Latch = L->getLoopLatch()) { 4122 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4123 if (BI && BI->isConditional()) { 4124 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4125 "Both outgoing branches should not target same header!"); 4126 BECond = BI->getCondition(); 4127 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4128 } else { 4129 return S; 4130 } 4131 } 4132 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4133 return Rewriter.visit(S); 4134 } 4135 4136 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4137 const SCEV *Result = Expr; 4138 bool InvariantF = SE.isLoopInvariant(Expr, L); 4139 4140 if (!InvariantF) { 4141 Instruction *I = cast<Instruction>(Expr->getValue()); 4142 switch (I->getOpcode()) { 4143 case Instruction::Select: { 4144 SelectInst *SI = cast<SelectInst>(I); 4145 Optional<const SCEV *> Res = 4146 compareWithBackedgeCondition(SI->getCondition()); 4147 if (Res.hasValue()) { 4148 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4149 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4150 } 4151 break; 4152 } 4153 default: { 4154 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4155 if (Res.hasValue()) 4156 Result = Res.getValue(); 4157 break; 4158 } 4159 } 4160 } 4161 return Result; 4162 } 4163 4164 private: 4165 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4166 bool IsPosBECond, ScalarEvolution &SE) 4167 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4168 IsPositiveBECond(IsPosBECond) {} 4169 4170 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4171 4172 const Loop *L; 4173 /// Loop back condition. 4174 Value *BackedgeCond = nullptr; 4175 /// Set to true if loop back is on positive branch condition. 4176 bool IsPositiveBECond; 4177 }; 4178 4179 Optional<const SCEV *> 4180 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4181 4182 // If value matches the backedge condition for loop latch, 4183 // then return a constant evolution node based on loopback 4184 // branch taken. 4185 if (BackedgeCond == IC) 4186 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4187 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4188 return None; 4189 } 4190 4191 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4192 public: 4193 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4194 ScalarEvolution &SE) { 4195 SCEVShiftRewriter Rewriter(L, SE); 4196 const SCEV *Result = Rewriter.visit(S); 4197 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4198 } 4199 4200 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4201 // Only allow AddRecExprs for this loop. 4202 if (!SE.isLoopInvariant(Expr, L)) 4203 Valid = false; 4204 return Expr; 4205 } 4206 4207 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4208 if (Expr->getLoop() == L && Expr->isAffine()) 4209 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4210 Valid = false; 4211 return Expr; 4212 } 4213 4214 bool isValid() { return Valid; } 4215 4216 private: 4217 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4218 : SCEVRewriteVisitor(SE), L(L) {} 4219 4220 const Loop *L; 4221 bool Valid = true; 4222 }; 4223 4224 } // end anonymous namespace 4225 4226 SCEV::NoWrapFlags 4227 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4228 if (!AR->isAffine()) 4229 return SCEV::FlagAnyWrap; 4230 4231 using OBO = OverflowingBinaryOperator; 4232 4233 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4234 4235 if (!AR->hasNoSignedWrap()) { 4236 ConstantRange AddRecRange = getSignedRange(AR); 4237 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4238 4239 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4240 Instruction::Add, IncRange, OBO::NoSignedWrap); 4241 if (NSWRegion.contains(AddRecRange)) 4242 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4243 } 4244 4245 if (!AR->hasNoUnsignedWrap()) { 4246 ConstantRange AddRecRange = getUnsignedRange(AR); 4247 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4248 4249 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4250 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4251 if (NUWRegion.contains(AddRecRange)) 4252 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4253 } 4254 4255 return Result; 4256 } 4257 4258 namespace { 4259 4260 /// Represents an abstract binary operation. This may exist as a 4261 /// normal instruction or constant expression, or may have been 4262 /// derived from an expression tree. 4263 struct BinaryOp { 4264 unsigned Opcode; 4265 Value *LHS; 4266 Value *RHS; 4267 bool IsNSW = false; 4268 bool IsNUW = false; 4269 4270 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4271 /// constant expression. 4272 Operator *Op = nullptr; 4273 4274 explicit BinaryOp(Operator *Op) 4275 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4276 Op(Op) { 4277 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4278 IsNSW = OBO->hasNoSignedWrap(); 4279 IsNUW = OBO->hasNoUnsignedWrap(); 4280 } 4281 } 4282 4283 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4284 bool IsNUW = false) 4285 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4286 }; 4287 4288 } // end anonymous namespace 4289 4290 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4291 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4292 auto *Op = dyn_cast<Operator>(V); 4293 if (!Op) 4294 return None; 4295 4296 // Implementation detail: all the cleverness here should happen without 4297 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4298 // SCEV expressions when possible, and we should not break that. 4299 4300 switch (Op->getOpcode()) { 4301 case Instruction::Add: 4302 case Instruction::Sub: 4303 case Instruction::Mul: 4304 case Instruction::UDiv: 4305 case Instruction::URem: 4306 case Instruction::And: 4307 case Instruction::Or: 4308 case Instruction::AShr: 4309 case Instruction::Shl: 4310 return BinaryOp(Op); 4311 4312 case Instruction::Xor: 4313 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4314 // If the RHS of the xor is a signmask, then this is just an add. 4315 // Instcombine turns add of signmask into xor as a strength reduction step. 4316 if (RHSC->getValue().isSignMask()) 4317 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4318 return BinaryOp(Op); 4319 4320 case Instruction::LShr: 4321 // Turn logical shift right of a constant into a unsigned divide. 4322 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4323 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4324 4325 // If the shift count is not less than the bitwidth, the result of 4326 // the shift is undefined. Don't try to analyze it, because the 4327 // resolution chosen here may differ from the resolution chosen in 4328 // other parts of the compiler. 4329 if (SA->getValue().ult(BitWidth)) { 4330 Constant *X = 4331 ConstantInt::get(SA->getContext(), 4332 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4333 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4334 } 4335 } 4336 return BinaryOp(Op); 4337 4338 case Instruction::ExtractValue: { 4339 auto *EVI = cast<ExtractValueInst>(Op); 4340 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4341 break; 4342 4343 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4344 if (!WO) 4345 break; 4346 4347 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4348 bool Signed = WO->isSigned(); 4349 // TODO: Should add nuw/nsw flags for mul as well. 4350 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4351 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4352 4353 // Now that we know that all uses of the arithmetic-result component of 4354 // CI are guarded by the overflow check, we can go ahead and pretend 4355 // that the arithmetic is non-overflowing. 4356 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4357 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4358 } 4359 4360 default: 4361 break; 4362 } 4363 4364 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4365 // semantics as a Sub, return a binary sub expression. 4366 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4367 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4368 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4369 4370 return None; 4371 } 4372 4373 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4374 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4375 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4376 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4377 /// follows one of the following patterns: 4378 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4379 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4380 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4381 /// we return the type of the truncation operation, and indicate whether the 4382 /// truncated type should be treated as signed/unsigned by setting 4383 /// \p Signed to true/false, respectively. 4384 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4385 bool &Signed, ScalarEvolution &SE) { 4386 // The case where Op == SymbolicPHI (that is, with no type conversions on 4387 // the way) is handled by the regular add recurrence creating logic and 4388 // would have already been triggered in createAddRecForPHI. Reaching it here 4389 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4390 // because one of the other operands of the SCEVAddExpr updating this PHI is 4391 // not invariant). 4392 // 4393 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4394 // this case predicates that allow us to prove that Op == SymbolicPHI will 4395 // be added. 4396 if (Op == SymbolicPHI) 4397 return nullptr; 4398 4399 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4400 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4401 if (SourceBits != NewBits) 4402 return nullptr; 4403 4404 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4405 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4406 if (!SExt && !ZExt) 4407 return nullptr; 4408 const SCEVTruncateExpr *Trunc = 4409 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4410 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4411 if (!Trunc) 4412 return nullptr; 4413 const SCEV *X = Trunc->getOperand(); 4414 if (X != SymbolicPHI) 4415 return nullptr; 4416 Signed = SExt != nullptr; 4417 return Trunc->getType(); 4418 } 4419 4420 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4421 if (!PN->getType()->isIntegerTy()) 4422 return nullptr; 4423 const Loop *L = LI.getLoopFor(PN->getParent()); 4424 if (!L || L->getHeader() != PN->getParent()) 4425 return nullptr; 4426 return L; 4427 } 4428 4429 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4430 // computation that updates the phi follows the following pattern: 4431 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4432 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4433 // If so, try to see if it can be rewritten as an AddRecExpr under some 4434 // Predicates. If successful, return them as a pair. Also cache the results 4435 // of the analysis. 4436 // 4437 // Example usage scenario: 4438 // Say the Rewriter is called for the following SCEV: 4439 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4440 // where: 4441 // %X = phi i64 (%Start, %BEValue) 4442 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4443 // and call this function with %SymbolicPHI = %X. 4444 // 4445 // The analysis will find that the value coming around the backedge has 4446 // the following SCEV: 4447 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4448 // Upon concluding that this matches the desired pattern, the function 4449 // will return the pair {NewAddRec, SmallPredsVec} where: 4450 // NewAddRec = {%Start,+,%Step} 4451 // SmallPredsVec = {P1, P2, P3} as follows: 4452 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4453 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4454 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4455 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4456 // under the predicates {P1,P2,P3}. 4457 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4458 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4459 // 4460 // TODO's: 4461 // 4462 // 1) Extend the Induction descriptor to also support inductions that involve 4463 // casts: When needed (namely, when we are called in the context of the 4464 // vectorizer induction analysis), a Set of cast instructions will be 4465 // populated by this method, and provided back to isInductionPHI. This is 4466 // needed to allow the vectorizer to properly record them to be ignored by 4467 // the cost model and to avoid vectorizing them (otherwise these casts, 4468 // which are redundant under the runtime overflow checks, will be 4469 // vectorized, which can be costly). 4470 // 4471 // 2) Support additional induction/PHISCEV patterns: We also want to support 4472 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4473 // after the induction update operation (the induction increment): 4474 // 4475 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4476 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4477 // 4478 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4479 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4480 // 4481 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4482 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4483 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4484 SmallVector<const SCEVPredicate *, 3> Predicates; 4485 4486 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4487 // return an AddRec expression under some predicate. 4488 4489 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4490 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4491 assert(L && "Expecting an integer loop header phi"); 4492 4493 // The loop may have multiple entrances or multiple exits; we can analyze 4494 // this phi as an addrec if it has a unique entry value and a unique 4495 // backedge value. 4496 Value *BEValueV = nullptr, *StartValueV = nullptr; 4497 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4498 Value *V = PN->getIncomingValue(i); 4499 if (L->contains(PN->getIncomingBlock(i))) { 4500 if (!BEValueV) { 4501 BEValueV = V; 4502 } else if (BEValueV != V) { 4503 BEValueV = nullptr; 4504 break; 4505 } 4506 } else if (!StartValueV) { 4507 StartValueV = V; 4508 } else if (StartValueV != V) { 4509 StartValueV = nullptr; 4510 break; 4511 } 4512 } 4513 if (!BEValueV || !StartValueV) 4514 return None; 4515 4516 const SCEV *BEValue = getSCEV(BEValueV); 4517 4518 // If the value coming around the backedge is an add with the symbolic 4519 // value we just inserted, possibly with casts that we can ignore under 4520 // an appropriate runtime guard, then we found a simple induction variable! 4521 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4522 if (!Add) 4523 return None; 4524 4525 // If there is a single occurrence of the symbolic value, possibly 4526 // casted, replace it with a recurrence. 4527 unsigned FoundIndex = Add->getNumOperands(); 4528 Type *TruncTy = nullptr; 4529 bool Signed; 4530 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4531 if ((TruncTy = 4532 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4533 if (FoundIndex == e) { 4534 FoundIndex = i; 4535 break; 4536 } 4537 4538 if (FoundIndex == Add->getNumOperands()) 4539 return None; 4540 4541 // Create an add with everything but the specified operand. 4542 SmallVector<const SCEV *, 8> Ops; 4543 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4544 if (i != FoundIndex) 4545 Ops.push_back(Add->getOperand(i)); 4546 const SCEV *Accum = getAddExpr(Ops); 4547 4548 // The runtime checks will not be valid if the step amount is 4549 // varying inside the loop. 4550 if (!isLoopInvariant(Accum, L)) 4551 return None; 4552 4553 // *** Part2: Create the predicates 4554 4555 // Analysis was successful: we have a phi-with-cast pattern for which we 4556 // can return an AddRec expression under the following predicates: 4557 // 4558 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4559 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4560 // P2: An Equal predicate that guarantees that 4561 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4562 // P3: An Equal predicate that guarantees that 4563 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4564 // 4565 // As we next prove, the above predicates guarantee that: 4566 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4567 // 4568 // 4569 // More formally, we want to prove that: 4570 // Expr(i+1) = Start + (i+1) * Accum 4571 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4572 // 4573 // Given that: 4574 // 1) Expr(0) = Start 4575 // 2) Expr(1) = Start + Accum 4576 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4577 // 3) Induction hypothesis (step i): 4578 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4579 // 4580 // Proof: 4581 // Expr(i+1) = 4582 // = Start + (i+1)*Accum 4583 // = (Start + i*Accum) + Accum 4584 // = Expr(i) + Accum 4585 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4586 // :: from step i 4587 // 4588 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4589 // 4590 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4591 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4592 // + Accum :: from P3 4593 // 4594 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4595 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4596 // 4597 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4598 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4599 // 4600 // By induction, the same applies to all iterations 1<=i<n: 4601 // 4602 4603 // Create a truncated addrec for which we will add a no overflow check (P1). 4604 const SCEV *StartVal = getSCEV(StartValueV); 4605 const SCEV *PHISCEV = 4606 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4607 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4608 4609 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4610 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4611 // will be constant. 4612 // 4613 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4614 // add P1. 4615 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4616 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4617 Signed ? SCEVWrapPredicate::IncrementNSSW 4618 : SCEVWrapPredicate::IncrementNUSW; 4619 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4620 Predicates.push_back(AddRecPred); 4621 } 4622 4623 // Create the Equal Predicates P2,P3: 4624 4625 // It is possible that the predicates P2 and/or P3 are computable at 4626 // compile time due to StartVal and/or Accum being constants. 4627 // If either one is, then we can check that now and escape if either P2 4628 // or P3 is false. 4629 4630 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4631 // for each of StartVal and Accum 4632 auto getExtendedExpr = [&](const SCEV *Expr, 4633 bool CreateSignExtend) -> const SCEV * { 4634 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4635 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4636 const SCEV *ExtendedExpr = 4637 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4638 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4639 return ExtendedExpr; 4640 }; 4641 4642 // Given: 4643 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4644 // = getExtendedExpr(Expr) 4645 // Determine whether the predicate P: Expr == ExtendedExpr 4646 // is known to be false at compile time 4647 auto PredIsKnownFalse = [&](const SCEV *Expr, 4648 const SCEV *ExtendedExpr) -> bool { 4649 return Expr != ExtendedExpr && 4650 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4651 }; 4652 4653 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4654 if (PredIsKnownFalse(StartVal, StartExtended)) { 4655 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4656 return None; 4657 } 4658 4659 // The Step is always Signed (because the overflow checks are either 4660 // NSSW or NUSW) 4661 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4662 if (PredIsKnownFalse(Accum, AccumExtended)) { 4663 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4664 return None; 4665 } 4666 4667 auto AppendPredicate = [&](const SCEV *Expr, 4668 const SCEV *ExtendedExpr) -> void { 4669 if (Expr != ExtendedExpr && 4670 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4671 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4672 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4673 Predicates.push_back(Pred); 4674 } 4675 }; 4676 4677 AppendPredicate(StartVal, StartExtended); 4678 AppendPredicate(Accum, AccumExtended); 4679 4680 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4681 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4682 // into NewAR if it will also add the runtime overflow checks specified in 4683 // Predicates. 4684 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4685 4686 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4687 std::make_pair(NewAR, Predicates); 4688 // Remember the result of the analysis for this SCEV at this locayyytion. 4689 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4690 return PredRewrite; 4691 } 4692 4693 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4694 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4695 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4696 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4697 if (!L) 4698 return None; 4699 4700 // Check to see if we already analyzed this PHI. 4701 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4702 if (I != PredicatedSCEVRewrites.end()) { 4703 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4704 I->second; 4705 // Analysis was done before and failed to create an AddRec: 4706 if (Rewrite.first == SymbolicPHI) 4707 return None; 4708 // Analysis was done before and succeeded to create an AddRec under 4709 // a predicate: 4710 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4711 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4712 return Rewrite; 4713 } 4714 4715 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4716 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4717 4718 // Record in the cache that the analysis failed 4719 if (!Rewrite) { 4720 SmallVector<const SCEVPredicate *, 3> Predicates; 4721 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4722 return None; 4723 } 4724 4725 return Rewrite; 4726 } 4727 4728 // FIXME: This utility is currently required because the Rewriter currently 4729 // does not rewrite this expression: 4730 // {0, +, (sext ix (trunc iy to ix) to iy)} 4731 // into {0, +, %step}, 4732 // even when the following Equal predicate exists: 4733 // "%step == (sext ix (trunc iy to ix) to iy)". 4734 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4735 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4736 if (AR1 == AR2) 4737 return true; 4738 4739 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4740 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4741 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4742 return false; 4743 return true; 4744 }; 4745 4746 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4747 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4748 return false; 4749 return true; 4750 } 4751 4752 /// A helper function for createAddRecFromPHI to handle simple cases. 4753 /// 4754 /// This function tries to find an AddRec expression for the simplest (yet most 4755 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4756 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4757 /// technique for finding the AddRec expression. 4758 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4759 Value *BEValueV, 4760 Value *StartValueV) { 4761 const Loop *L = LI.getLoopFor(PN->getParent()); 4762 assert(L && L->getHeader() == PN->getParent()); 4763 assert(BEValueV && StartValueV); 4764 4765 auto BO = MatchBinaryOp(BEValueV, DT); 4766 if (!BO) 4767 return nullptr; 4768 4769 if (BO->Opcode != Instruction::Add) 4770 return nullptr; 4771 4772 const SCEV *Accum = nullptr; 4773 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4774 Accum = getSCEV(BO->RHS); 4775 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4776 Accum = getSCEV(BO->LHS); 4777 4778 if (!Accum) 4779 return nullptr; 4780 4781 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4782 if (BO->IsNUW) 4783 Flags = setFlags(Flags, SCEV::FlagNUW); 4784 if (BO->IsNSW) 4785 Flags = setFlags(Flags, SCEV::FlagNSW); 4786 4787 const SCEV *StartVal = getSCEV(StartValueV); 4788 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4789 4790 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4791 4792 // We can add Flags to the post-inc expression only if we 4793 // know that it is *undefined behavior* for BEValueV to 4794 // overflow. 4795 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4796 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4797 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4798 4799 return PHISCEV; 4800 } 4801 4802 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4803 const Loop *L = LI.getLoopFor(PN->getParent()); 4804 if (!L || L->getHeader() != PN->getParent()) 4805 return nullptr; 4806 4807 // The loop may have multiple entrances or multiple exits; we can analyze 4808 // this phi as an addrec if it has a unique entry value and a unique 4809 // backedge value. 4810 Value *BEValueV = nullptr, *StartValueV = nullptr; 4811 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4812 Value *V = PN->getIncomingValue(i); 4813 if (L->contains(PN->getIncomingBlock(i))) { 4814 if (!BEValueV) { 4815 BEValueV = V; 4816 } else if (BEValueV != V) { 4817 BEValueV = nullptr; 4818 break; 4819 } 4820 } else if (!StartValueV) { 4821 StartValueV = V; 4822 } else if (StartValueV != V) { 4823 StartValueV = nullptr; 4824 break; 4825 } 4826 } 4827 if (!BEValueV || !StartValueV) 4828 return nullptr; 4829 4830 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4831 "PHI node already processed?"); 4832 4833 // First, try to find AddRec expression without creating a fictituos symbolic 4834 // value for PN. 4835 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4836 return S; 4837 4838 // Handle PHI node value symbolically. 4839 const SCEV *SymbolicName = getUnknown(PN); 4840 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 4841 4842 // Using this symbolic name for the PHI, analyze the value coming around 4843 // the back-edge. 4844 const SCEV *BEValue = getSCEV(BEValueV); 4845 4846 // NOTE: If BEValue is loop invariant, we know that the PHI node just 4847 // has a special value for the first iteration of the loop. 4848 4849 // If the value coming around the backedge is an add with the symbolic 4850 // value we just inserted, then we found a simple induction variable! 4851 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 4852 // If there is a single occurrence of the symbolic value, replace it 4853 // with a recurrence. 4854 unsigned FoundIndex = Add->getNumOperands(); 4855 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4856 if (Add->getOperand(i) == SymbolicName) 4857 if (FoundIndex == e) { 4858 FoundIndex = i; 4859 break; 4860 } 4861 4862 if (FoundIndex != Add->getNumOperands()) { 4863 // Create an add with everything but the specified operand. 4864 SmallVector<const SCEV *, 8> Ops; 4865 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4866 if (i != FoundIndex) 4867 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 4868 L, *this)); 4869 const SCEV *Accum = getAddExpr(Ops); 4870 4871 // This is not a valid addrec if the step amount is varying each 4872 // loop iteration, but is not itself an addrec in this loop. 4873 if (isLoopInvariant(Accum, L) || 4874 (isa<SCEVAddRecExpr>(Accum) && 4875 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 4876 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4877 4878 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 4879 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 4880 if (BO->IsNUW) 4881 Flags = setFlags(Flags, SCEV::FlagNUW); 4882 if (BO->IsNSW) 4883 Flags = setFlags(Flags, SCEV::FlagNSW); 4884 } 4885 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 4886 // If the increment is an inbounds GEP, then we know the address 4887 // space cannot be wrapped around. We cannot make any guarantee 4888 // about signed or unsigned overflow because pointers are 4889 // unsigned but we may have a negative index from the base 4890 // pointer. We can guarantee that no unsigned wrap occurs if the 4891 // indices form a positive value. 4892 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 4893 Flags = setFlags(Flags, SCEV::FlagNW); 4894 4895 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 4896 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 4897 Flags = setFlags(Flags, SCEV::FlagNUW); 4898 } 4899 4900 // We cannot transfer nuw and nsw flags from subtraction 4901 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 4902 // for instance. 4903 } 4904 4905 const SCEV *StartVal = getSCEV(StartValueV); 4906 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4907 4908 // Okay, for the entire analysis of this edge we assumed the PHI 4909 // to be symbolic. We now need to go back and purge all of the 4910 // entries for the scalars that use the symbolic expression. 4911 forgetSymbolicName(PN, SymbolicName); 4912 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4913 4914 // We can add Flags to the post-inc expression only if we 4915 // know that it is *undefined behavior* for BEValueV to 4916 // overflow. 4917 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4918 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4919 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4920 4921 return PHISCEV; 4922 } 4923 } 4924 } else { 4925 // Otherwise, this could be a loop like this: 4926 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 4927 // In this case, j = {1,+,1} and BEValue is j. 4928 // Because the other in-value of i (0) fits the evolution of BEValue 4929 // i really is an addrec evolution. 4930 // 4931 // We can generalize this saying that i is the shifted value of BEValue 4932 // by one iteration: 4933 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 4934 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 4935 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 4936 if (Shifted != getCouldNotCompute() && 4937 Start != getCouldNotCompute()) { 4938 const SCEV *StartVal = getSCEV(StartValueV); 4939 if (Start == StartVal) { 4940 // Okay, for the entire analysis of this edge we assumed the PHI 4941 // to be symbolic. We now need to go back and purge all of the 4942 // entries for the scalars that use the symbolic expression. 4943 forgetSymbolicName(PN, SymbolicName); 4944 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 4945 return Shifted; 4946 } 4947 } 4948 } 4949 4950 // Remove the temporary PHI node SCEV that has been inserted while intending 4951 // to create an AddRecExpr for this PHI node. We can not keep this temporary 4952 // as it will prevent later (possibly simpler) SCEV expressions to be added 4953 // to the ValueExprMap. 4954 eraseValueFromMap(PN); 4955 4956 return nullptr; 4957 } 4958 4959 // Checks if the SCEV S is available at BB. S is considered available at BB 4960 // if S can be materialized at BB without introducing a fault. 4961 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 4962 BasicBlock *BB) { 4963 struct CheckAvailable { 4964 bool TraversalDone = false; 4965 bool Available = true; 4966 4967 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 4968 BasicBlock *BB = nullptr; 4969 DominatorTree &DT; 4970 4971 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 4972 : L(L), BB(BB), DT(DT) {} 4973 4974 bool setUnavailable() { 4975 TraversalDone = true; 4976 Available = false; 4977 return false; 4978 } 4979 4980 bool follow(const SCEV *S) { 4981 switch (S->getSCEVType()) { 4982 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 4983 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 4984 case scUMinExpr: 4985 case scSMinExpr: 4986 // These expressions are available if their operand(s) is/are. 4987 return true; 4988 4989 case scAddRecExpr: { 4990 // We allow add recurrences that are on the loop BB is in, or some 4991 // outer loop. This guarantees availability because the value of the 4992 // add recurrence at BB is simply the "current" value of the induction 4993 // variable. We can relax this in the future; for instance an add 4994 // recurrence on a sibling dominating loop is also available at BB. 4995 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 4996 if (L && (ARLoop == L || ARLoop->contains(L))) 4997 return true; 4998 4999 return setUnavailable(); 5000 } 5001 5002 case scUnknown: { 5003 // For SCEVUnknown, we check for simple dominance. 5004 const auto *SU = cast<SCEVUnknown>(S); 5005 Value *V = SU->getValue(); 5006 5007 if (isa<Argument>(V)) 5008 return false; 5009 5010 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5011 return false; 5012 5013 return setUnavailable(); 5014 } 5015 5016 case scUDivExpr: 5017 case scCouldNotCompute: 5018 // We do not try to smart about these at all. 5019 return setUnavailable(); 5020 } 5021 llvm_unreachable("switch should be fully covered!"); 5022 } 5023 5024 bool isDone() { return TraversalDone; } 5025 }; 5026 5027 CheckAvailable CA(L, BB, DT); 5028 SCEVTraversal<CheckAvailable> ST(CA); 5029 5030 ST.visitAll(S); 5031 return CA.Available; 5032 } 5033 5034 // Try to match a control flow sequence that branches out at BI and merges back 5035 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5036 // match. 5037 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5038 Value *&C, Value *&LHS, Value *&RHS) { 5039 C = BI->getCondition(); 5040 5041 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5042 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5043 5044 if (!LeftEdge.isSingleEdge()) 5045 return false; 5046 5047 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5048 5049 Use &LeftUse = Merge->getOperandUse(0); 5050 Use &RightUse = Merge->getOperandUse(1); 5051 5052 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5053 LHS = LeftUse; 5054 RHS = RightUse; 5055 return true; 5056 } 5057 5058 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5059 LHS = RightUse; 5060 RHS = LeftUse; 5061 return true; 5062 } 5063 5064 return false; 5065 } 5066 5067 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5068 auto IsReachable = 5069 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5070 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5071 const Loop *L = LI.getLoopFor(PN->getParent()); 5072 5073 // We don't want to break LCSSA, even in a SCEV expression tree. 5074 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5075 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5076 return nullptr; 5077 5078 // Try to match 5079 // 5080 // br %cond, label %left, label %right 5081 // left: 5082 // br label %merge 5083 // right: 5084 // br label %merge 5085 // merge: 5086 // V = phi [ %x, %left ], [ %y, %right ] 5087 // 5088 // as "select %cond, %x, %y" 5089 5090 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5091 assert(IDom && "At least the entry block should dominate PN"); 5092 5093 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5094 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5095 5096 if (BI && BI->isConditional() && 5097 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5098 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5099 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5100 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5101 } 5102 5103 return nullptr; 5104 } 5105 5106 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5107 if (const SCEV *S = createAddRecFromPHI(PN)) 5108 return S; 5109 5110 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5111 return S; 5112 5113 // If the PHI has a single incoming value, follow that value, unless the 5114 // PHI's incoming blocks are in a different loop, in which case doing so 5115 // risks breaking LCSSA form. Instcombine would normally zap these, but 5116 // it doesn't have DominatorTree information, so it may miss cases. 5117 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5118 if (LI.replacementPreservesLCSSAForm(PN, V)) 5119 return getSCEV(V); 5120 5121 // If it's not a loop phi, we can't handle it yet. 5122 return getUnknown(PN); 5123 } 5124 5125 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5126 Value *Cond, 5127 Value *TrueVal, 5128 Value *FalseVal) { 5129 // Handle "constant" branch or select. This can occur for instance when a 5130 // loop pass transforms an inner loop and moves on to process the outer loop. 5131 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5132 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5133 5134 // Try to match some simple smax or umax patterns. 5135 auto *ICI = dyn_cast<ICmpInst>(Cond); 5136 if (!ICI) 5137 return getUnknown(I); 5138 5139 Value *LHS = ICI->getOperand(0); 5140 Value *RHS = ICI->getOperand(1); 5141 5142 switch (ICI->getPredicate()) { 5143 case ICmpInst::ICMP_SLT: 5144 case ICmpInst::ICMP_SLE: 5145 std::swap(LHS, RHS); 5146 LLVM_FALLTHROUGH; 5147 case ICmpInst::ICMP_SGT: 5148 case ICmpInst::ICMP_SGE: 5149 // a >s b ? a+x : b+x -> smax(a, b)+x 5150 // a >s b ? b+x : a+x -> smin(a, b)+x 5151 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5152 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5153 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5154 const SCEV *LA = getSCEV(TrueVal); 5155 const SCEV *RA = getSCEV(FalseVal); 5156 const SCEV *LDiff = getMinusSCEV(LA, LS); 5157 const SCEV *RDiff = getMinusSCEV(RA, RS); 5158 if (LDiff == RDiff) 5159 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5160 LDiff = getMinusSCEV(LA, RS); 5161 RDiff = getMinusSCEV(RA, LS); 5162 if (LDiff == RDiff) 5163 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5164 } 5165 break; 5166 case ICmpInst::ICMP_ULT: 5167 case ICmpInst::ICMP_ULE: 5168 std::swap(LHS, RHS); 5169 LLVM_FALLTHROUGH; 5170 case ICmpInst::ICMP_UGT: 5171 case ICmpInst::ICMP_UGE: 5172 // a >u b ? a+x : b+x -> umax(a, b)+x 5173 // a >u b ? b+x : a+x -> umin(a, b)+x 5174 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5175 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5176 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5177 const SCEV *LA = getSCEV(TrueVal); 5178 const SCEV *RA = getSCEV(FalseVal); 5179 const SCEV *LDiff = getMinusSCEV(LA, LS); 5180 const SCEV *RDiff = getMinusSCEV(RA, RS); 5181 if (LDiff == RDiff) 5182 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5183 LDiff = getMinusSCEV(LA, RS); 5184 RDiff = getMinusSCEV(RA, LS); 5185 if (LDiff == RDiff) 5186 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5187 } 5188 break; 5189 case ICmpInst::ICMP_NE: 5190 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5191 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5192 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5193 const SCEV *One = getOne(I->getType()); 5194 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5195 const SCEV *LA = getSCEV(TrueVal); 5196 const SCEV *RA = getSCEV(FalseVal); 5197 const SCEV *LDiff = getMinusSCEV(LA, LS); 5198 const SCEV *RDiff = getMinusSCEV(RA, One); 5199 if (LDiff == RDiff) 5200 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5201 } 5202 break; 5203 case ICmpInst::ICMP_EQ: 5204 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5205 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5206 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5207 const SCEV *One = getOne(I->getType()); 5208 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5209 const SCEV *LA = getSCEV(TrueVal); 5210 const SCEV *RA = getSCEV(FalseVal); 5211 const SCEV *LDiff = getMinusSCEV(LA, One); 5212 const SCEV *RDiff = getMinusSCEV(RA, LS); 5213 if (LDiff == RDiff) 5214 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5215 } 5216 break; 5217 default: 5218 break; 5219 } 5220 5221 return getUnknown(I); 5222 } 5223 5224 /// Expand GEP instructions into add and multiply operations. This allows them 5225 /// to be analyzed by regular SCEV code. 5226 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5227 // Don't attempt to analyze GEPs over unsized objects. 5228 if (!GEP->getSourceElementType()->isSized()) 5229 return getUnknown(GEP); 5230 5231 SmallVector<const SCEV *, 4> IndexExprs; 5232 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5233 IndexExprs.push_back(getSCEV(*Index)); 5234 return getGEPExpr(GEP, IndexExprs); 5235 } 5236 5237 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5238 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5239 return C->getAPInt().countTrailingZeros(); 5240 5241 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5242 return std::min(GetMinTrailingZeros(T->getOperand()), 5243 (uint32_t)getTypeSizeInBits(T->getType())); 5244 5245 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5246 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5247 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5248 ? getTypeSizeInBits(E->getType()) 5249 : OpRes; 5250 } 5251 5252 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5253 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5254 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5255 ? getTypeSizeInBits(E->getType()) 5256 : OpRes; 5257 } 5258 5259 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5260 // The result is the min of all operands results. 5261 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5262 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5263 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5264 return MinOpRes; 5265 } 5266 5267 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5268 // The result is the sum of all operands results. 5269 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5270 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5271 for (unsigned i = 1, e = M->getNumOperands(); 5272 SumOpRes != BitWidth && i != e; ++i) 5273 SumOpRes = 5274 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5275 return SumOpRes; 5276 } 5277 5278 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5279 // The result is the min of all operands results. 5280 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5281 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5282 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5283 return MinOpRes; 5284 } 5285 5286 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5287 // The result is the min of all operands results. 5288 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5289 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5290 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5291 return MinOpRes; 5292 } 5293 5294 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5295 // The result is the min of all operands results. 5296 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5297 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5298 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5299 return MinOpRes; 5300 } 5301 5302 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5303 // For a SCEVUnknown, ask ValueTracking. 5304 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5305 return Known.countMinTrailingZeros(); 5306 } 5307 5308 // SCEVUDivExpr 5309 return 0; 5310 } 5311 5312 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5313 auto I = MinTrailingZerosCache.find(S); 5314 if (I != MinTrailingZerosCache.end()) 5315 return I->second; 5316 5317 uint32_t Result = GetMinTrailingZerosImpl(S); 5318 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5319 assert(InsertPair.second && "Should insert a new key"); 5320 return InsertPair.first->second; 5321 } 5322 5323 /// Helper method to assign a range to V from metadata present in the IR. 5324 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5325 if (Instruction *I = dyn_cast<Instruction>(V)) 5326 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5327 return getConstantRangeFromMetadata(*MD); 5328 5329 return None; 5330 } 5331 5332 /// Determine the range for a particular SCEV. If SignHint is 5333 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5334 /// with a "cleaner" unsigned (resp. signed) representation. 5335 const ConstantRange & 5336 ScalarEvolution::getRangeRef(const SCEV *S, 5337 ScalarEvolution::RangeSignHint SignHint) { 5338 DenseMap<const SCEV *, ConstantRange> &Cache = 5339 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5340 : SignedRanges; 5341 ConstantRange::PreferredRangeType RangeType = 5342 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5343 ? ConstantRange::Unsigned : ConstantRange::Signed; 5344 5345 // See if we've computed this range already. 5346 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5347 if (I != Cache.end()) 5348 return I->second; 5349 5350 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5351 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5352 5353 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5354 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5355 using OBO = OverflowingBinaryOperator; 5356 5357 // If the value has known zeros, the maximum value will have those known zeros 5358 // as well. 5359 uint32_t TZ = GetMinTrailingZeros(S); 5360 if (TZ != 0) { 5361 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5362 ConservativeResult = 5363 ConstantRange(APInt::getMinValue(BitWidth), 5364 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5365 else 5366 ConservativeResult = ConstantRange( 5367 APInt::getSignedMinValue(BitWidth), 5368 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5369 } 5370 5371 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5372 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5373 unsigned WrapType = OBO::AnyWrap; 5374 if (Add->hasNoSignedWrap()) 5375 WrapType |= OBO::NoSignedWrap; 5376 if (Add->hasNoUnsignedWrap()) 5377 WrapType |= OBO::NoUnsignedWrap; 5378 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5379 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5380 WrapType, RangeType); 5381 return setRange(Add, SignHint, 5382 ConservativeResult.intersectWith(X, RangeType)); 5383 } 5384 5385 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5386 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5387 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5388 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5389 return setRange(Mul, SignHint, 5390 ConservativeResult.intersectWith(X, RangeType)); 5391 } 5392 5393 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5394 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5395 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5396 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5397 return setRange(SMax, SignHint, 5398 ConservativeResult.intersectWith(X, RangeType)); 5399 } 5400 5401 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5402 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5403 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5404 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5405 return setRange(UMax, SignHint, 5406 ConservativeResult.intersectWith(X, RangeType)); 5407 } 5408 5409 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5410 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5411 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5412 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5413 return setRange(SMin, SignHint, 5414 ConservativeResult.intersectWith(X, RangeType)); 5415 } 5416 5417 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5418 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5419 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5420 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5421 return setRange(UMin, SignHint, 5422 ConservativeResult.intersectWith(X, RangeType)); 5423 } 5424 5425 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5426 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5427 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5428 return setRange(UDiv, SignHint, 5429 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5430 } 5431 5432 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5433 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5434 return setRange(ZExt, SignHint, 5435 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5436 RangeType)); 5437 } 5438 5439 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5440 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5441 return setRange(SExt, SignHint, 5442 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5443 RangeType)); 5444 } 5445 5446 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5447 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5448 return setRange(Trunc, SignHint, 5449 ConservativeResult.intersectWith(X.truncate(BitWidth), 5450 RangeType)); 5451 } 5452 5453 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5454 // If there's no unsigned wrap, the value will never be less than its 5455 // initial value. 5456 if (AddRec->hasNoUnsignedWrap()) { 5457 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5458 if (!UnsignedMinValue.isNullValue()) 5459 ConservativeResult = ConservativeResult.intersectWith( 5460 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5461 } 5462 5463 // If there's no signed wrap, and all the operands except initial value have 5464 // the same sign or zero, the value won't ever be: 5465 // 1: smaller than initial value if operands are non negative, 5466 // 2: bigger than initial value if operands are non positive. 5467 // For both cases, value can not cross signed min/max boundary. 5468 if (AddRec->hasNoSignedWrap()) { 5469 bool AllNonNeg = true; 5470 bool AllNonPos = true; 5471 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5472 if (!isKnownNonNegative(AddRec->getOperand(i))) 5473 AllNonNeg = false; 5474 if (!isKnownNonPositive(AddRec->getOperand(i))) 5475 AllNonPos = false; 5476 } 5477 if (AllNonNeg) 5478 ConservativeResult = ConservativeResult.intersectWith( 5479 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5480 APInt::getSignedMinValue(BitWidth)), 5481 RangeType); 5482 else if (AllNonPos) 5483 ConservativeResult = ConservativeResult.intersectWith( 5484 ConstantRange::getNonEmpty( 5485 APInt::getSignedMinValue(BitWidth), 5486 getSignedRangeMax(AddRec->getStart()) + 1), 5487 RangeType); 5488 } 5489 5490 // TODO: non-affine addrec 5491 if (AddRec->isAffine()) { 5492 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5493 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5494 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5495 auto RangeFromAffine = getRangeForAffineAR( 5496 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5497 BitWidth); 5498 if (!RangeFromAffine.isFullSet()) 5499 ConservativeResult = 5500 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5501 5502 auto RangeFromFactoring = getRangeViaFactoring( 5503 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5504 BitWidth); 5505 if (!RangeFromFactoring.isFullSet()) 5506 ConservativeResult = 5507 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5508 } 5509 } 5510 5511 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5512 } 5513 5514 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5515 // Check if the IR explicitly contains !range metadata. 5516 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5517 if (MDRange.hasValue()) 5518 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5519 RangeType); 5520 5521 // Split here to avoid paying the compile-time cost of calling both 5522 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5523 // if needed. 5524 const DataLayout &DL = getDataLayout(); 5525 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5526 // For a SCEVUnknown, ask ValueTracking. 5527 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5528 if (Known.getBitWidth() != BitWidth) 5529 Known = Known.zextOrTrunc(BitWidth); 5530 // If Known does not result in full-set, intersect with it. 5531 if (Known.getMinValue() != Known.getMaxValue() + 1) 5532 ConservativeResult = ConservativeResult.intersectWith( 5533 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5534 RangeType); 5535 } else { 5536 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5537 "generalize as needed!"); 5538 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5539 // If the pointer size is larger than the index size type, this can cause 5540 // NS to be larger than BitWidth. So compensate for this. 5541 if (U->getType()->isPointerTy()) { 5542 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5543 int ptrIdxDiff = ptrSize - BitWidth; 5544 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5545 NS -= ptrIdxDiff; 5546 } 5547 5548 if (NS > 1) 5549 ConservativeResult = ConservativeResult.intersectWith( 5550 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5551 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5552 RangeType); 5553 } 5554 5555 // A range of Phi is a subset of union of all ranges of its input. 5556 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5557 // Make sure that we do not run over cycled Phis. 5558 if (PendingPhiRanges.insert(Phi).second) { 5559 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5560 for (auto &Op : Phi->operands()) { 5561 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5562 RangeFromOps = RangeFromOps.unionWith(OpRange); 5563 // No point to continue if we already have a full set. 5564 if (RangeFromOps.isFullSet()) 5565 break; 5566 } 5567 ConservativeResult = 5568 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5569 bool Erased = PendingPhiRanges.erase(Phi); 5570 assert(Erased && "Failed to erase Phi properly?"); 5571 (void) Erased; 5572 } 5573 } 5574 5575 return setRange(U, SignHint, std::move(ConservativeResult)); 5576 } 5577 5578 return setRange(S, SignHint, std::move(ConservativeResult)); 5579 } 5580 5581 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5582 // values that the expression can take. Initially, the expression has a value 5583 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5584 // argument defines if we treat Step as signed or unsigned. 5585 static ConstantRange getRangeForAffineARHelper(APInt Step, 5586 const ConstantRange &StartRange, 5587 const APInt &MaxBECount, 5588 unsigned BitWidth, bool Signed) { 5589 // If either Step or MaxBECount is 0, then the expression won't change, and we 5590 // just need to return the initial range. 5591 if (Step == 0 || MaxBECount == 0) 5592 return StartRange; 5593 5594 // If we don't know anything about the initial value (i.e. StartRange is 5595 // FullRange), then we don't know anything about the final range either. 5596 // Return FullRange. 5597 if (StartRange.isFullSet()) 5598 return ConstantRange::getFull(BitWidth); 5599 5600 // If Step is signed and negative, then we use its absolute value, but we also 5601 // note that we're moving in the opposite direction. 5602 bool Descending = Signed && Step.isNegative(); 5603 5604 if (Signed) 5605 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5606 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5607 // This equations hold true due to the well-defined wrap-around behavior of 5608 // APInt. 5609 Step = Step.abs(); 5610 5611 // Check if Offset is more than full span of BitWidth. If it is, the 5612 // expression is guaranteed to overflow. 5613 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5614 return ConstantRange::getFull(BitWidth); 5615 5616 // Offset is by how much the expression can change. Checks above guarantee no 5617 // overflow here. 5618 APInt Offset = Step * MaxBECount; 5619 5620 // Minimum value of the final range will match the minimal value of StartRange 5621 // if the expression is increasing and will be decreased by Offset otherwise. 5622 // Maximum value of the final range will match the maximal value of StartRange 5623 // if the expression is decreasing and will be increased by Offset otherwise. 5624 APInt StartLower = StartRange.getLower(); 5625 APInt StartUpper = StartRange.getUpper() - 1; 5626 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5627 : (StartUpper + std::move(Offset)); 5628 5629 // It's possible that the new minimum/maximum value will fall into the initial 5630 // range (due to wrap around). This means that the expression can take any 5631 // value in this bitwidth, and we have to return full range. 5632 if (StartRange.contains(MovedBoundary)) 5633 return ConstantRange::getFull(BitWidth); 5634 5635 APInt NewLower = 5636 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5637 APInt NewUpper = 5638 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5639 NewUpper += 1; 5640 5641 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5642 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5643 } 5644 5645 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5646 const SCEV *Step, 5647 const SCEV *MaxBECount, 5648 unsigned BitWidth) { 5649 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5650 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5651 "Precondition!"); 5652 5653 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5654 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5655 5656 // First, consider step signed. 5657 ConstantRange StartSRange = getSignedRange(Start); 5658 ConstantRange StepSRange = getSignedRange(Step); 5659 5660 // If Step can be both positive and negative, we need to find ranges for the 5661 // maximum absolute step values in both directions and union them. 5662 ConstantRange SR = 5663 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5664 MaxBECountValue, BitWidth, /* Signed = */ true); 5665 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5666 StartSRange, MaxBECountValue, 5667 BitWidth, /* Signed = */ true)); 5668 5669 // Next, consider step unsigned. 5670 ConstantRange UR = getRangeForAffineARHelper( 5671 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5672 MaxBECountValue, BitWidth, /* Signed = */ false); 5673 5674 // Finally, intersect signed and unsigned ranges. 5675 return SR.intersectWith(UR, ConstantRange::Smallest); 5676 } 5677 5678 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5679 const SCEV *Step, 5680 const SCEV *MaxBECount, 5681 unsigned BitWidth) { 5682 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5683 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5684 5685 struct SelectPattern { 5686 Value *Condition = nullptr; 5687 APInt TrueValue; 5688 APInt FalseValue; 5689 5690 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5691 const SCEV *S) { 5692 Optional<unsigned> CastOp; 5693 APInt Offset(BitWidth, 0); 5694 5695 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5696 "Should be!"); 5697 5698 // Peel off a constant offset: 5699 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5700 // In the future we could consider being smarter here and handle 5701 // {Start+Step,+,Step} too. 5702 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5703 return; 5704 5705 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5706 S = SA->getOperand(1); 5707 } 5708 5709 // Peel off a cast operation 5710 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5711 CastOp = SCast->getSCEVType(); 5712 S = SCast->getOperand(); 5713 } 5714 5715 using namespace llvm::PatternMatch; 5716 5717 auto *SU = dyn_cast<SCEVUnknown>(S); 5718 const APInt *TrueVal, *FalseVal; 5719 if (!SU || 5720 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5721 m_APInt(FalseVal)))) { 5722 Condition = nullptr; 5723 return; 5724 } 5725 5726 TrueValue = *TrueVal; 5727 FalseValue = *FalseVal; 5728 5729 // Re-apply the cast we peeled off earlier 5730 if (CastOp.hasValue()) 5731 switch (*CastOp) { 5732 default: 5733 llvm_unreachable("Unknown SCEV cast type!"); 5734 5735 case scTruncate: 5736 TrueValue = TrueValue.trunc(BitWidth); 5737 FalseValue = FalseValue.trunc(BitWidth); 5738 break; 5739 case scZeroExtend: 5740 TrueValue = TrueValue.zext(BitWidth); 5741 FalseValue = FalseValue.zext(BitWidth); 5742 break; 5743 case scSignExtend: 5744 TrueValue = TrueValue.sext(BitWidth); 5745 FalseValue = FalseValue.sext(BitWidth); 5746 break; 5747 } 5748 5749 // Re-apply the constant offset we peeled off earlier 5750 TrueValue += Offset; 5751 FalseValue += Offset; 5752 } 5753 5754 bool isRecognized() { return Condition != nullptr; } 5755 }; 5756 5757 SelectPattern StartPattern(*this, BitWidth, Start); 5758 if (!StartPattern.isRecognized()) 5759 return ConstantRange::getFull(BitWidth); 5760 5761 SelectPattern StepPattern(*this, BitWidth, Step); 5762 if (!StepPattern.isRecognized()) 5763 return ConstantRange::getFull(BitWidth); 5764 5765 if (StartPattern.Condition != StepPattern.Condition) { 5766 // We don't handle this case today; but we could, by considering four 5767 // possibilities below instead of two. I'm not sure if there are cases where 5768 // that will help over what getRange already does, though. 5769 return ConstantRange::getFull(BitWidth); 5770 } 5771 5772 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5773 // construct arbitrary general SCEV expressions here. This function is called 5774 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5775 // say) can end up caching a suboptimal value. 5776 5777 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5778 // C2352 and C2512 (otherwise it isn't needed). 5779 5780 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5781 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5782 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5783 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5784 5785 ConstantRange TrueRange = 5786 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5787 ConstantRange FalseRange = 5788 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5789 5790 return TrueRange.unionWith(FalseRange); 5791 } 5792 5793 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5794 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5795 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5796 5797 // Return early if there are no flags to propagate to the SCEV. 5798 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5799 if (BinOp->hasNoUnsignedWrap()) 5800 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5801 if (BinOp->hasNoSignedWrap()) 5802 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5803 if (Flags == SCEV::FlagAnyWrap) 5804 return SCEV::FlagAnyWrap; 5805 5806 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5807 } 5808 5809 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5810 // Here we check that I is in the header of the innermost loop containing I, 5811 // since we only deal with instructions in the loop header. The actual loop we 5812 // need to check later will come from an add recurrence, but getting that 5813 // requires computing the SCEV of the operands, which can be expensive. This 5814 // check we can do cheaply to rule out some cases early. 5815 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5816 if (InnermostContainingLoop == nullptr || 5817 InnermostContainingLoop->getHeader() != I->getParent()) 5818 return false; 5819 5820 // Only proceed if we can prove that I does not yield poison. 5821 if (!programUndefinedIfPoison(I)) 5822 return false; 5823 5824 // At this point we know that if I is executed, then it does not wrap 5825 // according to at least one of NSW or NUW. If I is not executed, then we do 5826 // not know if the calculation that I represents would wrap. Multiple 5827 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 5828 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 5829 // derived from other instructions that map to the same SCEV. We cannot make 5830 // that guarantee for cases where I is not executed. So we need to find the 5831 // loop that I is considered in relation to and prove that I is executed for 5832 // every iteration of that loop. That implies that the value that I 5833 // calculates does not wrap anywhere in the loop, so then we can apply the 5834 // flags to the SCEV. 5835 // 5836 // We check isLoopInvariant to disambiguate in case we are adding recurrences 5837 // from different loops, so that we know which loop to prove that I is 5838 // executed in. 5839 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 5840 // I could be an extractvalue from a call to an overflow intrinsic. 5841 // TODO: We can do better here in some cases. 5842 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 5843 return false; 5844 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 5845 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 5846 bool AllOtherOpsLoopInvariant = true; 5847 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 5848 ++OtherOpIndex) { 5849 if (OtherOpIndex != OpIndex) { 5850 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 5851 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 5852 AllOtherOpsLoopInvariant = false; 5853 break; 5854 } 5855 } 5856 } 5857 if (AllOtherOpsLoopInvariant && 5858 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 5859 return true; 5860 } 5861 } 5862 return false; 5863 } 5864 5865 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 5866 // If we know that \c I can never be poison period, then that's enough. 5867 if (isSCEVExprNeverPoison(I)) 5868 return true; 5869 5870 // For an add recurrence specifically, we assume that infinite loops without 5871 // side effects are undefined behavior, and then reason as follows: 5872 // 5873 // If the add recurrence is poison in any iteration, it is poison on all 5874 // future iterations (since incrementing poison yields poison). If the result 5875 // of the add recurrence is fed into the loop latch condition and the loop 5876 // does not contain any throws or exiting blocks other than the latch, we now 5877 // have the ability to "choose" whether the backedge is taken or not (by 5878 // choosing a sufficiently evil value for the poison feeding into the branch) 5879 // for every iteration including and after the one in which \p I first became 5880 // poison. There are two possibilities (let's call the iteration in which \p 5881 // I first became poison as K): 5882 // 5883 // 1. In the set of iterations including and after K, the loop body executes 5884 // no side effects. In this case executing the backege an infinte number 5885 // of times will yield undefined behavior. 5886 // 5887 // 2. In the set of iterations including and after K, the loop body executes 5888 // at least one side effect. In this case, that specific instance of side 5889 // effect is control dependent on poison, which also yields undefined 5890 // behavior. 5891 5892 auto *ExitingBB = L->getExitingBlock(); 5893 auto *LatchBB = L->getLoopLatch(); 5894 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 5895 return false; 5896 5897 SmallPtrSet<const Instruction *, 16> Pushed; 5898 SmallVector<const Instruction *, 8> PoisonStack; 5899 5900 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 5901 // things that are known to be poison under that assumption go on the 5902 // PoisonStack. 5903 Pushed.insert(I); 5904 PoisonStack.push_back(I); 5905 5906 bool LatchControlDependentOnPoison = false; 5907 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 5908 const Instruction *Poison = PoisonStack.pop_back_val(); 5909 5910 for (auto *PoisonUser : Poison->users()) { 5911 if (propagatesPoison(cast<Instruction>(PoisonUser))) { 5912 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 5913 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 5914 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 5915 assert(BI->isConditional() && "Only possibility!"); 5916 if (BI->getParent() == LatchBB) { 5917 LatchControlDependentOnPoison = true; 5918 break; 5919 } 5920 } 5921 } 5922 } 5923 5924 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 5925 } 5926 5927 ScalarEvolution::LoopProperties 5928 ScalarEvolution::getLoopProperties(const Loop *L) { 5929 using LoopProperties = ScalarEvolution::LoopProperties; 5930 5931 auto Itr = LoopPropertiesCache.find(L); 5932 if (Itr == LoopPropertiesCache.end()) { 5933 auto HasSideEffects = [](Instruction *I) { 5934 if (auto *SI = dyn_cast<StoreInst>(I)) 5935 return !SI->isSimple(); 5936 5937 return I->mayHaveSideEffects(); 5938 }; 5939 5940 LoopProperties LP = {/* HasNoAbnormalExits */ true, 5941 /*HasNoSideEffects*/ true}; 5942 5943 for (auto *BB : L->getBlocks()) 5944 for (auto &I : *BB) { 5945 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 5946 LP.HasNoAbnormalExits = false; 5947 if (HasSideEffects(&I)) 5948 LP.HasNoSideEffects = false; 5949 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 5950 break; // We're already as pessimistic as we can get. 5951 } 5952 5953 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 5954 assert(InsertPair.second && "We just checked!"); 5955 Itr = InsertPair.first; 5956 } 5957 5958 return Itr->second; 5959 } 5960 5961 const SCEV *ScalarEvolution::createSCEV(Value *V) { 5962 if (!isSCEVable(V->getType())) 5963 return getUnknown(V); 5964 5965 if (Instruction *I = dyn_cast<Instruction>(V)) { 5966 // Don't attempt to analyze instructions in blocks that aren't 5967 // reachable. Such instructions don't matter, and they aren't required 5968 // to obey basic rules for definitions dominating uses which this 5969 // analysis depends on. 5970 if (!DT.isReachableFromEntry(I->getParent())) 5971 return getUnknown(UndefValue::get(V->getType())); 5972 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 5973 return getConstant(CI); 5974 else if (isa<ConstantPointerNull>(V)) 5975 return getZero(V->getType()); 5976 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 5977 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 5978 else if (!isa<ConstantExpr>(V)) 5979 return getUnknown(V); 5980 5981 Operator *U = cast<Operator>(V); 5982 if (auto BO = MatchBinaryOp(U, DT)) { 5983 switch (BO->Opcode) { 5984 case Instruction::Add: { 5985 // The simple thing to do would be to just call getSCEV on both operands 5986 // and call getAddExpr with the result. However if we're looking at a 5987 // bunch of things all added together, this can be quite inefficient, 5988 // because it leads to N-1 getAddExpr calls for N ultimate operands. 5989 // Instead, gather up all the operands and make a single getAddExpr call. 5990 // LLVM IR canonical form means we need only traverse the left operands. 5991 SmallVector<const SCEV *, 4> AddOps; 5992 do { 5993 if (BO->Op) { 5994 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 5995 AddOps.push_back(OpSCEV); 5996 break; 5997 } 5998 5999 // If a NUW or NSW flag can be applied to the SCEV for this 6000 // addition, then compute the SCEV for this addition by itself 6001 // with a separate call to getAddExpr. We need to do that 6002 // instead of pushing the operands of the addition onto AddOps, 6003 // since the flags are only known to apply to this particular 6004 // addition - they may not apply to other additions that can be 6005 // formed with operands from AddOps. 6006 const SCEV *RHS = getSCEV(BO->RHS); 6007 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6008 if (Flags != SCEV::FlagAnyWrap) { 6009 const SCEV *LHS = getSCEV(BO->LHS); 6010 if (BO->Opcode == Instruction::Sub) 6011 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6012 else 6013 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6014 break; 6015 } 6016 } 6017 6018 if (BO->Opcode == Instruction::Sub) 6019 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6020 else 6021 AddOps.push_back(getSCEV(BO->RHS)); 6022 6023 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6024 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6025 NewBO->Opcode != Instruction::Sub)) { 6026 AddOps.push_back(getSCEV(BO->LHS)); 6027 break; 6028 } 6029 BO = NewBO; 6030 } while (true); 6031 6032 return getAddExpr(AddOps); 6033 } 6034 6035 case Instruction::Mul: { 6036 SmallVector<const SCEV *, 4> MulOps; 6037 do { 6038 if (BO->Op) { 6039 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6040 MulOps.push_back(OpSCEV); 6041 break; 6042 } 6043 6044 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6045 if (Flags != SCEV::FlagAnyWrap) { 6046 MulOps.push_back( 6047 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6048 break; 6049 } 6050 } 6051 6052 MulOps.push_back(getSCEV(BO->RHS)); 6053 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6054 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6055 MulOps.push_back(getSCEV(BO->LHS)); 6056 break; 6057 } 6058 BO = NewBO; 6059 } while (true); 6060 6061 return getMulExpr(MulOps); 6062 } 6063 case Instruction::UDiv: 6064 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6065 case Instruction::URem: 6066 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6067 case Instruction::Sub: { 6068 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6069 if (BO->Op) 6070 Flags = getNoWrapFlagsFromUB(BO->Op); 6071 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6072 } 6073 case Instruction::And: 6074 // For an expression like x&255 that merely masks off the high bits, 6075 // use zext(trunc(x)) as the SCEV expression. 6076 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6077 if (CI->isZero()) 6078 return getSCEV(BO->RHS); 6079 if (CI->isMinusOne()) 6080 return getSCEV(BO->LHS); 6081 const APInt &A = CI->getValue(); 6082 6083 // Instcombine's ShrinkDemandedConstant may strip bits out of 6084 // constants, obscuring what would otherwise be a low-bits mask. 6085 // Use computeKnownBits to compute what ShrinkDemandedConstant 6086 // knew about to reconstruct a low-bits mask value. 6087 unsigned LZ = A.countLeadingZeros(); 6088 unsigned TZ = A.countTrailingZeros(); 6089 unsigned BitWidth = A.getBitWidth(); 6090 KnownBits Known(BitWidth); 6091 computeKnownBits(BO->LHS, Known, getDataLayout(), 6092 0, &AC, nullptr, &DT); 6093 6094 APInt EffectiveMask = 6095 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6096 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6097 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6098 const SCEV *LHS = getSCEV(BO->LHS); 6099 const SCEV *ShiftedLHS = nullptr; 6100 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6101 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6102 // For an expression like (x * 8) & 8, simplify the multiply. 6103 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6104 unsigned GCD = std::min(MulZeros, TZ); 6105 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6106 SmallVector<const SCEV*, 4> MulOps; 6107 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6108 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6109 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6110 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6111 } 6112 } 6113 if (!ShiftedLHS) 6114 ShiftedLHS = getUDivExpr(LHS, MulCount); 6115 return getMulExpr( 6116 getZeroExtendExpr( 6117 getTruncateExpr(ShiftedLHS, 6118 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6119 BO->LHS->getType()), 6120 MulCount); 6121 } 6122 } 6123 break; 6124 6125 case Instruction::Or: 6126 // If the RHS of the Or is a constant, we may have something like: 6127 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6128 // optimizations will transparently handle this case. 6129 // 6130 // In order for this transformation to be safe, the LHS must be of the 6131 // form X*(2^n) and the Or constant must be less than 2^n. 6132 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6133 const SCEV *LHS = getSCEV(BO->LHS); 6134 const APInt &CIVal = CI->getValue(); 6135 if (GetMinTrailingZeros(LHS) >= 6136 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6137 // Build a plain add SCEV. 6138 return getAddExpr(LHS, getSCEV(CI), 6139 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6140 } 6141 } 6142 break; 6143 6144 case Instruction::Xor: 6145 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6146 // If the RHS of xor is -1, then this is a not operation. 6147 if (CI->isMinusOne()) 6148 return getNotSCEV(getSCEV(BO->LHS)); 6149 6150 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6151 // This is a variant of the check for xor with -1, and it handles 6152 // the case where instcombine has trimmed non-demanded bits out 6153 // of an xor with -1. 6154 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6155 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6156 if (LBO->getOpcode() == Instruction::And && 6157 LCI->getValue() == CI->getValue()) 6158 if (const SCEVZeroExtendExpr *Z = 6159 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6160 Type *UTy = BO->LHS->getType(); 6161 const SCEV *Z0 = Z->getOperand(); 6162 Type *Z0Ty = Z0->getType(); 6163 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6164 6165 // If C is a low-bits mask, the zero extend is serving to 6166 // mask off the high bits. Complement the operand and 6167 // re-apply the zext. 6168 if (CI->getValue().isMask(Z0TySize)) 6169 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6170 6171 // If C is a single bit, it may be in the sign-bit position 6172 // before the zero-extend. In this case, represent the xor 6173 // using an add, which is equivalent, and re-apply the zext. 6174 APInt Trunc = CI->getValue().trunc(Z0TySize); 6175 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6176 Trunc.isSignMask()) 6177 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6178 UTy); 6179 } 6180 } 6181 break; 6182 6183 case Instruction::Shl: 6184 // Turn shift left of a constant amount into a multiply. 6185 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6186 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6187 6188 // If the shift count is not less than the bitwidth, the result of 6189 // the shift is undefined. Don't try to analyze it, because the 6190 // resolution chosen here may differ from the resolution chosen in 6191 // other parts of the compiler. 6192 if (SA->getValue().uge(BitWidth)) 6193 break; 6194 6195 // We can safely preserve the nuw flag in all cases. It's also safe to 6196 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6197 // requires special handling. It can be preserved as long as we're not 6198 // left shifting by bitwidth - 1. 6199 auto Flags = SCEV::FlagAnyWrap; 6200 if (BO->Op) { 6201 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6202 if ((MulFlags & SCEV::FlagNSW) && 6203 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6204 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6205 if (MulFlags & SCEV::FlagNUW) 6206 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6207 } 6208 6209 Constant *X = ConstantInt::get( 6210 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6211 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6212 } 6213 break; 6214 6215 case Instruction::AShr: { 6216 // AShr X, C, where C is a constant. 6217 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6218 if (!CI) 6219 break; 6220 6221 Type *OuterTy = BO->LHS->getType(); 6222 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6223 // If the shift count is not less than the bitwidth, the result of 6224 // the shift is undefined. Don't try to analyze it, because the 6225 // resolution chosen here may differ from the resolution chosen in 6226 // other parts of the compiler. 6227 if (CI->getValue().uge(BitWidth)) 6228 break; 6229 6230 if (CI->isZero()) 6231 return getSCEV(BO->LHS); // shift by zero --> noop 6232 6233 uint64_t AShrAmt = CI->getZExtValue(); 6234 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6235 6236 Operator *L = dyn_cast<Operator>(BO->LHS); 6237 if (L && L->getOpcode() == Instruction::Shl) { 6238 // X = Shl A, n 6239 // Y = AShr X, m 6240 // Both n and m are constant. 6241 6242 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6243 if (L->getOperand(1) == BO->RHS) 6244 // For a two-shift sext-inreg, i.e. n = m, 6245 // use sext(trunc(x)) as the SCEV expression. 6246 return getSignExtendExpr( 6247 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6248 6249 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6250 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6251 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6252 if (ShlAmt > AShrAmt) { 6253 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6254 // expression. We already checked that ShlAmt < BitWidth, so 6255 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6256 // ShlAmt - AShrAmt < Amt. 6257 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6258 ShlAmt - AShrAmt); 6259 return getSignExtendExpr( 6260 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6261 getConstant(Mul)), OuterTy); 6262 } 6263 } 6264 } 6265 break; 6266 } 6267 } 6268 } 6269 6270 switch (U->getOpcode()) { 6271 case Instruction::Trunc: 6272 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6273 6274 case Instruction::ZExt: 6275 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6276 6277 case Instruction::SExt: 6278 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6279 // The NSW flag of a subtract does not always survive the conversion to 6280 // A + (-1)*B. By pushing sign extension onto its operands we are much 6281 // more likely to preserve NSW and allow later AddRec optimisations. 6282 // 6283 // NOTE: This is effectively duplicating this logic from getSignExtend: 6284 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6285 // but by that point the NSW information has potentially been lost. 6286 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6287 Type *Ty = U->getType(); 6288 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6289 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6290 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6291 } 6292 } 6293 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6294 6295 case Instruction::BitCast: 6296 // BitCasts are no-op casts so we just eliminate the cast. 6297 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6298 return getSCEV(U->getOperand(0)); 6299 break; 6300 6301 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6302 // lead to pointer expressions which cannot safely be expanded to GEPs, 6303 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6304 // simplifying integer expressions. 6305 6306 case Instruction::GetElementPtr: 6307 return createNodeForGEP(cast<GEPOperator>(U)); 6308 6309 case Instruction::PHI: 6310 return createNodeForPHI(cast<PHINode>(U)); 6311 6312 case Instruction::Select: 6313 // U can also be a select constant expr, which let fall through. Since 6314 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6315 // constant expressions cannot have instructions as operands, we'd have 6316 // returned getUnknown for a select constant expressions anyway. 6317 if (isa<Instruction>(U)) 6318 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6319 U->getOperand(1), U->getOperand(2)); 6320 break; 6321 6322 case Instruction::Call: 6323 case Instruction::Invoke: 6324 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6325 return getSCEV(RV); 6326 break; 6327 } 6328 6329 return getUnknown(V); 6330 } 6331 6332 //===----------------------------------------------------------------------===// 6333 // Iteration Count Computation Code 6334 // 6335 6336 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6337 if (!ExitCount) 6338 return 0; 6339 6340 ConstantInt *ExitConst = ExitCount->getValue(); 6341 6342 // Guard against huge trip counts. 6343 if (ExitConst->getValue().getActiveBits() > 32) 6344 return 0; 6345 6346 // In case of integer overflow, this returns 0, which is correct. 6347 return ((unsigned)ExitConst->getZExtValue()) + 1; 6348 } 6349 6350 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6351 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6352 return getSmallConstantTripCount(L, ExitingBB); 6353 6354 // No trip count information for multiple exits. 6355 return 0; 6356 } 6357 6358 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6359 BasicBlock *ExitingBlock) { 6360 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6361 assert(L->isLoopExiting(ExitingBlock) && 6362 "Exiting block must actually branch out of the loop!"); 6363 const SCEVConstant *ExitCount = 6364 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6365 return getConstantTripCount(ExitCount); 6366 } 6367 6368 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6369 const auto *MaxExitCount = 6370 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6371 return getConstantTripCount(MaxExitCount); 6372 } 6373 6374 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6375 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6376 return getSmallConstantTripMultiple(L, ExitingBB); 6377 6378 // No trip multiple information for multiple exits. 6379 return 0; 6380 } 6381 6382 /// Returns the largest constant divisor of the trip count of this loop as a 6383 /// normal unsigned value, if possible. This means that the actual trip count is 6384 /// always a multiple of the returned value (don't forget the trip count could 6385 /// very well be zero as well!). 6386 /// 6387 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6388 /// multiple of a constant (which is also the case if the trip count is simply 6389 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6390 /// if the trip count is very large (>= 2^32). 6391 /// 6392 /// As explained in the comments for getSmallConstantTripCount, this assumes 6393 /// that control exits the loop via ExitingBlock. 6394 unsigned 6395 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6396 BasicBlock *ExitingBlock) { 6397 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6398 assert(L->isLoopExiting(ExitingBlock) && 6399 "Exiting block must actually branch out of the loop!"); 6400 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6401 if (ExitCount == getCouldNotCompute()) 6402 return 1; 6403 6404 // Get the trip count from the BE count by adding 1. 6405 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6406 6407 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6408 if (!TC) 6409 // Attempt to factor more general cases. Returns the greatest power of 6410 // two divisor. If overflow happens, the trip count expression is still 6411 // divisible by the greatest power of 2 divisor returned. 6412 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6413 6414 ConstantInt *Result = TC->getValue(); 6415 6416 // Guard against huge trip counts (this requires checking 6417 // for zero to handle the case where the trip count == -1 and the 6418 // addition wraps). 6419 if (!Result || Result->getValue().getActiveBits() > 32 || 6420 Result->getValue().getActiveBits() == 0) 6421 return 1; 6422 6423 return (unsigned)Result->getZExtValue(); 6424 } 6425 6426 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6427 BasicBlock *ExitingBlock, 6428 ExitCountKind Kind) { 6429 switch (Kind) { 6430 case Exact: 6431 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6432 case ConstantMaximum: 6433 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6434 }; 6435 llvm_unreachable("Invalid ExitCountKind!"); 6436 } 6437 6438 const SCEV * 6439 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6440 SCEVUnionPredicate &Preds) { 6441 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6442 } 6443 6444 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6445 ExitCountKind Kind) { 6446 switch (Kind) { 6447 case Exact: 6448 return getBackedgeTakenInfo(L).getExact(L, this); 6449 case ConstantMaximum: 6450 return getBackedgeTakenInfo(L).getMax(this); 6451 }; 6452 llvm_unreachable("Invalid ExitCountKind!"); 6453 } 6454 6455 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6456 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6457 } 6458 6459 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6460 static void 6461 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6462 BasicBlock *Header = L->getHeader(); 6463 6464 // Push all Loop-header PHIs onto the Worklist stack. 6465 for (PHINode &PN : Header->phis()) 6466 Worklist.push_back(&PN); 6467 } 6468 6469 const ScalarEvolution::BackedgeTakenInfo & 6470 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6471 auto &BTI = getBackedgeTakenInfo(L); 6472 if (BTI.hasFullInfo()) 6473 return BTI; 6474 6475 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6476 6477 if (!Pair.second) 6478 return Pair.first->second; 6479 6480 BackedgeTakenInfo Result = 6481 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6482 6483 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6484 } 6485 6486 const ScalarEvolution::BackedgeTakenInfo & 6487 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6488 // Initially insert an invalid entry for this loop. If the insertion 6489 // succeeds, proceed to actually compute a backedge-taken count and 6490 // update the value. The temporary CouldNotCompute value tells SCEV 6491 // code elsewhere that it shouldn't attempt to request a new 6492 // backedge-taken count, which could result in infinite recursion. 6493 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6494 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6495 if (!Pair.second) 6496 return Pair.first->second; 6497 6498 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6499 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6500 // must be cleared in this scope. 6501 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6502 6503 // In product build, there are no usage of statistic. 6504 (void)NumTripCountsComputed; 6505 (void)NumTripCountsNotComputed; 6506 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6507 const SCEV *BEExact = Result.getExact(L, this); 6508 if (BEExact != getCouldNotCompute()) { 6509 assert(isLoopInvariant(BEExact, L) && 6510 isLoopInvariant(Result.getMax(this), L) && 6511 "Computed backedge-taken count isn't loop invariant for loop!"); 6512 ++NumTripCountsComputed; 6513 } 6514 else if (Result.getMax(this) == getCouldNotCompute() && 6515 isa<PHINode>(L->getHeader()->begin())) { 6516 // Only count loops that have phi nodes as not being computable. 6517 ++NumTripCountsNotComputed; 6518 } 6519 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6520 6521 // Now that we know more about the trip count for this loop, forget any 6522 // existing SCEV values for PHI nodes in this loop since they are only 6523 // conservative estimates made without the benefit of trip count 6524 // information. This is similar to the code in forgetLoop, except that 6525 // it handles SCEVUnknown PHI nodes specially. 6526 if (Result.hasAnyInfo()) { 6527 SmallVector<Instruction *, 16> Worklist; 6528 PushLoopPHIs(L, Worklist); 6529 6530 SmallPtrSet<Instruction *, 8> Discovered; 6531 while (!Worklist.empty()) { 6532 Instruction *I = Worklist.pop_back_val(); 6533 6534 ValueExprMapType::iterator It = 6535 ValueExprMap.find_as(static_cast<Value *>(I)); 6536 if (It != ValueExprMap.end()) { 6537 const SCEV *Old = It->second; 6538 6539 // SCEVUnknown for a PHI either means that it has an unrecognized 6540 // structure, or it's a PHI that's in the progress of being computed 6541 // by createNodeForPHI. In the former case, additional loop trip 6542 // count information isn't going to change anything. In the later 6543 // case, createNodeForPHI will perform the necessary updates on its 6544 // own when it gets to that point. 6545 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6546 eraseValueFromMap(It->first); 6547 forgetMemoizedResults(Old); 6548 } 6549 if (PHINode *PN = dyn_cast<PHINode>(I)) 6550 ConstantEvolutionLoopExitValue.erase(PN); 6551 } 6552 6553 // Since we don't need to invalidate anything for correctness and we're 6554 // only invalidating to make SCEV's results more precise, we get to stop 6555 // early to avoid invalidating too much. This is especially important in 6556 // cases like: 6557 // 6558 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6559 // loop0: 6560 // %pn0 = phi 6561 // ... 6562 // loop1: 6563 // %pn1 = phi 6564 // ... 6565 // 6566 // where both loop0 and loop1's backedge taken count uses the SCEV 6567 // expression for %v. If we don't have the early stop below then in cases 6568 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6569 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6570 // count for loop1, effectively nullifying SCEV's trip count cache. 6571 for (auto *U : I->users()) 6572 if (auto *I = dyn_cast<Instruction>(U)) { 6573 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6574 if (LoopForUser && L->contains(LoopForUser) && 6575 Discovered.insert(I).second) 6576 Worklist.push_back(I); 6577 } 6578 } 6579 } 6580 6581 // Re-lookup the insert position, since the call to 6582 // computeBackedgeTakenCount above could result in a 6583 // recusive call to getBackedgeTakenInfo (on a different 6584 // loop), which would invalidate the iterator computed 6585 // earlier. 6586 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6587 } 6588 6589 void ScalarEvolution::forgetAllLoops() { 6590 // This method is intended to forget all info about loops. It should 6591 // invalidate caches as if the following happened: 6592 // - The trip counts of all loops have changed arbitrarily 6593 // - Every llvm::Value has been updated in place to produce a different 6594 // result. 6595 BackedgeTakenCounts.clear(); 6596 PredicatedBackedgeTakenCounts.clear(); 6597 LoopPropertiesCache.clear(); 6598 ConstantEvolutionLoopExitValue.clear(); 6599 ValueExprMap.clear(); 6600 ValuesAtScopes.clear(); 6601 LoopDispositions.clear(); 6602 BlockDispositions.clear(); 6603 UnsignedRanges.clear(); 6604 SignedRanges.clear(); 6605 ExprValueMap.clear(); 6606 HasRecMap.clear(); 6607 MinTrailingZerosCache.clear(); 6608 PredicatedSCEVRewrites.clear(); 6609 } 6610 6611 void ScalarEvolution::forgetLoop(const Loop *L) { 6612 // Drop any stored trip count value. 6613 auto RemoveLoopFromBackedgeMap = 6614 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6615 auto BTCPos = Map.find(L); 6616 if (BTCPos != Map.end()) { 6617 BTCPos->second.clear(); 6618 Map.erase(BTCPos); 6619 } 6620 }; 6621 6622 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6623 SmallVector<Instruction *, 32> Worklist; 6624 SmallPtrSet<Instruction *, 16> Visited; 6625 6626 // Iterate over all the loops and sub-loops to drop SCEV information. 6627 while (!LoopWorklist.empty()) { 6628 auto *CurrL = LoopWorklist.pop_back_val(); 6629 6630 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6631 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6632 6633 // Drop information about predicated SCEV rewrites for this loop. 6634 for (auto I = PredicatedSCEVRewrites.begin(); 6635 I != PredicatedSCEVRewrites.end();) { 6636 std::pair<const SCEV *, const Loop *> Entry = I->first; 6637 if (Entry.second == CurrL) 6638 PredicatedSCEVRewrites.erase(I++); 6639 else 6640 ++I; 6641 } 6642 6643 auto LoopUsersItr = LoopUsers.find(CurrL); 6644 if (LoopUsersItr != LoopUsers.end()) { 6645 for (auto *S : LoopUsersItr->second) 6646 forgetMemoizedResults(S); 6647 LoopUsers.erase(LoopUsersItr); 6648 } 6649 6650 // Drop information about expressions based on loop-header PHIs. 6651 PushLoopPHIs(CurrL, Worklist); 6652 6653 while (!Worklist.empty()) { 6654 Instruction *I = Worklist.pop_back_val(); 6655 if (!Visited.insert(I).second) 6656 continue; 6657 6658 ValueExprMapType::iterator It = 6659 ValueExprMap.find_as(static_cast<Value *>(I)); 6660 if (It != ValueExprMap.end()) { 6661 eraseValueFromMap(It->first); 6662 forgetMemoizedResults(It->second); 6663 if (PHINode *PN = dyn_cast<PHINode>(I)) 6664 ConstantEvolutionLoopExitValue.erase(PN); 6665 } 6666 6667 PushDefUseChildren(I, Worklist); 6668 } 6669 6670 LoopPropertiesCache.erase(CurrL); 6671 // Forget all contained loops too, to avoid dangling entries in the 6672 // ValuesAtScopes map. 6673 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6674 } 6675 } 6676 6677 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6678 while (Loop *Parent = L->getParentLoop()) 6679 L = Parent; 6680 forgetLoop(L); 6681 } 6682 6683 void ScalarEvolution::forgetValue(Value *V) { 6684 Instruction *I = dyn_cast<Instruction>(V); 6685 if (!I) return; 6686 6687 // Drop information about expressions based on loop-header PHIs. 6688 SmallVector<Instruction *, 16> Worklist; 6689 Worklist.push_back(I); 6690 6691 SmallPtrSet<Instruction *, 8> Visited; 6692 while (!Worklist.empty()) { 6693 I = Worklist.pop_back_val(); 6694 if (!Visited.insert(I).second) 6695 continue; 6696 6697 ValueExprMapType::iterator It = 6698 ValueExprMap.find_as(static_cast<Value *>(I)); 6699 if (It != ValueExprMap.end()) { 6700 eraseValueFromMap(It->first); 6701 forgetMemoizedResults(It->second); 6702 if (PHINode *PN = dyn_cast<PHINode>(I)) 6703 ConstantEvolutionLoopExitValue.erase(PN); 6704 } 6705 6706 PushDefUseChildren(I, Worklist); 6707 } 6708 } 6709 6710 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 6711 LoopDispositions.clear(); 6712 } 6713 6714 /// Get the exact loop backedge taken count considering all loop exits. A 6715 /// computable result can only be returned for loops with all exiting blocks 6716 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6717 /// is never skipped. This is a valid assumption as long as the loop exits via 6718 /// that test. For precise results, it is the caller's responsibility to specify 6719 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6720 const SCEV * 6721 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6722 SCEVUnionPredicate *Preds) const { 6723 // If any exits were not computable, the loop is not computable. 6724 if (!isComplete() || ExitNotTaken.empty()) 6725 return SE->getCouldNotCompute(); 6726 6727 const BasicBlock *Latch = L->getLoopLatch(); 6728 // All exiting blocks we have collected must dominate the only backedge. 6729 if (!Latch) 6730 return SE->getCouldNotCompute(); 6731 6732 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6733 // count is simply a minimum out of all these calculated exit counts. 6734 SmallVector<const SCEV *, 2> Ops; 6735 for (auto &ENT : ExitNotTaken) { 6736 const SCEV *BECount = ENT.ExactNotTaken; 6737 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6738 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6739 "We should only have known counts for exiting blocks that dominate " 6740 "latch!"); 6741 6742 Ops.push_back(BECount); 6743 6744 if (Preds && !ENT.hasAlwaysTruePredicate()) 6745 Preds->add(ENT.Predicate.get()); 6746 6747 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6748 "Predicate should be always true!"); 6749 } 6750 6751 return SE->getUMinFromMismatchedTypes(Ops); 6752 } 6753 6754 /// Get the exact not taken count for this loop exit. 6755 const SCEV * 6756 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6757 ScalarEvolution *SE) const { 6758 for (auto &ENT : ExitNotTaken) 6759 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6760 return ENT.ExactNotTaken; 6761 6762 return SE->getCouldNotCompute(); 6763 } 6764 6765 const SCEV * 6766 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock, 6767 ScalarEvolution *SE) const { 6768 for (auto &ENT : ExitNotTaken) 6769 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6770 return ENT.MaxNotTaken; 6771 6772 return SE->getCouldNotCompute(); 6773 } 6774 6775 /// getMax - Get the max backedge taken count for the loop. 6776 const SCEV * 6777 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6778 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6779 return !ENT.hasAlwaysTruePredicate(); 6780 }; 6781 6782 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6783 return SE->getCouldNotCompute(); 6784 6785 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6786 "No point in having a non-constant max backedge taken count!"); 6787 return getMax(); 6788 } 6789 6790 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6791 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6792 return !ENT.hasAlwaysTruePredicate(); 6793 }; 6794 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6795 } 6796 6797 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6798 ScalarEvolution *SE) const { 6799 if (getMax() && getMax() != SE->getCouldNotCompute() && 6800 SE->hasOperand(getMax(), S)) 6801 return true; 6802 6803 for (auto &ENT : ExitNotTaken) 6804 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6805 SE->hasOperand(ENT.ExactNotTaken, S)) 6806 return true; 6807 6808 return false; 6809 } 6810 6811 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6812 : ExactNotTaken(E), MaxNotTaken(E) { 6813 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6814 isa<SCEVConstant>(MaxNotTaken)) && 6815 "No point in having a non-constant max backedge taken count!"); 6816 } 6817 6818 ScalarEvolution::ExitLimit::ExitLimit( 6819 const SCEV *E, const SCEV *M, bool MaxOrZero, 6820 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 6821 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 6822 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 6823 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 6824 "Exact is not allowed to be less precise than Max"); 6825 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6826 isa<SCEVConstant>(MaxNotTaken)) && 6827 "No point in having a non-constant max backedge taken count!"); 6828 for (auto *PredSet : PredSetList) 6829 for (auto *P : *PredSet) 6830 addPredicate(P); 6831 } 6832 6833 ScalarEvolution::ExitLimit::ExitLimit( 6834 const SCEV *E, const SCEV *M, bool MaxOrZero, 6835 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 6836 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 6837 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6838 isa<SCEVConstant>(MaxNotTaken)) && 6839 "No point in having a non-constant max backedge taken count!"); 6840 } 6841 6842 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 6843 bool MaxOrZero) 6844 : ExitLimit(E, M, MaxOrZero, None) { 6845 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6846 isa<SCEVConstant>(MaxNotTaken)) && 6847 "No point in having a non-constant max backedge taken count!"); 6848 } 6849 6850 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 6851 /// computable exit into a persistent ExitNotTakenInfo array. 6852 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 6853 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 6854 ExitCounts, 6855 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 6856 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 6857 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6858 6859 ExitNotTaken.reserve(ExitCounts.size()); 6860 std::transform( 6861 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 6862 [&](const EdgeExitInfo &EEI) { 6863 BasicBlock *ExitBB = EEI.first; 6864 const ExitLimit &EL = EEI.second; 6865 if (EL.Predicates.empty()) 6866 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 6867 nullptr); 6868 6869 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 6870 for (auto *Pred : EL.Predicates) 6871 Predicate->add(Pred); 6872 6873 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 6874 std::move(Predicate)); 6875 }); 6876 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 6877 "No point in having a non-constant max backedge taken count!"); 6878 } 6879 6880 /// Invalidate this result and free the ExitNotTakenInfo array. 6881 void ScalarEvolution::BackedgeTakenInfo::clear() { 6882 ExitNotTaken.clear(); 6883 } 6884 6885 /// Compute the number of times the backedge of the specified loop will execute. 6886 ScalarEvolution::BackedgeTakenInfo 6887 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 6888 bool AllowPredicates) { 6889 SmallVector<BasicBlock *, 8> ExitingBlocks; 6890 L->getExitingBlocks(ExitingBlocks); 6891 6892 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 6893 6894 SmallVector<EdgeExitInfo, 4> ExitCounts; 6895 bool CouldComputeBECount = true; 6896 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 6897 const SCEV *MustExitMaxBECount = nullptr; 6898 const SCEV *MayExitMaxBECount = nullptr; 6899 bool MustExitMaxOrZero = false; 6900 6901 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 6902 // and compute maxBECount. 6903 // Do a union of all the predicates here. 6904 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 6905 BasicBlock *ExitBB = ExitingBlocks[i]; 6906 6907 // We canonicalize untaken exits to br (constant), ignore them so that 6908 // proving an exit untaken doesn't negatively impact our ability to reason 6909 // about the loop as whole. 6910 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 6911 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 6912 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 6913 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 6914 continue; 6915 } 6916 6917 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 6918 6919 assert((AllowPredicates || EL.Predicates.empty()) && 6920 "Predicated exit limit when predicates are not allowed!"); 6921 6922 // 1. For each exit that can be computed, add an entry to ExitCounts. 6923 // CouldComputeBECount is true only if all exits can be computed. 6924 if (EL.ExactNotTaken == getCouldNotCompute()) 6925 // We couldn't compute an exact value for this exit, so 6926 // we won't be able to compute an exact value for the loop. 6927 CouldComputeBECount = false; 6928 else 6929 ExitCounts.emplace_back(ExitBB, EL); 6930 6931 // 2. Derive the loop's MaxBECount from each exit's max number of 6932 // non-exiting iterations. Partition the loop exits into two kinds: 6933 // LoopMustExits and LoopMayExits. 6934 // 6935 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 6936 // is a LoopMayExit. If any computable LoopMustExit is found, then 6937 // MaxBECount is the minimum EL.MaxNotTaken of computable 6938 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 6939 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 6940 // computable EL.MaxNotTaken. 6941 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 6942 DT.dominates(ExitBB, Latch)) { 6943 if (!MustExitMaxBECount) { 6944 MustExitMaxBECount = EL.MaxNotTaken; 6945 MustExitMaxOrZero = EL.MaxOrZero; 6946 } else { 6947 MustExitMaxBECount = 6948 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 6949 } 6950 } else if (MayExitMaxBECount != getCouldNotCompute()) { 6951 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 6952 MayExitMaxBECount = EL.MaxNotTaken; 6953 else { 6954 MayExitMaxBECount = 6955 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 6956 } 6957 } 6958 } 6959 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 6960 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 6961 // The loop backedge will be taken the maximum or zero times if there's 6962 // a single exit that must be taken the maximum or zero times. 6963 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 6964 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 6965 MaxBECount, MaxOrZero); 6966 } 6967 6968 ScalarEvolution::ExitLimit 6969 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 6970 bool AllowPredicates) { 6971 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 6972 // If our exiting block does not dominate the latch, then its connection with 6973 // loop's exit limit may be far from trivial. 6974 const BasicBlock *Latch = L->getLoopLatch(); 6975 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 6976 return getCouldNotCompute(); 6977 6978 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 6979 Instruction *Term = ExitingBlock->getTerminator(); 6980 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 6981 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 6982 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 6983 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 6984 "It should have one successor in loop and one exit block!"); 6985 // Proceed to the next level to examine the exit condition expression. 6986 return computeExitLimitFromCond( 6987 L, BI->getCondition(), ExitIfTrue, 6988 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 6989 } 6990 6991 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 6992 // For switch, make sure that there is a single exit from the loop. 6993 BasicBlock *Exit = nullptr; 6994 for (auto *SBB : successors(ExitingBlock)) 6995 if (!L->contains(SBB)) { 6996 if (Exit) // Multiple exit successors. 6997 return getCouldNotCompute(); 6998 Exit = SBB; 6999 } 7000 assert(Exit && "Exiting block must have at least one exit"); 7001 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7002 /*ControlsExit=*/IsOnlyExit); 7003 } 7004 7005 return getCouldNotCompute(); 7006 } 7007 7008 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7009 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7010 bool ControlsExit, bool AllowPredicates) { 7011 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7012 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7013 ControlsExit, AllowPredicates); 7014 } 7015 7016 Optional<ScalarEvolution::ExitLimit> 7017 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7018 bool ExitIfTrue, bool ControlsExit, 7019 bool AllowPredicates) { 7020 (void)this->L; 7021 (void)this->ExitIfTrue; 7022 (void)this->AllowPredicates; 7023 7024 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7025 this->AllowPredicates == AllowPredicates && 7026 "Variance in assumed invariant key components!"); 7027 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7028 if (Itr == TripCountMap.end()) 7029 return None; 7030 return Itr->second; 7031 } 7032 7033 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7034 bool ExitIfTrue, 7035 bool ControlsExit, 7036 bool AllowPredicates, 7037 const ExitLimit &EL) { 7038 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7039 this->AllowPredicates == AllowPredicates && 7040 "Variance in assumed invariant key components!"); 7041 7042 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7043 assert(InsertResult.second && "Expected successful insertion!"); 7044 (void)InsertResult; 7045 (void)ExitIfTrue; 7046 } 7047 7048 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7049 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7050 bool ControlsExit, bool AllowPredicates) { 7051 7052 if (auto MaybeEL = 7053 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7054 return *MaybeEL; 7055 7056 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7057 ControlsExit, AllowPredicates); 7058 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7059 return EL; 7060 } 7061 7062 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7063 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7064 bool ControlsExit, bool AllowPredicates) { 7065 // Check if the controlling expression for this loop is an And or Or. 7066 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7067 if (BO->getOpcode() == Instruction::And) { 7068 // Recurse on the operands of the and. 7069 bool EitherMayExit = !ExitIfTrue; 7070 ExitLimit EL0 = computeExitLimitFromCondCached( 7071 Cache, L, BO->getOperand(0), ExitIfTrue, 7072 ControlsExit && !EitherMayExit, AllowPredicates); 7073 ExitLimit EL1 = computeExitLimitFromCondCached( 7074 Cache, L, BO->getOperand(1), ExitIfTrue, 7075 ControlsExit && !EitherMayExit, AllowPredicates); 7076 // Be robust against unsimplified IR for the form "and i1 X, true" 7077 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7078 return CI->isOne() ? EL0 : EL1; 7079 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7080 return CI->isOne() ? EL1 : EL0; 7081 const SCEV *BECount = getCouldNotCompute(); 7082 const SCEV *MaxBECount = getCouldNotCompute(); 7083 if (EitherMayExit) { 7084 // Both conditions must be true for the loop to continue executing. 7085 // Choose the less conservative count. 7086 if (EL0.ExactNotTaken == getCouldNotCompute() || 7087 EL1.ExactNotTaken == getCouldNotCompute()) 7088 BECount = getCouldNotCompute(); 7089 else 7090 BECount = 7091 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7092 if (EL0.MaxNotTaken == getCouldNotCompute()) 7093 MaxBECount = EL1.MaxNotTaken; 7094 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7095 MaxBECount = EL0.MaxNotTaken; 7096 else 7097 MaxBECount = 7098 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7099 } else { 7100 // Both conditions must be true at the same time for the loop to exit. 7101 // For now, be conservative. 7102 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7103 MaxBECount = EL0.MaxNotTaken; 7104 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7105 BECount = EL0.ExactNotTaken; 7106 } 7107 7108 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7109 // to be more aggressive when computing BECount than when computing 7110 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7111 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7112 // to not. 7113 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7114 !isa<SCEVCouldNotCompute>(BECount)) 7115 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7116 7117 return ExitLimit(BECount, MaxBECount, false, 7118 {&EL0.Predicates, &EL1.Predicates}); 7119 } 7120 if (BO->getOpcode() == Instruction::Or) { 7121 // Recurse on the operands of the or. 7122 bool EitherMayExit = ExitIfTrue; 7123 ExitLimit EL0 = computeExitLimitFromCondCached( 7124 Cache, L, BO->getOperand(0), ExitIfTrue, 7125 ControlsExit && !EitherMayExit, AllowPredicates); 7126 ExitLimit EL1 = computeExitLimitFromCondCached( 7127 Cache, L, BO->getOperand(1), ExitIfTrue, 7128 ControlsExit && !EitherMayExit, AllowPredicates); 7129 // Be robust against unsimplified IR for the form "or i1 X, true" 7130 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7131 return CI->isZero() ? EL0 : EL1; 7132 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7133 return CI->isZero() ? EL1 : EL0; 7134 const SCEV *BECount = getCouldNotCompute(); 7135 const SCEV *MaxBECount = getCouldNotCompute(); 7136 if (EitherMayExit) { 7137 // Both conditions must be false for the loop to continue executing. 7138 // Choose the less conservative count. 7139 if (EL0.ExactNotTaken == getCouldNotCompute() || 7140 EL1.ExactNotTaken == getCouldNotCompute()) 7141 BECount = getCouldNotCompute(); 7142 else 7143 BECount = 7144 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7145 if (EL0.MaxNotTaken == getCouldNotCompute()) 7146 MaxBECount = EL1.MaxNotTaken; 7147 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7148 MaxBECount = EL0.MaxNotTaken; 7149 else 7150 MaxBECount = 7151 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7152 } else { 7153 // Both conditions must be false at the same time for the loop to exit. 7154 // For now, be conservative. 7155 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7156 MaxBECount = EL0.MaxNotTaken; 7157 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7158 BECount = EL0.ExactNotTaken; 7159 } 7160 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7161 // to be more aggressive when computing BECount than when computing 7162 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7163 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7164 // to not. 7165 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7166 !isa<SCEVCouldNotCompute>(BECount)) 7167 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7168 7169 return ExitLimit(BECount, MaxBECount, false, 7170 {&EL0.Predicates, &EL1.Predicates}); 7171 } 7172 } 7173 7174 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7175 // Proceed to the next level to examine the icmp. 7176 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7177 ExitLimit EL = 7178 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7179 if (EL.hasFullInfo() || !AllowPredicates) 7180 return EL; 7181 7182 // Try again, but use SCEV predicates this time. 7183 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7184 /*AllowPredicates=*/true); 7185 } 7186 7187 // Check for a constant condition. These are normally stripped out by 7188 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7189 // preserve the CFG and is temporarily leaving constant conditions 7190 // in place. 7191 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7192 if (ExitIfTrue == !CI->getZExtValue()) 7193 // The backedge is always taken. 7194 return getCouldNotCompute(); 7195 else 7196 // The backedge is never taken. 7197 return getZero(CI->getType()); 7198 } 7199 7200 // If it's not an integer or pointer comparison then compute it the hard way. 7201 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7202 } 7203 7204 ScalarEvolution::ExitLimit 7205 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7206 ICmpInst *ExitCond, 7207 bool ExitIfTrue, 7208 bool ControlsExit, 7209 bool AllowPredicates) { 7210 // If the condition was exit on true, convert the condition to exit on false 7211 ICmpInst::Predicate Pred; 7212 if (!ExitIfTrue) 7213 Pred = ExitCond->getPredicate(); 7214 else 7215 Pred = ExitCond->getInversePredicate(); 7216 const ICmpInst::Predicate OriginalPred = Pred; 7217 7218 // Handle common loops like: for (X = "string"; *X; ++X) 7219 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7220 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7221 ExitLimit ItCnt = 7222 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7223 if (ItCnt.hasAnyInfo()) 7224 return ItCnt; 7225 } 7226 7227 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7228 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7229 7230 // Try to evaluate any dependencies out of the loop. 7231 LHS = getSCEVAtScope(LHS, L); 7232 RHS = getSCEVAtScope(RHS, L); 7233 7234 // At this point, we would like to compute how many iterations of the 7235 // loop the predicate will return true for these inputs. 7236 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7237 // If there is a loop-invariant, force it into the RHS. 7238 std::swap(LHS, RHS); 7239 Pred = ICmpInst::getSwappedPredicate(Pred); 7240 } 7241 7242 // Simplify the operands before analyzing them. 7243 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7244 7245 // If we have a comparison of a chrec against a constant, try to use value 7246 // ranges to answer this query. 7247 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7248 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7249 if (AddRec->getLoop() == L) { 7250 // Form the constant range. 7251 ConstantRange CompRange = 7252 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7253 7254 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7255 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7256 } 7257 7258 switch (Pred) { 7259 case ICmpInst::ICMP_NE: { // while (X != Y) 7260 // Convert to: while (X-Y != 0) 7261 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7262 AllowPredicates); 7263 if (EL.hasAnyInfo()) return EL; 7264 break; 7265 } 7266 case ICmpInst::ICMP_EQ: { // while (X == Y) 7267 // Convert to: while (X-Y == 0) 7268 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7269 if (EL.hasAnyInfo()) return EL; 7270 break; 7271 } 7272 case ICmpInst::ICMP_SLT: 7273 case ICmpInst::ICMP_ULT: { // while (X < Y) 7274 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7275 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7276 AllowPredicates); 7277 if (EL.hasAnyInfo()) return EL; 7278 break; 7279 } 7280 case ICmpInst::ICMP_SGT: 7281 case ICmpInst::ICMP_UGT: { // while (X > Y) 7282 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7283 ExitLimit EL = 7284 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7285 AllowPredicates); 7286 if (EL.hasAnyInfo()) return EL; 7287 break; 7288 } 7289 default: 7290 break; 7291 } 7292 7293 auto *ExhaustiveCount = 7294 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7295 7296 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7297 return ExhaustiveCount; 7298 7299 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7300 ExitCond->getOperand(1), L, OriginalPred); 7301 } 7302 7303 ScalarEvolution::ExitLimit 7304 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7305 SwitchInst *Switch, 7306 BasicBlock *ExitingBlock, 7307 bool ControlsExit) { 7308 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7309 7310 // Give up if the exit is the default dest of a switch. 7311 if (Switch->getDefaultDest() == ExitingBlock) 7312 return getCouldNotCompute(); 7313 7314 assert(L->contains(Switch->getDefaultDest()) && 7315 "Default case must not exit the loop!"); 7316 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7317 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7318 7319 // while (X != Y) --> while (X-Y != 0) 7320 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7321 if (EL.hasAnyInfo()) 7322 return EL; 7323 7324 return getCouldNotCompute(); 7325 } 7326 7327 static ConstantInt * 7328 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7329 ScalarEvolution &SE) { 7330 const SCEV *InVal = SE.getConstant(C); 7331 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7332 assert(isa<SCEVConstant>(Val) && 7333 "Evaluation of SCEV at constant didn't fold correctly?"); 7334 return cast<SCEVConstant>(Val)->getValue(); 7335 } 7336 7337 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7338 /// compute the backedge execution count. 7339 ScalarEvolution::ExitLimit 7340 ScalarEvolution::computeLoadConstantCompareExitLimit( 7341 LoadInst *LI, 7342 Constant *RHS, 7343 const Loop *L, 7344 ICmpInst::Predicate predicate) { 7345 if (LI->isVolatile()) return getCouldNotCompute(); 7346 7347 // Check to see if the loaded pointer is a getelementptr of a global. 7348 // TODO: Use SCEV instead of manually grubbing with GEPs. 7349 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7350 if (!GEP) return getCouldNotCompute(); 7351 7352 // Make sure that it is really a constant global we are gepping, with an 7353 // initializer, and make sure the first IDX is really 0. 7354 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7355 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7356 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7357 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7358 return getCouldNotCompute(); 7359 7360 // Okay, we allow one non-constant index into the GEP instruction. 7361 Value *VarIdx = nullptr; 7362 std::vector<Constant*> Indexes; 7363 unsigned VarIdxNum = 0; 7364 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7365 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7366 Indexes.push_back(CI); 7367 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7368 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7369 VarIdx = GEP->getOperand(i); 7370 VarIdxNum = i-2; 7371 Indexes.push_back(nullptr); 7372 } 7373 7374 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7375 if (!VarIdx) 7376 return getCouldNotCompute(); 7377 7378 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7379 // Check to see if X is a loop variant variable value now. 7380 const SCEV *Idx = getSCEV(VarIdx); 7381 Idx = getSCEVAtScope(Idx, L); 7382 7383 // We can only recognize very limited forms of loop index expressions, in 7384 // particular, only affine AddRec's like {C1,+,C2}. 7385 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7386 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7387 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7388 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7389 return getCouldNotCompute(); 7390 7391 unsigned MaxSteps = MaxBruteForceIterations; 7392 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7393 ConstantInt *ItCst = ConstantInt::get( 7394 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7395 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7396 7397 // Form the GEP offset. 7398 Indexes[VarIdxNum] = Val; 7399 7400 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7401 Indexes); 7402 if (!Result) break; // Cannot compute! 7403 7404 // Evaluate the condition for this iteration. 7405 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7406 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7407 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7408 ++NumArrayLenItCounts; 7409 return getConstant(ItCst); // Found terminating iteration! 7410 } 7411 } 7412 return getCouldNotCompute(); 7413 } 7414 7415 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7416 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7417 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7418 if (!RHS) 7419 return getCouldNotCompute(); 7420 7421 const BasicBlock *Latch = L->getLoopLatch(); 7422 if (!Latch) 7423 return getCouldNotCompute(); 7424 7425 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7426 if (!Predecessor) 7427 return getCouldNotCompute(); 7428 7429 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7430 // Return LHS in OutLHS and shift_opt in OutOpCode. 7431 auto MatchPositiveShift = 7432 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7433 7434 using namespace PatternMatch; 7435 7436 ConstantInt *ShiftAmt; 7437 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7438 OutOpCode = Instruction::LShr; 7439 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7440 OutOpCode = Instruction::AShr; 7441 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7442 OutOpCode = Instruction::Shl; 7443 else 7444 return false; 7445 7446 return ShiftAmt->getValue().isStrictlyPositive(); 7447 }; 7448 7449 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7450 // 7451 // loop: 7452 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7453 // %iv.shifted = lshr i32 %iv, <positive constant> 7454 // 7455 // Return true on a successful match. Return the corresponding PHI node (%iv 7456 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7457 auto MatchShiftRecurrence = 7458 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7459 Optional<Instruction::BinaryOps> PostShiftOpCode; 7460 7461 { 7462 Instruction::BinaryOps OpC; 7463 Value *V; 7464 7465 // If we encounter a shift instruction, "peel off" the shift operation, 7466 // and remember that we did so. Later when we inspect %iv's backedge 7467 // value, we will make sure that the backedge value uses the same 7468 // operation. 7469 // 7470 // Note: the peeled shift operation does not have to be the same 7471 // instruction as the one feeding into the PHI's backedge value. We only 7472 // really care about it being the same *kind* of shift instruction -- 7473 // that's all that is required for our later inferences to hold. 7474 if (MatchPositiveShift(LHS, V, OpC)) { 7475 PostShiftOpCode = OpC; 7476 LHS = V; 7477 } 7478 } 7479 7480 PNOut = dyn_cast<PHINode>(LHS); 7481 if (!PNOut || PNOut->getParent() != L->getHeader()) 7482 return false; 7483 7484 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7485 Value *OpLHS; 7486 7487 return 7488 // The backedge value for the PHI node must be a shift by a positive 7489 // amount 7490 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7491 7492 // of the PHI node itself 7493 OpLHS == PNOut && 7494 7495 // and the kind of shift should be match the kind of shift we peeled 7496 // off, if any. 7497 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7498 }; 7499 7500 PHINode *PN; 7501 Instruction::BinaryOps OpCode; 7502 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7503 return getCouldNotCompute(); 7504 7505 const DataLayout &DL = getDataLayout(); 7506 7507 // The key rationale for this optimization is that for some kinds of shift 7508 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7509 // within a finite number of iterations. If the condition guarding the 7510 // backedge (in the sense that the backedge is taken if the condition is true) 7511 // is false for the value the shift recurrence stabilizes to, then we know 7512 // that the backedge is taken only a finite number of times. 7513 7514 ConstantInt *StableValue = nullptr; 7515 switch (OpCode) { 7516 default: 7517 llvm_unreachable("Impossible case!"); 7518 7519 case Instruction::AShr: { 7520 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7521 // bitwidth(K) iterations. 7522 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7523 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7524 Predecessor->getTerminator(), &DT); 7525 auto *Ty = cast<IntegerType>(RHS->getType()); 7526 if (Known.isNonNegative()) 7527 StableValue = ConstantInt::get(Ty, 0); 7528 else if (Known.isNegative()) 7529 StableValue = ConstantInt::get(Ty, -1, true); 7530 else 7531 return getCouldNotCompute(); 7532 7533 break; 7534 } 7535 case Instruction::LShr: 7536 case Instruction::Shl: 7537 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7538 // stabilize to 0 in at most bitwidth(K) iterations. 7539 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7540 break; 7541 } 7542 7543 auto *Result = 7544 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7545 assert(Result->getType()->isIntegerTy(1) && 7546 "Otherwise cannot be an operand to a branch instruction"); 7547 7548 if (Result->isZeroValue()) { 7549 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7550 const SCEV *UpperBound = 7551 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7552 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7553 } 7554 7555 return getCouldNotCompute(); 7556 } 7557 7558 /// Return true if we can constant fold an instruction of the specified type, 7559 /// assuming that all operands were constants. 7560 static bool CanConstantFold(const Instruction *I) { 7561 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7562 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7563 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7564 return true; 7565 7566 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7567 if (const Function *F = CI->getCalledFunction()) 7568 return canConstantFoldCallTo(CI, F); 7569 return false; 7570 } 7571 7572 /// Determine whether this instruction can constant evolve within this loop 7573 /// assuming its operands can all constant evolve. 7574 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7575 // An instruction outside of the loop can't be derived from a loop PHI. 7576 if (!L->contains(I)) return false; 7577 7578 if (isa<PHINode>(I)) { 7579 // We don't currently keep track of the control flow needed to evaluate 7580 // PHIs, so we cannot handle PHIs inside of loops. 7581 return L->getHeader() == I->getParent(); 7582 } 7583 7584 // If we won't be able to constant fold this expression even if the operands 7585 // are constants, bail early. 7586 return CanConstantFold(I); 7587 } 7588 7589 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7590 /// recursing through each instruction operand until reaching a loop header phi. 7591 static PHINode * 7592 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7593 DenseMap<Instruction *, PHINode *> &PHIMap, 7594 unsigned Depth) { 7595 if (Depth > MaxConstantEvolvingDepth) 7596 return nullptr; 7597 7598 // Otherwise, we can evaluate this instruction if all of its operands are 7599 // constant or derived from a PHI node themselves. 7600 PHINode *PHI = nullptr; 7601 for (Value *Op : UseInst->operands()) { 7602 if (isa<Constant>(Op)) continue; 7603 7604 Instruction *OpInst = dyn_cast<Instruction>(Op); 7605 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7606 7607 PHINode *P = dyn_cast<PHINode>(OpInst); 7608 if (!P) 7609 // If this operand is already visited, reuse the prior result. 7610 // We may have P != PHI if this is the deepest point at which the 7611 // inconsistent paths meet. 7612 P = PHIMap.lookup(OpInst); 7613 if (!P) { 7614 // Recurse and memoize the results, whether a phi is found or not. 7615 // This recursive call invalidates pointers into PHIMap. 7616 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7617 PHIMap[OpInst] = P; 7618 } 7619 if (!P) 7620 return nullptr; // Not evolving from PHI 7621 if (PHI && PHI != P) 7622 return nullptr; // Evolving from multiple different PHIs. 7623 PHI = P; 7624 } 7625 // This is a expression evolving from a constant PHI! 7626 return PHI; 7627 } 7628 7629 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7630 /// in the loop that V is derived from. We allow arbitrary operations along the 7631 /// way, but the operands of an operation must either be constants or a value 7632 /// derived from a constant PHI. If this expression does not fit with these 7633 /// constraints, return null. 7634 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7635 Instruction *I = dyn_cast<Instruction>(V); 7636 if (!I || !canConstantEvolve(I, L)) return nullptr; 7637 7638 if (PHINode *PN = dyn_cast<PHINode>(I)) 7639 return PN; 7640 7641 // Record non-constant instructions contained by the loop. 7642 DenseMap<Instruction *, PHINode *> PHIMap; 7643 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7644 } 7645 7646 /// EvaluateExpression - Given an expression that passes the 7647 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7648 /// in the loop has the value PHIVal. If we can't fold this expression for some 7649 /// reason, return null. 7650 static Constant *EvaluateExpression(Value *V, const Loop *L, 7651 DenseMap<Instruction *, Constant *> &Vals, 7652 const DataLayout &DL, 7653 const TargetLibraryInfo *TLI) { 7654 // Convenient constant check, but redundant for recursive calls. 7655 if (Constant *C = dyn_cast<Constant>(V)) return C; 7656 Instruction *I = dyn_cast<Instruction>(V); 7657 if (!I) return nullptr; 7658 7659 if (Constant *C = Vals.lookup(I)) return C; 7660 7661 // An instruction inside the loop depends on a value outside the loop that we 7662 // weren't given a mapping for, or a value such as a call inside the loop. 7663 if (!canConstantEvolve(I, L)) return nullptr; 7664 7665 // An unmapped PHI can be due to a branch or another loop inside this loop, 7666 // or due to this not being the initial iteration through a loop where we 7667 // couldn't compute the evolution of this particular PHI last time. 7668 if (isa<PHINode>(I)) return nullptr; 7669 7670 std::vector<Constant*> Operands(I->getNumOperands()); 7671 7672 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7673 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7674 if (!Operand) { 7675 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7676 if (!Operands[i]) return nullptr; 7677 continue; 7678 } 7679 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7680 Vals[Operand] = C; 7681 if (!C) return nullptr; 7682 Operands[i] = C; 7683 } 7684 7685 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7686 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7687 Operands[1], DL, TLI); 7688 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7689 if (!LI->isVolatile()) 7690 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7691 } 7692 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7693 } 7694 7695 7696 // If every incoming value to PN except the one for BB is a specific Constant, 7697 // return that, else return nullptr. 7698 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7699 Constant *IncomingVal = nullptr; 7700 7701 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7702 if (PN->getIncomingBlock(i) == BB) 7703 continue; 7704 7705 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7706 if (!CurrentVal) 7707 return nullptr; 7708 7709 if (IncomingVal != CurrentVal) { 7710 if (IncomingVal) 7711 return nullptr; 7712 IncomingVal = CurrentVal; 7713 } 7714 } 7715 7716 return IncomingVal; 7717 } 7718 7719 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7720 /// in the header of its containing loop, we know the loop executes a 7721 /// constant number of times, and the PHI node is just a recurrence 7722 /// involving constants, fold it. 7723 Constant * 7724 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7725 const APInt &BEs, 7726 const Loop *L) { 7727 auto I = ConstantEvolutionLoopExitValue.find(PN); 7728 if (I != ConstantEvolutionLoopExitValue.end()) 7729 return I->second; 7730 7731 if (BEs.ugt(MaxBruteForceIterations)) 7732 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7733 7734 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7735 7736 DenseMap<Instruction *, Constant *> CurrentIterVals; 7737 BasicBlock *Header = L->getHeader(); 7738 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7739 7740 BasicBlock *Latch = L->getLoopLatch(); 7741 if (!Latch) 7742 return nullptr; 7743 7744 for (PHINode &PHI : Header->phis()) { 7745 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7746 CurrentIterVals[&PHI] = StartCST; 7747 } 7748 if (!CurrentIterVals.count(PN)) 7749 return RetVal = nullptr; 7750 7751 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7752 7753 // Execute the loop symbolically to determine the exit value. 7754 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7755 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7756 7757 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7758 unsigned IterationNum = 0; 7759 const DataLayout &DL = getDataLayout(); 7760 for (; ; ++IterationNum) { 7761 if (IterationNum == NumIterations) 7762 return RetVal = CurrentIterVals[PN]; // Got exit value! 7763 7764 // Compute the value of the PHIs for the next iteration. 7765 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7766 DenseMap<Instruction *, Constant *> NextIterVals; 7767 Constant *NextPHI = 7768 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7769 if (!NextPHI) 7770 return nullptr; // Couldn't evaluate! 7771 NextIterVals[PN] = NextPHI; 7772 7773 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7774 7775 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7776 // cease to be able to evaluate one of them or if they stop evolving, 7777 // because that doesn't necessarily prevent us from computing PN. 7778 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7779 for (const auto &I : CurrentIterVals) { 7780 PHINode *PHI = dyn_cast<PHINode>(I.first); 7781 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7782 PHIsToCompute.emplace_back(PHI, I.second); 7783 } 7784 // We use two distinct loops because EvaluateExpression may invalidate any 7785 // iterators into CurrentIterVals. 7786 for (const auto &I : PHIsToCompute) { 7787 PHINode *PHI = I.first; 7788 Constant *&NextPHI = NextIterVals[PHI]; 7789 if (!NextPHI) { // Not already computed. 7790 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7791 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7792 } 7793 if (NextPHI != I.second) 7794 StoppedEvolving = false; 7795 } 7796 7797 // If all entries in CurrentIterVals == NextIterVals then we can stop 7798 // iterating, the loop can't continue to change. 7799 if (StoppedEvolving) 7800 return RetVal = CurrentIterVals[PN]; 7801 7802 CurrentIterVals.swap(NextIterVals); 7803 } 7804 } 7805 7806 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7807 Value *Cond, 7808 bool ExitWhen) { 7809 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7810 if (!PN) return getCouldNotCompute(); 7811 7812 // If the loop is canonicalized, the PHI will have exactly two entries. 7813 // That's the only form we support here. 7814 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7815 7816 DenseMap<Instruction *, Constant *> CurrentIterVals; 7817 BasicBlock *Header = L->getHeader(); 7818 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7819 7820 BasicBlock *Latch = L->getLoopLatch(); 7821 assert(Latch && "Should follow from NumIncomingValues == 2!"); 7822 7823 for (PHINode &PHI : Header->phis()) { 7824 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7825 CurrentIterVals[&PHI] = StartCST; 7826 } 7827 if (!CurrentIterVals.count(PN)) 7828 return getCouldNotCompute(); 7829 7830 // Okay, we find a PHI node that defines the trip count of this loop. Execute 7831 // the loop symbolically to determine when the condition gets a value of 7832 // "ExitWhen". 7833 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 7834 const DataLayout &DL = getDataLayout(); 7835 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 7836 auto *CondVal = dyn_cast_or_null<ConstantInt>( 7837 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 7838 7839 // Couldn't symbolically evaluate. 7840 if (!CondVal) return getCouldNotCompute(); 7841 7842 if (CondVal->getValue() == uint64_t(ExitWhen)) { 7843 ++NumBruteForceTripCountsComputed; 7844 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 7845 } 7846 7847 // Update all the PHI nodes for the next iteration. 7848 DenseMap<Instruction *, Constant *> NextIterVals; 7849 7850 // Create a list of which PHIs we need to compute. We want to do this before 7851 // calling EvaluateExpression on them because that may invalidate iterators 7852 // into CurrentIterVals. 7853 SmallVector<PHINode *, 8> PHIsToCompute; 7854 for (const auto &I : CurrentIterVals) { 7855 PHINode *PHI = dyn_cast<PHINode>(I.first); 7856 if (!PHI || PHI->getParent() != Header) continue; 7857 PHIsToCompute.push_back(PHI); 7858 } 7859 for (PHINode *PHI : PHIsToCompute) { 7860 Constant *&NextPHI = NextIterVals[PHI]; 7861 if (NextPHI) continue; // Already computed! 7862 7863 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7864 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7865 } 7866 CurrentIterVals.swap(NextIterVals); 7867 } 7868 7869 // Too many iterations were needed to evaluate. 7870 return getCouldNotCompute(); 7871 } 7872 7873 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 7874 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 7875 ValuesAtScopes[V]; 7876 // Check to see if we've folded this expression at this loop before. 7877 for (auto &LS : Values) 7878 if (LS.first == L) 7879 return LS.second ? LS.second : V; 7880 7881 Values.emplace_back(L, nullptr); 7882 7883 // Otherwise compute it. 7884 const SCEV *C = computeSCEVAtScope(V, L); 7885 for (auto &LS : reverse(ValuesAtScopes[V])) 7886 if (LS.first == L) { 7887 LS.second = C; 7888 break; 7889 } 7890 return C; 7891 } 7892 7893 /// This builds up a Constant using the ConstantExpr interface. That way, we 7894 /// will return Constants for objects which aren't represented by a 7895 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 7896 /// Returns NULL if the SCEV isn't representable as a Constant. 7897 static Constant *BuildConstantFromSCEV(const SCEV *V) { 7898 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 7899 case scCouldNotCompute: 7900 case scAddRecExpr: 7901 break; 7902 case scConstant: 7903 return cast<SCEVConstant>(V)->getValue(); 7904 case scUnknown: 7905 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 7906 case scSignExtend: { 7907 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 7908 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 7909 return ConstantExpr::getSExt(CastOp, SS->getType()); 7910 break; 7911 } 7912 case scZeroExtend: { 7913 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 7914 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 7915 return ConstantExpr::getZExt(CastOp, SZ->getType()); 7916 break; 7917 } 7918 case scTruncate: { 7919 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 7920 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 7921 return ConstantExpr::getTrunc(CastOp, ST->getType()); 7922 break; 7923 } 7924 case scAddExpr: { 7925 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 7926 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 7927 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7928 unsigned AS = PTy->getAddressSpace(); 7929 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7930 C = ConstantExpr::getBitCast(C, DestPtrTy); 7931 } 7932 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 7933 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 7934 if (!C2) return nullptr; 7935 7936 // First pointer! 7937 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 7938 unsigned AS = C2->getType()->getPointerAddressSpace(); 7939 std::swap(C, C2); 7940 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 7941 // The offsets have been converted to bytes. We can add bytes to an 7942 // i8* by GEP with the byte count in the first index. 7943 C = ConstantExpr::getBitCast(C, DestPtrTy); 7944 } 7945 7946 // Don't bother trying to sum two pointers. We probably can't 7947 // statically compute a load that results from it anyway. 7948 if (C2->getType()->isPointerTy()) 7949 return nullptr; 7950 7951 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 7952 if (PTy->getElementType()->isStructTy()) 7953 C2 = ConstantExpr::getIntegerCast( 7954 C2, Type::getInt32Ty(C->getContext()), true); 7955 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 7956 } else 7957 C = ConstantExpr::getAdd(C, C2); 7958 } 7959 return C; 7960 } 7961 break; 7962 } 7963 case scMulExpr: { 7964 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 7965 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 7966 // Don't bother with pointers at all. 7967 if (C->getType()->isPointerTy()) return nullptr; 7968 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 7969 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 7970 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 7971 C = ConstantExpr::getMul(C, C2); 7972 } 7973 return C; 7974 } 7975 break; 7976 } 7977 case scUDivExpr: { 7978 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 7979 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 7980 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 7981 if (LHS->getType() == RHS->getType()) 7982 return ConstantExpr::getUDiv(LHS, RHS); 7983 break; 7984 } 7985 case scSMaxExpr: 7986 case scUMaxExpr: 7987 case scSMinExpr: 7988 case scUMinExpr: 7989 break; // TODO: smax, umax, smin, umax. 7990 } 7991 return nullptr; 7992 } 7993 7994 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 7995 if (isa<SCEVConstant>(V)) return V; 7996 7997 // If this instruction is evolved from a constant-evolving PHI, compute the 7998 // exit value from the loop without using SCEVs. 7999 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8000 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8001 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8002 const Loop *LI = this->LI[I->getParent()]; 8003 // Looking for loop exit value. 8004 if (LI && LI->getParentLoop() == L && 8005 PN->getParent() == LI->getHeader()) { 8006 // Okay, there is no closed form solution for the PHI node. Check 8007 // to see if the loop that contains it has a known backedge-taken 8008 // count. If so, we may be able to force computation of the exit 8009 // value. 8010 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8011 // This trivial case can show up in some degenerate cases where 8012 // the incoming IR has not yet been fully simplified. 8013 if (BackedgeTakenCount->isZero()) { 8014 Value *InitValue = nullptr; 8015 bool MultipleInitValues = false; 8016 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8017 if (!LI->contains(PN->getIncomingBlock(i))) { 8018 if (!InitValue) 8019 InitValue = PN->getIncomingValue(i); 8020 else if (InitValue != PN->getIncomingValue(i)) { 8021 MultipleInitValues = true; 8022 break; 8023 } 8024 } 8025 } 8026 if (!MultipleInitValues && InitValue) 8027 return getSCEV(InitValue); 8028 } 8029 // Do we have a loop invariant value flowing around the backedge 8030 // for a loop which must execute the backedge? 8031 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8032 isKnownPositive(BackedgeTakenCount) && 8033 PN->getNumIncomingValues() == 2) { 8034 8035 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8036 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8037 if (LI->isLoopInvariant(BackedgeVal)) 8038 return getSCEV(BackedgeVal); 8039 } 8040 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8041 // Okay, we know how many times the containing loop executes. If 8042 // this is a constant evolving PHI node, get the final value at 8043 // the specified iteration number. 8044 Constant *RV = 8045 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8046 if (RV) return getSCEV(RV); 8047 } 8048 } 8049 8050 // If there is a single-input Phi, evaluate it at our scope. If we can 8051 // prove that this replacement does not break LCSSA form, use new value. 8052 if (PN->getNumOperands() == 1) { 8053 const SCEV *Input = getSCEV(PN->getOperand(0)); 8054 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8055 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8056 // for the simplest case just support constants. 8057 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8058 } 8059 } 8060 8061 // Okay, this is an expression that we cannot symbolically evaluate 8062 // into a SCEV. Check to see if it's possible to symbolically evaluate 8063 // the arguments into constants, and if so, try to constant propagate the 8064 // result. This is particularly useful for computing loop exit values. 8065 if (CanConstantFold(I)) { 8066 SmallVector<Constant *, 4> Operands; 8067 bool MadeImprovement = false; 8068 for (Value *Op : I->operands()) { 8069 if (Constant *C = dyn_cast<Constant>(Op)) { 8070 Operands.push_back(C); 8071 continue; 8072 } 8073 8074 // If any of the operands is non-constant and if they are 8075 // non-integer and non-pointer, don't even try to analyze them 8076 // with scev techniques. 8077 if (!isSCEVable(Op->getType())) 8078 return V; 8079 8080 const SCEV *OrigV = getSCEV(Op); 8081 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8082 MadeImprovement |= OrigV != OpV; 8083 8084 Constant *C = BuildConstantFromSCEV(OpV); 8085 if (!C) return V; 8086 if (C->getType() != Op->getType()) 8087 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8088 Op->getType(), 8089 false), 8090 C, Op->getType()); 8091 Operands.push_back(C); 8092 } 8093 8094 // Check to see if getSCEVAtScope actually made an improvement. 8095 if (MadeImprovement) { 8096 Constant *C = nullptr; 8097 const DataLayout &DL = getDataLayout(); 8098 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8099 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8100 Operands[1], DL, &TLI); 8101 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8102 if (!LI->isVolatile()) 8103 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8104 } else 8105 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8106 if (!C) return V; 8107 return getSCEV(C); 8108 } 8109 } 8110 } 8111 8112 // This is some other type of SCEVUnknown, just return it. 8113 return V; 8114 } 8115 8116 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8117 // Avoid performing the look-up in the common case where the specified 8118 // expression has no loop-variant portions. 8119 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8120 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8121 if (OpAtScope != Comm->getOperand(i)) { 8122 // Okay, at least one of these operands is loop variant but might be 8123 // foldable. Build a new instance of the folded commutative expression. 8124 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8125 Comm->op_begin()+i); 8126 NewOps.push_back(OpAtScope); 8127 8128 for (++i; i != e; ++i) { 8129 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8130 NewOps.push_back(OpAtScope); 8131 } 8132 if (isa<SCEVAddExpr>(Comm)) 8133 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8134 if (isa<SCEVMulExpr>(Comm)) 8135 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8136 if (isa<SCEVMinMaxExpr>(Comm)) 8137 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8138 llvm_unreachable("Unknown commutative SCEV type!"); 8139 } 8140 } 8141 // If we got here, all operands are loop invariant. 8142 return Comm; 8143 } 8144 8145 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8146 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8147 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8148 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8149 return Div; // must be loop invariant 8150 return getUDivExpr(LHS, RHS); 8151 } 8152 8153 // If this is a loop recurrence for a loop that does not contain L, then we 8154 // are dealing with the final value computed by the loop. 8155 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8156 // First, attempt to evaluate each operand. 8157 // Avoid performing the look-up in the common case where the specified 8158 // expression has no loop-variant portions. 8159 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8160 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8161 if (OpAtScope == AddRec->getOperand(i)) 8162 continue; 8163 8164 // Okay, at least one of these operands is loop variant but might be 8165 // foldable. Build a new instance of the folded commutative expression. 8166 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8167 AddRec->op_begin()+i); 8168 NewOps.push_back(OpAtScope); 8169 for (++i; i != e; ++i) 8170 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8171 8172 const SCEV *FoldedRec = 8173 getAddRecExpr(NewOps, AddRec->getLoop(), 8174 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8175 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8176 // The addrec may be folded to a nonrecurrence, for example, if the 8177 // induction variable is multiplied by zero after constant folding. Go 8178 // ahead and return the folded value. 8179 if (!AddRec) 8180 return FoldedRec; 8181 break; 8182 } 8183 8184 // If the scope is outside the addrec's loop, evaluate it by using the 8185 // loop exit value of the addrec. 8186 if (!AddRec->getLoop()->contains(L)) { 8187 // To evaluate this recurrence, we need to know how many times the AddRec 8188 // loop iterates. Compute this now. 8189 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8190 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8191 8192 // Then, evaluate the AddRec. 8193 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8194 } 8195 8196 return AddRec; 8197 } 8198 8199 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8200 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8201 if (Op == Cast->getOperand()) 8202 return Cast; // must be loop invariant 8203 return getZeroExtendExpr(Op, Cast->getType()); 8204 } 8205 8206 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8207 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8208 if (Op == Cast->getOperand()) 8209 return Cast; // must be loop invariant 8210 return getSignExtendExpr(Op, Cast->getType()); 8211 } 8212 8213 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8214 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8215 if (Op == Cast->getOperand()) 8216 return Cast; // must be loop invariant 8217 return getTruncateExpr(Op, Cast->getType()); 8218 } 8219 8220 llvm_unreachable("Unknown SCEV type!"); 8221 } 8222 8223 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8224 return getSCEVAtScope(getSCEV(V), L); 8225 } 8226 8227 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8228 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8229 return stripInjectiveFunctions(ZExt->getOperand()); 8230 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8231 return stripInjectiveFunctions(SExt->getOperand()); 8232 return S; 8233 } 8234 8235 /// Finds the minimum unsigned root of the following equation: 8236 /// 8237 /// A * X = B (mod N) 8238 /// 8239 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8240 /// A and B isn't important. 8241 /// 8242 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8243 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8244 ScalarEvolution &SE) { 8245 uint32_t BW = A.getBitWidth(); 8246 assert(BW == SE.getTypeSizeInBits(B->getType())); 8247 assert(A != 0 && "A must be non-zero."); 8248 8249 // 1. D = gcd(A, N) 8250 // 8251 // The gcd of A and N may have only one prime factor: 2. The number of 8252 // trailing zeros in A is its multiplicity 8253 uint32_t Mult2 = A.countTrailingZeros(); 8254 // D = 2^Mult2 8255 8256 // 2. Check if B is divisible by D. 8257 // 8258 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8259 // is not less than multiplicity of this prime factor for D. 8260 if (SE.GetMinTrailingZeros(B) < Mult2) 8261 return SE.getCouldNotCompute(); 8262 8263 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8264 // modulo (N / D). 8265 // 8266 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8267 // (N / D) in general. The inverse itself always fits into BW bits, though, 8268 // so we immediately truncate it. 8269 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8270 APInt Mod(BW + 1, 0); 8271 Mod.setBit(BW - Mult2); // Mod = N / D 8272 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8273 8274 // 4. Compute the minimum unsigned root of the equation: 8275 // I * (B / D) mod (N / D) 8276 // To simplify the computation, we factor out the divide by D: 8277 // (I * B mod N) / D 8278 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8279 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8280 } 8281 8282 /// For a given quadratic addrec, generate coefficients of the corresponding 8283 /// quadratic equation, multiplied by a common value to ensure that they are 8284 /// integers. 8285 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8286 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8287 /// were multiplied by, and BitWidth is the bit width of the original addrec 8288 /// coefficients. 8289 /// This function returns None if the addrec coefficients are not compile- 8290 /// time constants. 8291 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8292 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8293 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8294 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8295 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8296 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8297 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8298 << *AddRec << '\n'); 8299 8300 // We currently can only solve this if the coefficients are constants. 8301 if (!LC || !MC || !NC) { 8302 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8303 return None; 8304 } 8305 8306 APInt L = LC->getAPInt(); 8307 APInt M = MC->getAPInt(); 8308 APInt N = NC->getAPInt(); 8309 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8310 8311 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8312 unsigned NewWidth = BitWidth + 1; 8313 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8314 << BitWidth << '\n'); 8315 // The sign-extension (as opposed to a zero-extension) here matches the 8316 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8317 N = N.sext(NewWidth); 8318 M = M.sext(NewWidth); 8319 L = L.sext(NewWidth); 8320 8321 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8322 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8323 // L+M, L+2M+N, L+3M+3N, ... 8324 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8325 // 8326 // The equation Acc = 0 is then 8327 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8328 // In a quadratic form it becomes: 8329 // N n^2 + (2M-N) n + 2L = 0. 8330 8331 APInt A = N; 8332 APInt B = 2 * M - A; 8333 APInt C = 2 * L; 8334 APInt T = APInt(NewWidth, 2); 8335 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8336 << "x + " << C << ", coeff bw: " << NewWidth 8337 << ", multiplied by " << T << '\n'); 8338 return std::make_tuple(A, B, C, T, BitWidth); 8339 } 8340 8341 /// Helper function to compare optional APInts: 8342 /// (a) if X and Y both exist, return min(X, Y), 8343 /// (b) if neither X nor Y exist, return None, 8344 /// (c) if exactly one of X and Y exists, return that value. 8345 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8346 if (X.hasValue() && Y.hasValue()) { 8347 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8348 APInt XW = X->sextOrSelf(W); 8349 APInt YW = Y->sextOrSelf(W); 8350 return XW.slt(YW) ? *X : *Y; 8351 } 8352 if (!X.hasValue() && !Y.hasValue()) 8353 return None; 8354 return X.hasValue() ? *X : *Y; 8355 } 8356 8357 /// Helper function to truncate an optional APInt to a given BitWidth. 8358 /// When solving addrec-related equations, it is preferable to return a value 8359 /// that has the same bit width as the original addrec's coefficients. If the 8360 /// solution fits in the original bit width, truncate it (except for i1). 8361 /// Returning a value of a different bit width may inhibit some optimizations. 8362 /// 8363 /// In general, a solution to a quadratic equation generated from an addrec 8364 /// may require BW+1 bits, where BW is the bit width of the addrec's 8365 /// coefficients. The reason is that the coefficients of the quadratic 8366 /// equation are BW+1 bits wide (to avoid truncation when converting from 8367 /// the addrec to the equation). 8368 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8369 if (!X.hasValue()) 8370 return None; 8371 unsigned W = X->getBitWidth(); 8372 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8373 return X->trunc(BitWidth); 8374 return X; 8375 } 8376 8377 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8378 /// iterations. The values L, M, N are assumed to be signed, and they 8379 /// should all have the same bit widths. 8380 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8381 /// where BW is the bit width of the addrec's coefficients. 8382 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8383 /// returned as such, otherwise the bit width of the returned value may 8384 /// be greater than BW. 8385 /// 8386 /// This function returns None if 8387 /// (a) the addrec coefficients are not constant, or 8388 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8389 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8390 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8391 static Optional<APInt> 8392 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8393 APInt A, B, C, M; 8394 unsigned BitWidth; 8395 auto T = GetQuadraticEquation(AddRec); 8396 if (!T.hasValue()) 8397 return None; 8398 8399 std::tie(A, B, C, M, BitWidth) = *T; 8400 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8401 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8402 if (!X.hasValue()) 8403 return None; 8404 8405 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8406 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8407 if (!V->isZero()) 8408 return None; 8409 8410 return TruncIfPossible(X, BitWidth); 8411 } 8412 8413 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8414 /// iterations. The values M, N are assumed to be signed, and they 8415 /// should all have the same bit widths. 8416 /// Find the least n such that c(n) does not belong to the given range, 8417 /// while c(n-1) does. 8418 /// 8419 /// This function returns None if 8420 /// (a) the addrec coefficients are not constant, or 8421 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8422 /// bounds of the range. 8423 static Optional<APInt> 8424 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8425 const ConstantRange &Range, ScalarEvolution &SE) { 8426 assert(AddRec->getOperand(0)->isZero() && 8427 "Starting value of addrec should be 0"); 8428 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8429 << Range << ", addrec " << *AddRec << '\n'); 8430 // This case is handled in getNumIterationsInRange. Here we can assume that 8431 // we start in the range. 8432 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8433 "Addrec's initial value should be in range"); 8434 8435 APInt A, B, C, M; 8436 unsigned BitWidth; 8437 auto T = GetQuadraticEquation(AddRec); 8438 if (!T.hasValue()) 8439 return None; 8440 8441 // Be careful about the return value: there can be two reasons for not 8442 // returning an actual number. First, if no solutions to the equations 8443 // were found, and second, if the solutions don't leave the given range. 8444 // The first case means that the actual solution is "unknown", the second 8445 // means that it's known, but not valid. If the solution is unknown, we 8446 // cannot make any conclusions. 8447 // Return a pair: the optional solution and a flag indicating if the 8448 // solution was found. 8449 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8450 // Solve for signed overflow and unsigned overflow, pick the lower 8451 // solution. 8452 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8453 << Bound << " (before multiplying by " << M << ")\n"); 8454 Bound *= M; // The quadratic equation multiplier. 8455 8456 Optional<APInt> SO = None; 8457 if (BitWidth > 1) { 8458 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8459 "signed overflow\n"); 8460 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8461 } 8462 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8463 "unsigned overflow\n"); 8464 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8465 BitWidth+1); 8466 8467 auto LeavesRange = [&] (const APInt &X) { 8468 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8469 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8470 if (Range.contains(V0->getValue())) 8471 return false; 8472 // X should be at least 1, so X-1 is non-negative. 8473 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8474 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8475 if (Range.contains(V1->getValue())) 8476 return true; 8477 return false; 8478 }; 8479 8480 // If SolveQuadraticEquationWrap returns None, it means that there can 8481 // be a solution, but the function failed to find it. We cannot treat it 8482 // as "no solution". 8483 if (!SO.hasValue() || !UO.hasValue()) 8484 return { None, false }; 8485 8486 // Check the smaller value first to see if it leaves the range. 8487 // At this point, both SO and UO must have values. 8488 Optional<APInt> Min = MinOptional(SO, UO); 8489 if (LeavesRange(*Min)) 8490 return { Min, true }; 8491 Optional<APInt> Max = Min == SO ? UO : SO; 8492 if (LeavesRange(*Max)) 8493 return { Max, true }; 8494 8495 // Solutions were found, but were eliminated, hence the "true". 8496 return { None, true }; 8497 }; 8498 8499 std::tie(A, B, C, M, BitWidth) = *T; 8500 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8501 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8502 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8503 auto SL = SolveForBoundary(Lower); 8504 auto SU = SolveForBoundary(Upper); 8505 // If any of the solutions was unknown, no meaninigful conclusions can 8506 // be made. 8507 if (!SL.second || !SU.second) 8508 return None; 8509 8510 // Claim: The correct solution is not some value between Min and Max. 8511 // 8512 // Justification: Assuming that Min and Max are different values, one of 8513 // them is when the first signed overflow happens, the other is when the 8514 // first unsigned overflow happens. Crossing the range boundary is only 8515 // possible via an overflow (treating 0 as a special case of it, modeling 8516 // an overflow as crossing k*2^W for some k). 8517 // 8518 // The interesting case here is when Min was eliminated as an invalid 8519 // solution, but Max was not. The argument is that if there was another 8520 // overflow between Min and Max, it would also have been eliminated if 8521 // it was considered. 8522 // 8523 // For a given boundary, it is possible to have two overflows of the same 8524 // type (signed/unsigned) without having the other type in between: this 8525 // can happen when the vertex of the parabola is between the iterations 8526 // corresponding to the overflows. This is only possible when the two 8527 // overflows cross k*2^W for the same k. In such case, if the second one 8528 // left the range (and was the first one to do so), the first overflow 8529 // would have to enter the range, which would mean that either we had left 8530 // the range before or that we started outside of it. Both of these cases 8531 // are contradictions. 8532 // 8533 // Claim: In the case where SolveForBoundary returns None, the correct 8534 // solution is not some value between the Max for this boundary and the 8535 // Min of the other boundary. 8536 // 8537 // Justification: Assume that we had such Max_A and Min_B corresponding 8538 // to range boundaries A and B and such that Max_A < Min_B. If there was 8539 // a solution between Max_A and Min_B, it would have to be caused by an 8540 // overflow corresponding to either A or B. It cannot correspond to B, 8541 // since Min_B is the first occurrence of such an overflow. If it 8542 // corresponded to A, it would have to be either a signed or an unsigned 8543 // overflow that is larger than both eliminated overflows for A. But 8544 // between the eliminated overflows and this overflow, the values would 8545 // cover the entire value space, thus crossing the other boundary, which 8546 // is a contradiction. 8547 8548 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8549 } 8550 8551 ScalarEvolution::ExitLimit 8552 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8553 bool AllowPredicates) { 8554 8555 // This is only used for loops with a "x != y" exit test. The exit condition 8556 // is now expressed as a single expression, V = x-y. So the exit test is 8557 // effectively V != 0. We know and take advantage of the fact that this 8558 // expression only being used in a comparison by zero context. 8559 8560 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8561 // If the value is a constant 8562 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8563 // If the value is already zero, the branch will execute zero times. 8564 if (C->getValue()->isZero()) return C; 8565 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8566 } 8567 8568 const SCEVAddRecExpr *AddRec = 8569 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8570 8571 if (!AddRec && AllowPredicates) 8572 // Try to make this an AddRec using runtime tests, in the first X 8573 // iterations of this loop, where X is the SCEV expression found by the 8574 // algorithm below. 8575 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8576 8577 if (!AddRec || AddRec->getLoop() != L) 8578 return getCouldNotCompute(); 8579 8580 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8581 // the quadratic equation to solve it. 8582 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8583 // We can only use this value if the chrec ends up with an exact zero 8584 // value at this index. When solving for "X*X != 5", for example, we 8585 // should not accept a root of 2. 8586 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8587 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8588 return ExitLimit(R, R, false, Predicates); 8589 } 8590 return getCouldNotCompute(); 8591 } 8592 8593 // Otherwise we can only handle this if it is affine. 8594 if (!AddRec->isAffine()) 8595 return getCouldNotCompute(); 8596 8597 // If this is an affine expression, the execution count of this branch is 8598 // the minimum unsigned root of the following equation: 8599 // 8600 // Start + Step*N = 0 (mod 2^BW) 8601 // 8602 // equivalent to: 8603 // 8604 // Step*N = -Start (mod 2^BW) 8605 // 8606 // where BW is the common bit width of Start and Step. 8607 8608 // Get the initial value for the loop. 8609 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8610 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8611 8612 // For now we handle only constant steps. 8613 // 8614 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8615 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8616 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8617 // We have not yet seen any such cases. 8618 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8619 if (!StepC || StepC->getValue()->isZero()) 8620 return getCouldNotCompute(); 8621 8622 // For positive steps (counting up until unsigned overflow): 8623 // N = -Start/Step (as unsigned) 8624 // For negative steps (counting down to zero): 8625 // N = Start/-Step 8626 // First compute the unsigned distance from zero in the direction of Step. 8627 bool CountDown = StepC->getAPInt().isNegative(); 8628 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8629 8630 // Handle unitary steps, which cannot wraparound. 8631 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8632 // N = Distance (as unsigned) 8633 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8634 APInt MaxBECount = getUnsignedRangeMax(Distance); 8635 8636 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8637 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8638 // case, and see if we can improve the bound. 8639 // 8640 // Explicitly handling this here is necessary because getUnsignedRange 8641 // isn't context-sensitive; it doesn't know that we only care about the 8642 // range inside the loop. 8643 const SCEV *Zero = getZero(Distance->getType()); 8644 const SCEV *One = getOne(Distance->getType()); 8645 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8646 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8647 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8648 // as "unsigned_max(Distance + 1) - 1". 8649 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8650 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8651 } 8652 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8653 } 8654 8655 // If the condition controls loop exit (the loop exits only if the expression 8656 // is true) and the addition is no-wrap we can use unsigned divide to 8657 // compute the backedge count. In this case, the step may not divide the 8658 // distance, but we don't care because if the condition is "missed" the loop 8659 // will have undefined behavior due to wrapping. 8660 if (ControlsExit && AddRec->hasNoSelfWrap() && 8661 loopHasNoAbnormalExits(AddRec->getLoop())) { 8662 const SCEV *Exact = 8663 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8664 const SCEV *Max = 8665 Exact == getCouldNotCompute() 8666 ? Exact 8667 : getConstant(getUnsignedRangeMax(Exact)); 8668 return ExitLimit(Exact, Max, false, Predicates); 8669 } 8670 8671 // Solve the general equation. 8672 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8673 getNegativeSCEV(Start), *this); 8674 const SCEV *M = E == getCouldNotCompute() 8675 ? E 8676 : getConstant(getUnsignedRangeMax(E)); 8677 return ExitLimit(E, M, false, Predicates); 8678 } 8679 8680 ScalarEvolution::ExitLimit 8681 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8682 // Loops that look like: while (X == 0) are very strange indeed. We don't 8683 // handle them yet except for the trivial case. This could be expanded in the 8684 // future as needed. 8685 8686 // If the value is a constant, check to see if it is known to be non-zero 8687 // already. If so, the backedge will execute zero times. 8688 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8689 if (!C->getValue()->isZero()) 8690 return getZero(C->getType()); 8691 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8692 } 8693 8694 // We could implement others, but I really doubt anyone writes loops like 8695 // this, and if they did, they would already be constant folded. 8696 return getCouldNotCompute(); 8697 } 8698 8699 std::pair<BasicBlock *, BasicBlock *> 8700 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8701 // If the block has a unique predecessor, then there is no path from the 8702 // predecessor to the block that does not go through the direct edge 8703 // from the predecessor to the block. 8704 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8705 return {Pred, BB}; 8706 8707 // A loop's header is defined to be a block that dominates the loop. 8708 // If the header has a unique predecessor outside the loop, it must be 8709 // a block that has exactly one successor that can reach the loop. 8710 if (Loop *L = LI.getLoopFor(BB)) 8711 return {L->getLoopPredecessor(), L->getHeader()}; 8712 8713 return {nullptr, nullptr}; 8714 } 8715 8716 /// SCEV structural equivalence is usually sufficient for testing whether two 8717 /// expressions are equal, however for the purposes of looking for a condition 8718 /// guarding a loop, it can be useful to be a little more general, since a 8719 /// front-end may have replicated the controlling expression. 8720 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8721 // Quick check to see if they are the same SCEV. 8722 if (A == B) return true; 8723 8724 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8725 // Not all instructions that are "identical" compute the same value. For 8726 // instance, two distinct alloca instructions allocating the same type are 8727 // identical and do not read memory; but compute distinct values. 8728 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8729 }; 8730 8731 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8732 // two different instructions with the same value. Check for this case. 8733 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8734 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8735 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8736 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8737 if (ComputesEqualValues(AI, BI)) 8738 return true; 8739 8740 // Otherwise assume they may have a different value. 8741 return false; 8742 } 8743 8744 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8745 const SCEV *&LHS, const SCEV *&RHS, 8746 unsigned Depth) { 8747 bool Changed = false; 8748 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8749 // '0 != 0'. 8750 auto TrivialCase = [&](bool TriviallyTrue) { 8751 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8752 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8753 return true; 8754 }; 8755 // If we hit the max recursion limit bail out. 8756 if (Depth >= 3) 8757 return false; 8758 8759 // Canonicalize a constant to the right side. 8760 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8761 // Check for both operands constant. 8762 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8763 if (ConstantExpr::getICmp(Pred, 8764 LHSC->getValue(), 8765 RHSC->getValue())->isNullValue()) 8766 return TrivialCase(false); 8767 else 8768 return TrivialCase(true); 8769 } 8770 // Otherwise swap the operands to put the constant on the right. 8771 std::swap(LHS, RHS); 8772 Pred = ICmpInst::getSwappedPredicate(Pred); 8773 Changed = true; 8774 } 8775 8776 // If we're comparing an addrec with a value which is loop-invariant in the 8777 // addrec's loop, put the addrec on the left. Also make a dominance check, 8778 // as both operands could be addrecs loop-invariant in each other's loop. 8779 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8780 const Loop *L = AR->getLoop(); 8781 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8782 std::swap(LHS, RHS); 8783 Pred = ICmpInst::getSwappedPredicate(Pred); 8784 Changed = true; 8785 } 8786 } 8787 8788 // If there's a constant operand, canonicalize comparisons with boundary 8789 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8790 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8791 const APInt &RA = RC->getAPInt(); 8792 8793 bool SimplifiedByConstantRange = false; 8794 8795 if (!ICmpInst::isEquality(Pred)) { 8796 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8797 if (ExactCR.isFullSet()) 8798 return TrivialCase(true); 8799 else if (ExactCR.isEmptySet()) 8800 return TrivialCase(false); 8801 8802 APInt NewRHS; 8803 CmpInst::Predicate NewPred; 8804 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8805 ICmpInst::isEquality(NewPred)) { 8806 // We were able to convert an inequality to an equality. 8807 Pred = NewPred; 8808 RHS = getConstant(NewRHS); 8809 Changed = SimplifiedByConstantRange = true; 8810 } 8811 } 8812 8813 if (!SimplifiedByConstantRange) { 8814 switch (Pred) { 8815 default: 8816 break; 8817 case ICmpInst::ICMP_EQ: 8818 case ICmpInst::ICMP_NE: 8819 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8820 if (!RA) 8821 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 8822 if (const SCEVMulExpr *ME = 8823 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 8824 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 8825 ME->getOperand(0)->isAllOnesValue()) { 8826 RHS = AE->getOperand(1); 8827 LHS = ME->getOperand(1); 8828 Changed = true; 8829 } 8830 break; 8831 8832 8833 // The "Should have been caught earlier!" messages refer to the fact 8834 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 8835 // should have fired on the corresponding cases, and canonicalized the 8836 // check to trivial case. 8837 8838 case ICmpInst::ICMP_UGE: 8839 assert(!RA.isMinValue() && "Should have been caught earlier!"); 8840 Pred = ICmpInst::ICMP_UGT; 8841 RHS = getConstant(RA - 1); 8842 Changed = true; 8843 break; 8844 case ICmpInst::ICMP_ULE: 8845 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 8846 Pred = ICmpInst::ICMP_ULT; 8847 RHS = getConstant(RA + 1); 8848 Changed = true; 8849 break; 8850 case ICmpInst::ICMP_SGE: 8851 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 8852 Pred = ICmpInst::ICMP_SGT; 8853 RHS = getConstant(RA - 1); 8854 Changed = true; 8855 break; 8856 case ICmpInst::ICMP_SLE: 8857 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 8858 Pred = ICmpInst::ICMP_SLT; 8859 RHS = getConstant(RA + 1); 8860 Changed = true; 8861 break; 8862 } 8863 } 8864 } 8865 8866 // Check for obvious equality. 8867 if (HasSameValue(LHS, RHS)) { 8868 if (ICmpInst::isTrueWhenEqual(Pred)) 8869 return TrivialCase(true); 8870 if (ICmpInst::isFalseWhenEqual(Pred)) 8871 return TrivialCase(false); 8872 } 8873 8874 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 8875 // adding or subtracting 1 from one of the operands. 8876 switch (Pred) { 8877 case ICmpInst::ICMP_SLE: 8878 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 8879 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8880 SCEV::FlagNSW); 8881 Pred = ICmpInst::ICMP_SLT; 8882 Changed = true; 8883 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 8884 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 8885 SCEV::FlagNSW); 8886 Pred = ICmpInst::ICMP_SLT; 8887 Changed = true; 8888 } 8889 break; 8890 case ICmpInst::ICMP_SGE: 8891 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 8892 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 8893 SCEV::FlagNSW); 8894 Pred = ICmpInst::ICMP_SGT; 8895 Changed = true; 8896 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 8897 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8898 SCEV::FlagNSW); 8899 Pred = ICmpInst::ICMP_SGT; 8900 Changed = true; 8901 } 8902 break; 8903 case ICmpInst::ICMP_ULE: 8904 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 8905 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 8906 SCEV::FlagNUW); 8907 Pred = ICmpInst::ICMP_ULT; 8908 Changed = true; 8909 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 8910 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 8911 Pred = ICmpInst::ICMP_ULT; 8912 Changed = true; 8913 } 8914 break; 8915 case ICmpInst::ICMP_UGE: 8916 if (!getUnsignedRangeMin(RHS).isMinValue()) { 8917 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 8918 Pred = ICmpInst::ICMP_UGT; 8919 Changed = true; 8920 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 8921 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 8922 SCEV::FlagNUW); 8923 Pred = ICmpInst::ICMP_UGT; 8924 Changed = true; 8925 } 8926 break; 8927 default: 8928 break; 8929 } 8930 8931 // TODO: More simplifications are possible here. 8932 8933 // Recursively simplify until we either hit a recursion limit or nothing 8934 // changes. 8935 if (Changed) 8936 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 8937 8938 return Changed; 8939 } 8940 8941 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 8942 return getSignedRangeMax(S).isNegative(); 8943 } 8944 8945 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 8946 return getSignedRangeMin(S).isStrictlyPositive(); 8947 } 8948 8949 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 8950 return !getSignedRangeMin(S).isNegative(); 8951 } 8952 8953 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 8954 return !getSignedRangeMax(S).isStrictlyPositive(); 8955 } 8956 8957 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 8958 return isKnownNegative(S) || isKnownPositive(S); 8959 } 8960 8961 std::pair<const SCEV *, const SCEV *> 8962 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 8963 // Compute SCEV on entry of loop L. 8964 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 8965 if (Start == getCouldNotCompute()) 8966 return { Start, Start }; 8967 // Compute post increment SCEV for loop L. 8968 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 8969 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 8970 return { Start, PostInc }; 8971 } 8972 8973 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 8974 const SCEV *LHS, const SCEV *RHS) { 8975 // First collect all loops. 8976 SmallPtrSet<const Loop *, 8> LoopsUsed; 8977 getUsedLoops(LHS, LoopsUsed); 8978 getUsedLoops(RHS, LoopsUsed); 8979 8980 if (LoopsUsed.empty()) 8981 return false; 8982 8983 // Domination relationship must be a linear order on collected loops. 8984 #ifndef NDEBUG 8985 for (auto *L1 : LoopsUsed) 8986 for (auto *L2 : LoopsUsed) 8987 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 8988 DT.dominates(L2->getHeader(), L1->getHeader())) && 8989 "Domination relationship is not a linear order"); 8990 #endif 8991 8992 const Loop *MDL = 8993 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 8994 [&](const Loop *L1, const Loop *L2) { 8995 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 8996 }); 8997 8998 // Get init and post increment value for LHS. 8999 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9000 // if LHS contains unknown non-invariant SCEV then bail out. 9001 if (SplitLHS.first == getCouldNotCompute()) 9002 return false; 9003 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9004 // Get init and post increment value for RHS. 9005 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9006 // if RHS contains unknown non-invariant SCEV then bail out. 9007 if (SplitRHS.first == getCouldNotCompute()) 9008 return false; 9009 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9010 // It is possible that init SCEV contains an invariant load but it does 9011 // not dominate MDL and is not available at MDL loop entry, so we should 9012 // check it here. 9013 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9014 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9015 return false; 9016 9017 // It seems backedge guard check is faster than entry one so in some cases 9018 // it can speed up whole estimation by short circuit 9019 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9020 SplitRHS.second) && 9021 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9022 } 9023 9024 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9025 const SCEV *LHS, const SCEV *RHS) { 9026 // Canonicalize the inputs first. 9027 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9028 9029 if (isKnownViaInduction(Pred, LHS, RHS)) 9030 return true; 9031 9032 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9033 return true; 9034 9035 // Otherwise see what can be done with some simple reasoning. 9036 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9037 } 9038 9039 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9040 const SCEVAddRecExpr *LHS, 9041 const SCEV *RHS) { 9042 const Loop *L = LHS->getLoop(); 9043 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9044 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9045 } 9046 9047 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9048 ICmpInst::Predicate Pred, 9049 bool &Increasing) { 9050 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9051 9052 #ifndef NDEBUG 9053 // Verify an invariant: inverting the predicate should turn a monotonically 9054 // increasing change to a monotonically decreasing one, and vice versa. 9055 bool IncreasingSwapped; 9056 bool ResultSwapped = isMonotonicPredicateImpl( 9057 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9058 9059 assert(Result == ResultSwapped && "should be able to analyze both!"); 9060 if (ResultSwapped) 9061 assert(Increasing == !IncreasingSwapped && 9062 "monotonicity should flip as we flip the predicate"); 9063 #endif 9064 9065 return Result; 9066 } 9067 9068 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9069 ICmpInst::Predicate Pred, 9070 bool &Increasing) { 9071 9072 // A zero step value for LHS means the induction variable is essentially a 9073 // loop invariant value. We don't really depend on the predicate actually 9074 // flipping from false to true (for increasing predicates, and the other way 9075 // around for decreasing predicates), all we care about is that *if* the 9076 // predicate changes then it only changes from false to true. 9077 // 9078 // A zero step value in itself is not very useful, but there may be places 9079 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9080 // as general as possible. 9081 9082 switch (Pred) { 9083 default: 9084 return false; // Conservative answer 9085 9086 case ICmpInst::ICMP_UGT: 9087 case ICmpInst::ICMP_UGE: 9088 case ICmpInst::ICMP_ULT: 9089 case ICmpInst::ICMP_ULE: 9090 if (!LHS->hasNoUnsignedWrap()) 9091 return false; 9092 9093 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9094 return true; 9095 9096 case ICmpInst::ICMP_SGT: 9097 case ICmpInst::ICMP_SGE: 9098 case ICmpInst::ICMP_SLT: 9099 case ICmpInst::ICMP_SLE: { 9100 if (!LHS->hasNoSignedWrap()) 9101 return false; 9102 9103 const SCEV *Step = LHS->getStepRecurrence(*this); 9104 9105 if (isKnownNonNegative(Step)) { 9106 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9107 return true; 9108 } 9109 9110 if (isKnownNonPositive(Step)) { 9111 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9112 return true; 9113 } 9114 9115 return false; 9116 } 9117 9118 } 9119 9120 llvm_unreachable("switch has default clause!"); 9121 } 9122 9123 bool ScalarEvolution::isLoopInvariantPredicate( 9124 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9125 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9126 const SCEV *&InvariantRHS) { 9127 9128 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9129 if (!isLoopInvariant(RHS, L)) { 9130 if (!isLoopInvariant(LHS, L)) 9131 return false; 9132 9133 std::swap(LHS, RHS); 9134 Pred = ICmpInst::getSwappedPredicate(Pred); 9135 } 9136 9137 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9138 if (!ArLHS || ArLHS->getLoop() != L) 9139 return false; 9140 9141 bool Increasing; 9142 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9143 return false; 9144 9145 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9146 // true as the loop iterates, and the backedge is control dependent on 9147 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9148 // 9149 // * if the predicate was false in the first iteration then the predicate 9150 // is never evaluated again, since the loop exits without taking the 9151 // backedge. 9152 // * if the predicate was true in the first iteration then it will 9153 // continue to be true for all future iterations since it is 9154 // monotonically increasing. 9155 // 9156 // For both the above possibilities, we can replace the loop varying 9157 // predicate with its value on the first iteration of the loop (which is 9158 // loop invariant). 9159 // 9160 // A similar reasoning applies for a monotonically decreasing predicate, by 9161 // replacing true with false and false with true in the above two bullets. 9162 9163 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9164 9165 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9166 return false; 9167 9168 InvariantPred = Pred; 9169 InvariantLHS = ArLHS->getStart(); 9170 InvariantRHS = RHS; 9171 return true; 9172 } 9173 9174 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9175 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9176 if (HasSameValue(LHS, RHS)) 9177 return ICmpInst::isTrueWhenEqual(Pred); 9178 9179 // This code is split out from isKnownPredicate because it is called from 9180 // within isLoopEntryGuardedByCond. 9181 9182 auto CheckRanges = 9183 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9184 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9185 .contains(RangeLHS); 9186 }; 9187 9188 // The check at the top of the function catches the case where the values are 9189 // known to be equal. 9190 if (Pred == CmpInst::ICMP_EQ) 9191 return false; 9192 9193 if (Pred == CmpInst::ICMP_NE) 9194 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9195 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9196 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9197 9198 if (CmpInst::isSigned(Pred)) 9199 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9200 9201 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9202 } 9203 9204 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9205 const SCEV *LHS, 9206 const SCEV *RHS) { 9207 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9208 // Return Y via OutY. 9209 auto MatchBinaryAddToConst = 9210 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9211 SCEV::NoWrapFlags ExpectedFlags) { 9212 const SCEV *NonConstOp, *ConstOp; 9213 SCEV::NoWrapFlags FlagsPresent; 9214 9215 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9216 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9217 return false; 9218 9219 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9220 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9221 }; 9222 9223 APInt C; 9224 9225 switch (Pred) { 9226 default: 9227 break; 9228 9229 case ICmpInst::ICMP_SGE: 9230 std::swap(LHS, RHS); 9231 LLVM_FALLTHROUGH; 9232 case ICmpInst::ICMP_SLE: 9233 // X s<= (X + C)<nsw> if C >= 0 9234 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9235 return true; 9236 9237 // (X + C)<nsw> s<= X if C <= 0 9238 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9239 !C.isStrictlyPositive()) 9240 return true; 9241 break; 9242 9243 case ICmpInst::ICMP_SGT: 9244 std::swap(LHS, RHS); 9245 LLVM_FALLTHROUGH; 9246 case ICmpInst::ICMP_SLT: 9247 // X s< (X + C)<nsw> if C > 0 9248 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9249 C.isStrictlyPositive()) 9250 return true; 9251 9252 // (X + C)<nsw> s< X if C < 0 9253 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9254 return true; 9255 break; 9256 } 9257 9258 return false; 9259 } 9260 9261 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9262 const SCEV *LHS, 9263 const SCEV *RHS) { 9264 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9265 return false; 9266 9267 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9268 // the stack can result in exponential time complexity. 9269 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9270 9271 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9272 // 9273 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9274 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9275 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9276 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9277 // use isKnownPredicate later if needed. 9278 return isKnownNonNegative(RHS) && 9279 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9280 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9281 } 9282 9283 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9284 ICmpInst::Predicate Pred, 9285 const SCEV *LHS, const SCEV *RHS) { 9286 // No need to even try if we know the module has no guards. 9287 if (!HasGuards) 9288 return false; 9289 9290 return any_of(*BB, [&](Instruction &I) { 9291 using namespace llvm::PatternMatch; 9292 9293 Value *Condition; 9294 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9295 m_Value(Condition))) && 9296 isImpliedCond(Pred, LHS, RHS, Condition, false); 9297 }); 9298 } 9299 9300 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9301 /// protected by a conditional between LHS and RHS. This is used to 9302 /// to eliminate casts. 9303 bool 9304 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9305 ICmpInst::Predicate Pred, 9306 const SCEV *LHS, const SCEV *RHS) { 9307 // Interpret a null as meaning no loop, where there is obviously no guard 9308 // (interprocedural conditions notwithstanding). 9309 if (!L) return true; 9310 9311 if (VerifyIR) 9312 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9313 "This cannot be done on broken IR!"); 9314 9315 9316 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9317 return true; 9318 9319 BasicBlock *Latch = L->getLoopLatch(); 9320 if (!Latch) 9321 return false; 9322 9323 BranchInst *LoopContinuePredicate = 9324 dyn_cast<BranchInst>(Latch->getTerminator()); 9325 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9326 isImpliedCond(Pred, LHS, RHS, 9327 LoopContinuePredicate->getCondition(), 9328 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9329 return true; 9330 9331 // We don't want more than one activation of the following loops on the stack 9332 // -- that can lead to O(n!) time complexity. 9333 if (WalkingBEDominatingConds) 9334 return false; 9335 9336 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9337 9338 // See if we can exploit a trip count to prove the predicate. 9339 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9340 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9341 if (LatchBECount != getCouldNotCompute()) { 9342 // We know that Latch branches back to the loop header exactly 9343 // LatchBECount times. This means the backdege condition at Latch is 9344 // equivalent to "{0,+,1} u< LatchBECount". 9345 Type *Ty = LatchBECount->getType(); 9346 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9347 const SCEV *LoopCounter = 9348 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9349 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9350 LatchBECount)) 9351 return true; 9352 } 9353 9354 // Check conditions due to any @llvm.assume intrinsics. 9355 for (auto &AssumeVH : AC.assumptions()) { 9356 if (!AssumeVH) 9357 continue; 9358 auto *CI = cast<CallInst>(AssumeVH); 9359 if (!DT.dominates(CI, Latch->getTerminator())) 9360 continue; 9361 9362 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9363 return true; 9364 } 9365 9366 // If the loop is not reachable from the entry block, we risk running into an 9367 // infinite loop as we walk up into the dom tree. These loops do not matter 9368 // anyway, so we just return a conservative answer when we see them. 9369 if (!DT.isReachableFromEntry(L->getHeader())) 9370 return false; 9371 9372 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9373 return true; 9374 9375 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9376 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9377 assert(DTN && "should reach the loop header before reaching the root!"); 9378 9379 BasicBlock *BB = DTN->getBlock(); 9380 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9381 return true; 9382 9383 BasicBlock *PBB = BB->getSinglePredecessor(); 9384 if (!PBB) 9385 continue; 9386 9387 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9388 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9389 continue; 9390 9391 Value *Condition = ContinuePredicate->getCondition(); 9392 9393 // If we have an edge `E` within the loop body that dominates the only 9394 // latch, the condition guarding `E` also guards the backedge. This 9395 // reasoning works only for loops with a single latch. 9396 9397 BasicBlockEdge DominatingEdge(PBB, BB); 9398 if (DominatingEdge.isSingleEdge()) { 9399 // We're constructively (and conservatively) enumerating edges within the 9400 // loop body that dominate the latch. The dominator tree better agree 9401 // with us on this: 9402 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9403 9404 if (isImpliedCond(Pred, LHS, RHS, Condition, 9405 BB != ContinuePredicate->getSuccessor(0))) 9406 return true; 9407 } 9408 } 9409 9410 return false; 9411 } 9412 9413 bool 9414 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9415 ICmpInst::Predicate Pred, 9416 const SCEV *LHS, const SCEV *RHS) { 9417 // Interpret a null as meaning no loop, where there is obviously no guard 9418 // (interprocedural conditions notwithstanding). 9419 if (!L) return false; 9420 9421 if (VerifyIR) 9422 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9423 "This cannot be done on broken IR!"); 9424 9425 // Both LHS and RHS must be available at loop entry. 9426 assert(isAvailableAtLoopEntry(LHS, L) && 9427 "LHS is not available at Loop Entry"); 9428 assert(isAvailableAtLoopEntry(RHS, L) && 9429 "RHS is not available at Loop Entry"); 9430 9431 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9432 return true; 9433 9434 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9435 // the facts (a >= b && a != b) separately. A typical situation is when the 9436 // non-strict comparison is known from ranges and non-equality is known from 9437 // dominating predicates. If we are proving strict comparison, we always try 9438 // to prove non-equality and non-strict comparison separately. 9439 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9440 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9441 bool ProvedNonStrictComparison = false; 9442 bool ProvedNonEquality = false; 9443 9444 if (ProvingStrictComparison) { 9445 ProvedNonStrictComparison = 9446 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9447 ProvedNonEquality = 9448 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9449 if (ProvedNonStrictComparison && ProvedNonEquality) 9450 return true; 9451 } 9452 9453 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9454 auto ProveViaGuard = [&](BasicBlock *Block) { 9455 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9456 return true; 9457 if (ProvingStrictComparison) { 9458 if (!ProvedNonStrictComparison) 9459 ProvedNonStrictComparison = 9460 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9461 if (!ProvedNonEquality) 9462 ProvedNonEquality = 9463 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9464 if (ProvedNonStrictComparison && ProvedNonEquality) 9465 return true; 9466 } 9467 return false; 9468 }; 9469 9470 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9471 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9472 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9473 return true; 9474 if (ProvingStrictComparison) { 9475 if (!ProvedNonStrictComparison) 9476 ProvedNonStrictComparison = 9477 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9478 if (!ProvedNonEquality) 9479 ProvedNonEquality = 9480 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9481 if (ProvedNonStrictComparison && ProvedNonEquality) 9482 return true; 9483 } 9484 return false; 9485 }; 9486 9487 // Starting at the loop predecessor, climb up the predecessor chain, as long 9488 // as there are predecessors that can be found that have unique successors 9489 // leading to the original header. 9490 for (std::pair<BasicBlock *, BasicBlock *> 9491 Pair(L->getLoopPredecessor(), L->getHeader()); 9492 Pair.first; 9493 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9494 9495 if (ProveViaGuard(Pair.first)) 9496 return true; 9497 9498 BranchInst *LoopEntryPredicate = 9499 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9500 if (!LoopEntryPredicate || 9501 LoopEntryPredicate->isUnconditional()) 9502 continue; 9503 9504 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9505 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9506 return true; 9507 } 9508 9509 // Check conditions due to any @llvm.assume intrinsics. 9510 for (auto &AssumeVH : AC.assumptions()) { 9511 if (!AssumeVH) 9512 continue; 9513 auto *CI = cast<CallInst>(AssumeVH); 9514 if (!DT.dominates(CI, L->getHeader())) 9515 continue; 9516 9517 if (ProveViaCond(CI->getArgOperand(0), false)) 9518 return true; 9519 } 9520 9521 return false; 9522 } 9523 9524 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9525 const SCEV *LHS, const SCEV *RHS, 9526 Value *FoundCondValue, 9527 bool Inverse) { 9528 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9529 return false; 9530 9531 auto ClearOnExit = 9532 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9533 9534 // Recursively handle And and Or conditions. 9535 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9536 if (BO->getOpcode() == Instruction::And) { 9537 if (!Inverse) 9538 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9539 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9540 } else if (BO->getOpcode() == Instruction::Or) { 9541 if (Inverse) 9542 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9543 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9544 } 9545 } 9546 9547 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9548 if (!ICI) return false; 9549 9550 // Now that we found a conditional branch that dominates the loop or controls 9551 // the loop latch. Check to see if it is the comparison we are looking for. 9552 ICmpInst::Predicate FoundPred; 9553 if (Inverse) 9554 FoundPred = ICI->getInversePredicate(); 9555 else 9556 FoundPred = ICI->getPredicate(); 9557 9558 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9559 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9560 9561 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9562 } 9563 9564 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9565 const SCEV *RHS, 9566 ICmpInst::Predicate FoundPred, 9567 const SCEV *FoundLHS, 9568 const SCEV *FoundRHS) { 9569 // Balance the types. 9570 if (getTypeSizeInBits(LHS->getType()) < 9571 getTypeSizeInBits(FoundLHS->getType())) { 9572 if (CmpInst::isSigned(Pred)) { 9573 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9574 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9575 } else { 9576 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9577 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9578 } 9579 } else if (getTypeSizeInBits(LHS->getType()) > 9580 getTypeSizeInBits(FoundLHS->getType())) { 9581 if (CmpInst::isSigned(FoundPred)) { 9582 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9583 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9584 } else { 9585 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9586 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9587 } 9588 } 9589 9590 // Canonicalize the query to match the way instcombine will have 9591 // canonicalized the comparison. 9592 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9593 if (LHS == RHS) 9594 return CmpInst::isTrueWhenEqual(Pred); 9595 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9596 if (FoundLHS == FoundRHS) 9597 return CmpInst::isFalseWhenEqual(FoundPred); 9598 9599 // Check to see if we can make the LHS or RHS match. 9600 if (LHS == FoundRHS || RHS == FoundLHS) { 9601 if (isa<SCEVConstant>(RHS)) { 9602 std::swap(FoundLHS, FoundRHS); 9603 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9604 } else { 9605 std::swap(LHS, RHS); 9606 Pred = ICmpInst::getSwappedPredicate(Pred); 9607 } 9608 } 9609 9610 // Check whether the found predicate is the same as the desired predicate. 9611 if (FoundPred == Pred) 9612 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9613 9614 // Check whether swapping the found predicate makes it the same as the 9615 // desired predicate. 9616 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9617 if (isa<SCEVConstant>(RHS)) 9618 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9619 else 9620 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9621 RHS, LHS, FoundLHS, FoundRHS); 9622 } 9623 9624 // Unsigned comparison is the same as signed comparison when both the operands 9625 // are non-negative. 9626 if (CmpInst::isUnsigned(FoundPred) && 9627 CmpInst::getSignedPredicate(FoundPred) == Pred && 9628 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9629 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9630 9631 // Check if we can make progress by sharpening ranges. 9632 if (FoundPred == ICmpInst::ICMP_NE && 9633 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9634 9635 const SCEVConstant *C = nullptr; 9636 const SCEV *V = nullptr; 9637 9638 if (isa<SCEVConstant>(FoundLHS)) { 9639 C = cast<SCEVConstant>(FoundLHS); 9640 V = FoundRHS; 9641 } else { 9642 C = cast<SCEVConstant>(FoundRHS); 9643 V = FoundLHS; 9644 } 9645 9646 // The guarding predicate tells us that C != V. If the known range 9647 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9648 // range we consider has to correspond to same signedness as the 9649 // predicate we're interested in folding. 9650 9651 APInt Min = ICmpInst::isSigned(Pred) ? 9652 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9653 9654 if (Min == C->getAPInt()) { 9655 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9656 // This is true even if (Min + 1) wraps around -- in case of 9657 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9658 9659 APInt SharperMin = Min + 1; 9660 9661 switch (Pred) { 9662 case ICmpInst::ICMP_SGE: 9663 case ICmpInst::ICMP_UGE: 9664 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9665 // RHS, we're done. 9666 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9667 getConstant(SharperMin))) 9668 return true; 9669 LLVM_FALLTHROUGH; 9670 9671 case ICmpInst::ICMP_SGT: 9672 case ICmpInst::ICMP_UGT: 9673 // We know from the range information that (V `Pred` Min || 9674 // V == Min). We know from the guarding condition that !(V 9675 // == Min). This gives us 9676 // 9677 // V `Pred` Min || V == Min && !(V == Min) 9678 // => V `Pred` Min 9679 // 9680 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9681 9682 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9683 return true; 9684 LLVM_FALLTHROUGH; 9685 9686 default: 9687 // No change 9688 break; 9689 } 9690 } 9691 } 9692 9693 // Check whether the actual condition is beyond sufficient. 9694 if (FoundPred == ICmpInst::ICMP_EQ) 9695 if (ICmpInst::isTrueWhenEqual(Pred)) 9696 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9697 return true; 9698 if (Pred == ICmpInst::ICMP_NE) 9699 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9700 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9701 return true; 9702 9703 // Otherwise assume the worst. 9704 return false; 9705 } 9706 9707 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9708 const SCEV *&L, const SCEV *&R, 9709 SCEV::NoWrapFlags &Flags) { 9710 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9711 if (!AE || AE->getNumOperands() != 2) 9712 return false; 9713 9714 L = AE->getOperand(0); 9715 R = AE->getOperand(1); 9716 Flags = AE->getNoWrapFlags(); 9717 return true; 9718 } 9719 9720 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9721 const SCEV *Less) { 9722 // We avoid subtracting expressions here because this function is usually 9723 // fairly deep in the call stack (i.e. is called many times). 9724 9725 // X - X = 0. 9726 if (More == Less) 9727 return APInt(getTypeSizeInBits(More->getType()), 0); 9728 9729 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9730 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9731 const auto *MAR = cast<SCEVAddRecExpr>(More); 9732 9733 if (LAR->getLoop() != MAR->getLoop()) 9734 return None; 9735 9736 // We look at affine expressions only; not for correctness but to keep 9737 // getStepRecurrence cheap. 9738 if (!LAR->isAffine() || !MAR->isAffine()) 9739 return None; 9740 9741 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9742 return None; 9743 9744 Less = LAR->getStart(); 9745 More = MAR->getStart(); 9746 9747 // fall through 9748 } 9749 9750 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9751 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9752 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9753 return M - L; 9754 } 9755 9756 SCEV::NoWrapFlags Flags; 9757 const SCEV *LLess = nullptr, *RLess = nullptr; 9758 const SCEV *LMore = nullptr, *RMore = nullptr; 9759 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9760 // Compare (X + C1) vs X. 9761 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9762 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9763 if (RLess == More) 9764 return -(C1->getAPInt()); 9765 9766 // Compare X vs (X + C2). 9767 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9768 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9769 if (RMore == Less) 9770 return C2->getAPInt(); 9771 9772 // Compare (X + C1) vs (X + C2). 9773 if (C1 && C2 && RLess == RMore) 9774 return C2->getAPInt() - C1->getAPInt(); 9775 9776 return None; 9777 } 9778 9779 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9780 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9781 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9782 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9783 return false; 9784 9785 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9786 if (!AddRecLHS) 9787 return false; 9788 9789 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9790 if (!AddRecFoundLHS) 9791 return false; 9792 9793 // We'd like to let SCEV reason about control dependencies, so we constrain 9794 // both the inequalities to be about add recurrences on the same loop. This 9795 // way we can use isLoopEntryGuardedByCond later. 9796 9797 const Loop *L = AddRecFoundLHS->getLoop(); 9798 if (L != AddRecLHS->getLoop()) 9799 return false; 9800 9801 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9802 // 9803 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9804 // ... (2) 9805 // 9806 // Informal proof for (2), assuming (1) [*]: 9807 // 9808 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9809 // 9810 // Then 9811 // 9812 // FoundLHS s< FoundRHS s< INT_MIN - C 9813 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9814 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9815 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9816 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9817 // <=> FoundLHS + C s< FoundRHS + C 9818 // 9819 // [*]: (1) can be proved by ruling out overflow. 9820 // 9821 // [**]: This can be proved by analyzing all the four possibilities: 9822 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9823 // (A s>= 0, B s>= 0). 9824 // 9825 // Note: 9826 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 9827 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 9828 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 9829 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 9830 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 9831 // C)". 9832 9833 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 9834 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 9835 if (!LDiff || !RDiff || *LDiff != *RDiff) 9836 return false; 9837 9838 if (LDiff->isMinValue()) 9839 return true; 9840 9841 APInt FoundRHSLimit; 9842 9843 if (Pred == CmpInst::ICMP_ULT) { 9844 FoundRHSLimit = -(*RDiff); 9845 } else { 9846 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 9847 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 9848 } 9849 9850 // Try to prove (1) or (2), as needed. 9851 return isAvailableAtLoopEntry(FoundRHS, L) && 9852 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 9853 getConstant(FoundRHSLimit)); 9854 } 9855 9856 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 9857 const SCEV *LHS, const SCEV *RHS, 9858 const SCEV *FoundLHS, 9859 const SCEV *FoundRHS, unsigned Depth) { 9860 const PHINode *LPhi = nullptr, *RPhi = nullptr; 9861 9862 auto ClearOnExit = make_scope_exit([&]() { 9863 if (LPhi) { 9864 bool Erased = PendingMerges.erase(LPhi); 9865 assert(Erased && "Failed to erase LPhi!"); 9866 (void)Erased; 9867 } 9868 if (RPhi) { 9869 bool Erased = PendingMerges.erase(RPhi); 9870 assert(Erased && "Failed to erase RPhi!"); 9871 (void)Erased; 9872 } 9873 }); 9874 9875 // Find respective Phis and check that they are not being pending. 9876 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 9877 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 9878 if (!PendingMerges.insert(Phi).second) 9879 return false; 9880 LPhi = Phi; 9881 } 9882 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 9883 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 9884 // If we detect a loop of Phi nodes being processed by this method, for 9885 // example: 9886 // 9887 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 9888 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 9889 // 9890 // we don't want to deal with a case that complex, so return conservative 9891 // answer false. 9892 if (!PendingMerges.insert(Phi).second) 9893 return false; 9894 RPhi = Phi; 9895 } 9896 9897 // If none of LHS, RHS is a Phi, nothing to do here. 9898 if (!LPhi && !RPhi) 9899 return false; 9900 9901 // If there is a SCEVUnknown Phi we are interested in, make it left. 9902 if (!LPhi) { 9903 std::swap(LHS, RHS); 9904 std::swap(FoundLHS, FoundRHS); 9905 std::swap(LPhi, RPhi); 9906 Pred = ICmpInst::getSwappedPredicate(Pred); 9907 } 9908 9909 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 9910 const BasicBlock *LBB = LPhi->getParent(); 9911 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 9912 9913 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 9914 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 9915 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 9916 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 9917 }; 9918 9919 if (RPhi && RPhi->getParent() == LBB) { 9920 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 9921 // If we compare two Phis from the same block, and for each entry block 9922 // the predicate is true for incoming values from this block, then the 9923 // predicate is also true for the Phis. 9924 for (const BasicBlock *IncBB : predecessors(LBB)) { 9925 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9926 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 9927 if (!ProvedEasily(L, R)) 9928 return false; 9929 } 9930 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 9931 // Case two: RHS is also a Phi from the same basic block, and it is an 9932 // AddRec. It means that there is a loop which has both AddRec and Unknown 9933 // PHIs, for it we can compare incoming values of AddRec from above the loop 9934 // and latch with their respective incoming values of LPhi. 9935 // TODO: Generalize to handle loops with many inputs in a header. 9936 if (LPhi->getNumIncomingValues() != 2) return false; 9937 9938 auto *RLoop = RAR->getLoop(); 9939 auto *Predecessor = RLoop->getLoopPredecessor(); 9940 assert(Predecessor && "Loop with AddRec with no predecessor?"); 9941 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 9942 if (!ProvedEasily(L1, RAR->getStart())) 9943 return false; 9944 auto *Latch = RLoop->getLoopLatch(); 9945 assert(Latch && "Loop with AddRec with no latch?"); 9946 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 9947 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 9948 return false; 9949 } else { 9950 // In all other cases go over inputs of LHS and compare each of them to RHS, 9951 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 9952 // At this point RHS is either a non-Phi, or it is a Phi from some block 9953 // different from LBB. 9954 for (const BasicBlock *IncBB : predecessors(LBB)) { 9955 // Check that RHS is available in this block. 9956 if (!dominates(RHS, IncBB)) 9957 return false; 9958 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 9959 if (!ProvedEasily(L, RHS)) 9960 return false; 9961 } 9962 } 9963 return true; 9964 } 9965 9966 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 9967 const SCEV *LHS, const SCEV *RHS, 9968 const SCEV *FoundLHS, 9969 const SCEV *FoundRHS) { 9970 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9971 return true; 9972 9973 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9974 return true; 9975 9976 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 9977 FoundLHS, FoundRHS) || 9978 // ~x < ~y --> x > y 9979 isImpliedCondOperandsHelper(Pred, LHS, RHS, 9980 getNotSCEV(FoundRHS), 9981 getNotSCEV(FoundLHS)); 9982 } 9983 9984 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 9985 template <typename MinMaxExprType> 9986 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 9987 const SCEV *Candidate) { 9988 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 9989 if (!MinMaxExpr) 9990 return false; 9991 9992 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 9993 } 9994 9995 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 9996 ICmpInst::Predicate Pred, 9997 const SCEV *LHS, const SCEV *RHS) { 9998 // If both sides are affine addrecs for the same loop, with equal 9999 // steps, and we know the recurrences don't wrap, then we only 10000 // need to check the predicate on the starting values. 10001 10002 if (!ICmpInst::isRelational(Pred)) 10003 return false; 10004 10005 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10006 if (!LAR) 10007 return false; 10008 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10009 if (!RAR) 10010 return false; 10011 if (LAR->getLoop() != RAR->getLoop()) 10012 return false; 10013 if (!LAR->isAffine() || !RAR->isAffine()) 10014 return false; 10015 10016 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10017 return false; 10018 10019 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10020 SCEV::FlagNSW : SCEV::FlagNUW; 10021 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10022 return false; 10023 10024 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10025 } 10026 10027 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10028 /// expression? 10029 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10030 ICmpInst::Predicate Pred, 10031 const SCEV *LHS, const SCEV *RHS) { 10032 switch (Pred) { 10033 default: 10034 return false; 10035 10036 case ICmpInst::ICMP_SGE: 10037 std::swap(LHS, RHS); 10038 LLVM_FALLTHROUGH; 10039 case ICmpInst::ICMP_SLE: 10040 return 10041 // min(A, ...) <= A 10042 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10043 // A <= max(A, ...) 10044 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10045 10046 case ICmpInst::ICMP_UGE: 10047 std::swap(LHS, RHS); 10048 LLVM_FALLTHROUGH; 10049 case ICmpInst::ICMP_ULE: 10050 return 10051 // min(A, ...) <= A 10052 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10053 // A <= max(A, ...) 10054 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10055 } 10056 10057 llvm_unreachable("covered switch fell through?!"); 10058 } 10059 10060 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10061 const SCEV *LHS, const SCEV *RHS, 10062 const SCEV *FoundLHS, 10063 const SCEV *FoundRHS, 10064 unsigned Depth) { 10065 assert(getTypeSizeInBits(LHS->getType()) == 10066 getTypeSizeInBits(RHS->getType()) && 10067 "LHS and RHS have different sizes?"); 10068 assert(getTypeSizeInBits(FoundLHS->getType()) == 10069 getTypeSizeInBits(FoundRHS->getType()) && 10070 "FoundLHS and FoundRHS have different sizes?"); 10071 // We want to avoid hurting the compile time with analysis of too big trees. 10072 if (Depth > MaxSCEVOperationsImplicationDepth) 10073 return false; 10074 // We only want to work with ICMP_SGT comparison so far. 10075 // TODO: Extend to ICMP_UGT? 10076 if (Pred == ICmpInst::ICMP_SLT) { 10077 Pred = ICmpInst::ICMP_SGT; 10078 std::swap(LHS, RHS); 10079 std::swap(FoundLHS, FoundRHS); 10080 } 10081 if (Pred != ICmpInst::ICMP_SGT) 10082 return false; 10083 10084 auto GetOpFromSExt = [&](const SCEV *S) { 10085 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10086 return Ext->getOperand(); 10087 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10088 // the constant in some cases. 10089 return S; 10090 }; 10091 10092 // Acquire values from extensions. 10093 auto *OrigLHS = LHS; 10094 auto *OrigFoundLHS = FoundLHS; 10095 LHS = GetOpFromSExt(LHS); 10096 FoundLHS = GetOpFromSExt(FoundLHS); 10097 10098 // Is the SGT predicate can be proved trivially or using the found context. 10099 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10100 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10101 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10102 FoundRHS, Depth + 1); 10103 }; 10104 10105 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10106 // We want to avoid creation of any new non-constant SCEV. Since we are 10107 // going to compare the operands to RHS, we should be certain that we don't 10108 // need any size extensions for this. So let's decline all cases when the 10109 // sizes of types of LHS and RHS do not match. 10110 // TODO: Maybe try to get RHS from sext to catch more cases? 10111 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10112 return false; 10113 10114 // Should not overflow. 10115 if (!LHSAddExpr->hasNoSignedWrap()) 10116 return false; 10117 10118 auto *LL = LHSAddExpr->getOperand(0); 10119 auto *LR = LHSAddExpr->getOperand(1); 10120 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10121 10122 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10123 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10124 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10125 }; 10126 // Try to prove the following rule: 10127 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10128 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10129 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10130 return true; 10131 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10132 Value *LL, *LR; 10133 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10134 10135 using namespace llvm::PatternMatch; 10136 10137 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10138 // Rules for division. 10139 // We are going to perform some comparisons with Denominator and its 10140 // derivative expressions. In general case, creating a SCEV for it may 10141 // lead to a complex analysis of the entire graph, and in particular it 10142 // can request trip count recalculation for the same loop. This would 10143 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10144 // this, we only want to create SCEVs that are constants in this section. 10145 // So we bail if Denominator is not a constant. 10146 if (!isa<ConstantInt>(LR)) 10147 return false; 10148 10149 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10150 10151 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10152 // then a SCEV for the numerator already exists and matches with FoundLHS. 10153 auto *Numerator = getExistingSCEV(LL); 10154 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10155 return false; 10156 10157 // Make sure that the numerator matches with FoundLHS and the denominator 10158 // is positive. 10159 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10160 return false; 10161 10162 auto *DTy = Denominator->getType(); 10163 auto *FRHSTy = FoundRHS->getType(); 10164 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10165 // One of types is a pointer and another one is not. We cannot extend 10166 // them properly to a wider type, so let us just reject this case. 10167 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10168 // to avoid this check. 10169 return false; 10170 10171 // Given that: 10172 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10173 auto *WTy = getWiderType(DTy, FRHSTy); 10174 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10175 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10176 10177 // Try to prove the following rule: 10178 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10179 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10180 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10181 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10182 if (isKnownNonPositive(RHS) && 10183 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10184 return true; 10185 10186 // Try to prove the following rule: 10187 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10188 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10189 // If we divide it by Denominator > 2, then: 10190 // 1. If FoundLHS is negative, then the result is 0. 10191 // 2. If FoundLHS is non-negative, then the result is non-negative. 10192 // Anyways, the result is non-negative. 10193 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10194 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10195 if (isKnownNegative(RHS) && 10196 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10197 return true; 10198 } 10199 } 10200 10201 // If our expression contained SCEVUnknown Phis, and we split it down and now 10202 // need to prove something for them, try to prove the predicate for every 10203 // possible incoming values of those Phis. 10204 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10205 return true; 10206 10207 return false; 10208 } 10209 10210 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10211 const SCEV *LHS, const SCEV *RHS) { 10212 // zext x u<= sext x, sext x s<= zext x 10213 switch (Pred) { 10214 case ICmpInst::ICMP_SGE: 10215 std::swap(LHS, RHS); 10216 LLVM_FALLTHROUGH; 10217 case ICmpInst::ICMP_SLE: { 10218 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10219 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10220 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10221 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10222 return true; 10223 break; 10224 } 10225 case ICmpInst::ICMP_UGE: 10226 std::swap(LHS, RHS); 10227 LLVM_FALLTHROUGH; 10228 case ICmpInst::ICMP_ULE: { 10229 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10230 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10231 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10232 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10233 return true; 10234 break; 10235 } 10236 default: 10237 break; 10238 }; 10239 return false; 10240 } 10241 10242 bool 10243 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10244 const SCEV *LHS, const SCEV *RHS) { 10245 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10246 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10247 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10248 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10249 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10250 } 10251 10252 bool 10253 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10254 const SCEV *LHS, const SCEV *RHS, 10255 const SCEV *FoundLHS, 10256 const SCEV *FoundRHS) { 10257 switch (Pred) { 10258 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10259 case ICmpInst::ICMP_EQ: 10260 case ICmpInst::ICMP_NE: 10261 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10262 return true; 10263 break; 10264 case ICmpInst::ICMP_SLT: 10265 case ICmpInst::ICMP_SLE: 10266 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10267 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10268 return true; 10269 break; 10270 case ICmpInst::ICMP_SGT: 10271 case ICmpInst::ICMP_SGE: 10272 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10273 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10274 return true; 10275 break; 10276 case ICmpInst::ICMP_ULT: 10277 case ICmpInst::ICMP_ULE: 10278 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10279 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10280 return true; 10281 break; 10282 case ICmpInst::ICMP_UGT: 10283 case ICmpInst::ICMP_UGE: 10284 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10285 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10286 return true; 10287 break; 10288 } 10289 10290 // Maybe it can be proved via operations? 10291 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10292 return true; 10293 10294 return false; 10295 } 10296 10297 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10298 const SCEV *LHS, 10299 const SCEV *RHS, 10300 const SCEV *FoundLHS, 10301 const SCEV *FoundRHS) { 10302 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10303 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10304 // reduce the compile time impact of this optimization. 10305 return false; 10306 10307 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10308 if (!Addend) 10309 return false; 10310 10311 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10312 10313 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10314 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10315 ConstantRange FoundLHSRange = 10316 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10317 10318 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10319 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10320 10321 // We can also compute the range of values for `LHS` that satisfy the 10322 // consequent, "`LHS` `Pred` `RHS`": 10323 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10324 ConstantRange SatisfyingLHSRange = 10325 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10326 10327 // The antecedent implies the consequent if every value of `LHS` that 10328 // satisfies the antecedent also satisfies the consequent. 10329 return SatisfyingLHSRange.contains(LHSRange); 10330 } 10331 10332 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10333 bool IsSigned, bool NoWrap) { 10334 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10335 10336 if (NoWrap) return false; 10337 10338 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10339 const SCEV *One = getOne(Stride->getType()); 10340 10341 if (IsSigned) { 10342 APInt MaxRHS = getSignedRangeMax(RHS); 10343 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10344 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10345 10346 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10347 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10348 } 10349 10350 APInt MaxRHS = getUnsignedRangeMax(RHS); 10351 APInt MaxValue = APInt::getMaxValue(BitWidth); 10352 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10353 10354 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10355 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10356 } 10357 10358 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10359 bool IsSigned, bool NoWrap) { 10360 if (NoWrap) return false; 10361 10362 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10363 const SCEV *One = getOne(Stride->getType()); 10364 10365 if (IsSigned) { 10366 APInt MinRHS = getSignedRangeMin(RHS); 10367 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10368 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10369 10370 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10371 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10372 } 10373 10374 APInt MinRHS = getUnsignedRangeMin(RHS); 10375 APInt MinValue = APInt::getMinValue(BitWidth); 10376 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10377 10378 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10379 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10380 } 10381 10382 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10383 bool Equality) { 10384 const SCEV *One = getOne(Step->getType()); 10385 Delta = Equality ? getAddExpr(Delta, Step) 10386 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10387 return getUDivExpr(Delta, Step); 10388 } 10389 10390 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10391 const SCEV *Stride, 10392 const SCEV *End, 10393 unsigned BitWidth, 10394 bool IsSigned) { 10395 10396 assert(!isKnownNonPositive(Stride) && 10397 "Stride is expected strictly positive!"); 10398 // Calculate the maximum backedge count based on the range of values 10399 // permitted by Start, End, and Stride. 10400 const SCEV *MaxBECount; 10401 APInt MinStart = 10402 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10403 10404 APInt StrideForMaxBECount = 10405 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10406 10407 // We already know that the stride is positive, so we paper over conservatism 10408 // in our range computation by forcing StrideForMaxBECount to be at least one. 10409 // In theory this is unnecessary, but we expect MaxBECount to be a 10410 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10411 // is nothing to constant fold it to). 10412 APInt One(BitWidth, 1, IsSigned); 10413 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10414 10415 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10416 : APInt::getMaxValue(BitWidth); 10417 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10418 10419 // Although End can be a MAX expression we estimate MaxEnd considering only 10420 // the case End = RHS of the loop termination condition. This is safe because 10421 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10422 // taken count. 10423 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10424 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10425 10426 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10427 getConstant(StrideForMaxBECount) /* Step */, 10428 false /* Equality */); 10429 10430 return MaxBECount; 10431 } 10432 10433 ScalarEvolution::ExitLimit 10434 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10435 const Loop *L, bool IsSigned, 10436 bool ControlsExit, bool AllowPredicates) { 10437 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10438 10439 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10440 bool PredicatedIV = false; 10441 10442 if (!IV && AllowPredicates) { 10443 // Try to make this an AddRec using runtime tests, in the first X 10444 // iterations of this loop, where X is the SCEV expression found by the 10445 // algorithm below. 10446 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10447 PredicatedIV = true; 10448 } 10449 10450 // Avoid weird loops 10451 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10452 return getCouldNotCompute(); 10453 10454 bool NoWrap = ControlsExit && 10455 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10456 10457 const SCEV *Stride = IV->getStepRecurrence(*this); 10458 10459 bool PositiveStride = isKnownPositive(Stride); 10460 10461 // Avoid negative or zero stride values. 10462 if (!PositiveStride) { 10463 // We can compute the correct backedge taken count for loops with unknown 10464 // strides if we can prove that the loop is not an infinite loop with side 10465 // effects. Here's the loop structure we are trying to handle - 10466 // 10467 // i = start 10468 // do { 10469 // A[i] = i; 10470 // i += s; 10471 // } while (i < end); 10472 // 10473 // The backedge taken count for such loops is evaluated as - 10474 // (max(end, start + stride) - start - 1) /u stride 10475 // 10476 // The additional preconditions that we need to check to prove correctness 10477 // of the above formula is as follows - 10478 // 10479 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10480 // NoWrap flag). 10481 // b) loop is single exit with no side effects. 10482 // 10483 // 10484 // Precondition a) implies that if the stride is negative, this is a single 10485 // trip loop. The backedge taken count formula reduces to zero in this case. 10486 // 10487 // Precondition b) implies that the unknown stride cannot be zero otherwise 10488 // we have UB. 10489 // 10490 // The positive stride case is the same as isKnownPositive(Stride) returning 10491 // true (original behavior of the function). 10492 // 10493 // We want to make sure that the stride is truly unknown as there are edge 10494 // cases where ScalarEvolution propagates no wrap flags to the 10495 // post-increment/decrement IV even though the increment/decrement operation 10496 // itself is wrapping. The computed backedge taken count may be wrong in 10497 // such cases. This is prevented by checking that the stride is not known to 10498 // be either positive or non-positive. For example, no wrap flags are 10499 // propagated to the post-increment IV of this loop with a trip count of 2 - 10500 // 10501 // unsigned char i; 10502 // for(i=127; i<128; i+=129) 10503 // A[i] = i; 10504 // 10505 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10506 !loopHasNoSideEffects(L)) 10507 return getCouldNotCompute(); 10508 } else if (!Stride->isOne() && 10509 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10510 // Avoid proven overflow cases: this will ensure that the backedge taken 10511 // count will not generate any unsigned overflow. Relaxed no-overflow 10512 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10513 // undefined behaviors like the case of C language. 10514 return getCouldNotCompute(); 10515 10516 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10517 : ICmpInst::ICMP_ULT; 10518 const SCEV *Start = IV->getStart(); 10519 const SCEV *End = RHS; 10520 // When the RHS is not invariant, we do not know the end bound of the loop and 10521 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10522 // calculate the MaxBECount, given the start, stride and max value for the end 10523 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10524 // checked above). 10525 if (!isLoopInvariant(RHS, L)) { 10526 const SCEV *MaxBECount = computeMaxBECountForLT( 10527 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10528 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10529 false /*MaxOrZero*/, Predicates); 10530 } 10531 // If the backedge is taken at least once, then it will be taken 10532 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10533 // is the LHS value of the less-than comparison the first time it is evaluated 10534 // and End is the RHS. 10535 const SCEV *BECountIfBackedgeTaken = 10536 computeBECount(getMinusSCEV(End, Start), Stride, false); 10537 // If the loop entry is guarded by the result of the backedge test of the 10538 // first loop iteration, then we know the backedge will be taken at least 10539 // once and so the backedge taken count is as above. If not then we use the 10540 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10541 // as if the backedge is taken at least once max(End,Start) is End and so the 10542 // result is as above, and if not max(End,Start) is Start so we get a backedge 10543 // count of zero. 10544 const SCEV *BECount; 10545 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10546 BECount = BECountIfBackedgeTaken; 10547 else { 10548 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10549 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10550 } 10551 10552 const SCEV *MaxBECount; 10553 bool MaxOrZero = false; 10554 if (isa<SCEVConstant>(BECount)) 10555 MaxBECount = BECount; 10556 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10557 // If we know exactly how many times the backedge will be taken if it's 10558 // taken at least once, then the backedge count will either be that or 10559 // zero. 10560 MaxBECount = BECountIfBackedgeTaken; 10561 MaxOrZero = true; 10562 } else { 10563 MaxBECount = computeMaxBECountForLT( 10564 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10565 } 10566 10567 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10568 !isa<SCEVCouldNotCompute>(BECount)) 10569 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10570 10571 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10572 } 10573 10574 ScalarEvolution::ExitLimit 10575 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10576 const Loop *L, bool IsSigned, 10577 bool ControlsExit, bool AllowPredicates) { 10578 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10579 // We handle only IV > Invariant 10580 if (!isLoopInvariant(RHS, L)) 10581 return getCouldNotCompute(); 10582 10583 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10584 if (!IV && AllowPredicates) 10585 // Try to make this an AddRec using runtime tests, in the first X 10586 // iterations of this loop, where X is the SCEV expression found by the 10587 // algorithm below. 10588 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10589 10590 // Avoid weird loops 10591 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10592 return getCouldNotCompute(); 10593 10594 bool NoWrap = ControlsExit && 10595 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10596 10597 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10598 10599 // Avoid negative or zero stride values 10600 if (!isKnownPositive(Stride)) 10601 return getCouldNotCompute(); 10602 10603 // Avoid proven overflow cases: this will ensure that the backedge taken count 10604 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10605 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10606 // behaviors like the case of C language. 10607 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10608 return getCouldNotCompute(); 10609 10610 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10611 : ICmpInst::ICMP_UGT; 10612 10613 const SCEV *Start = IV->getStart(); 10614 const SCEV *End = RHS; 10615 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10616 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10617 10618 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10619 10620 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10621 : getUnsignedRangeMax(Start); 10622 10623 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10624 : getUnsignedRangeMin(Stride); 10625 10626 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10627 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10628 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10629 10630 // Although End can be a MIN expression we estimate MinEnd considering only 10631 // the case End = RHS. This is safe because in the other case (Start - End) 10632 // is zero, leading to a zero maximum backedge taken count. 10633 APInt MinEnd = 10634 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10635 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10636 10637 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10638 ? BECount 10639 : computeBECount(getConstant(MaxStart - MinEnd), 10640 getConstant(MinStride), false); 10641 10642 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10643 MaxBECount = BECount; 10644 10645 return ExitLimit(BECount, MaxBECount, false, Predicates); 10646 } 10647 10648 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10649 ScalarEvolution &SE) const { 10650 if (Range.isFullSet()) // Infinite loop. 10651 return SE.getCouldNotCompute(); 10652 10653 // If the start is a non-zero constant, shift the range to simplify things. 10654 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10655 if (!SC->getValue()->isZero()) { 10656 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10657 Operands[0] = SE.getZero(SC->getType()); 10658 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10659 getNoWrapFlags(FlagNW)); 10660 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10661 return ShiftedAddRec->getNumIterationsInRange( 10662 Range.subtract(SC->getAPInt()), SE); 10663 // This is strange and shouldn't happen. 10664 return SE.getCouldNotCompute(); 10665 } 10666 10667 // The only time we can solve this is when we have all constant indices. 10668 // Otherwise, we cannot determine the overflow conditions. 10669 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10670 return SE.getCouldNotCompute(); 10671 10672 // Okay at this point we know that all elements of the chrec are constants and 10673 // that the start element is zero. 10674 10675 // First check to see if the range contains zero. If not, the first 10676 // iteration exits. 10677 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10678 if (!Range.contains(APInt(BitWidth, 0))) 10679 return SE.getZero(getType()); 10680 10681 if (isAffine()) { 10682 // If this is an affine expression then we have this situation: 10683 // Solve {0,+,A} in Range === Ax in Range 10684 10685 // We know that zero is in the range. If A is positive then we know that 10686 // the upper value of the range must be the first possible exit value. 10687 // If A is negative then the lower of the range is the last possible loop 10688 // value. Also note that we already checked for a full range. 10689 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10690 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10691 10692 // The exit value should be (End+A)/A. 10693 APInt ExitVal = (End + A).udiv(A); 10694 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10695 10696 // Evaluate at the exit value. If we really did fall out of the valid 10697 // range, then we computed our trip count, otherwise wrap around or other 10698 // things must have happened. 10699 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10700 if (Range.contains(Val->getValue())) 10701 return SE.getCouldNotCompute(); // Something strange happened 10702 10703 // Ensure that the previous value is in the range. This is a sanity check. 10704 assert(Range.contains( 10705 EvaluateConstantChrecAtConstant(this, 10706 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10707 "Linear scev computation is off in a bad way!"); 10708 return SE.getConstant(ExitValue); 10709 } 10710 10711 if (isQuadratic()) { 10712 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10713 return SE.getConstant(S.getValue()); 10714 } 10715 10716 return SE.getCouldNotCompute(); 10717 } 10718 10719 const SCEVAddRecExpr * 10720 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10721 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10722 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10723 // but in this case we cannot guarantee that the value returned will be an 10724 // AddRec because SCEV does not have a fixed point where it stops 10725 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10726 // may happen if we reach arithmetic depth limit while simplifying. So we 10727 // construct the returned value explicitly. 10728 SmallVector<const SCEV *, 3> Ops; 10729 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10730 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10731 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10732 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10733 // We know that the last operand is not a constant zero (otherwise it would 10734 // have been popped out earlier). This guarantees us that if the result has 10735 // the same last operand, then it will also not be popped out, meaning that 10736 // the returned value will be an AddRec. 10737 const SCEV *Last = getOperand(getNumOperands() - 1); 10738 assert(!Last->isZero() && "Recurrency with zero step?"); 10739 Ops.push_back(Last); 10740 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10741 SCEV::FlagAnyWrap)); 10742 } 10743 10744 // Return true when S contains at least an undef value. 10745 static inline bool containsUndefs(const SCEV *S) { 10746 return SCEVExprContains(S, [](const SCEV *S) { 10747 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10748 return isa<UndefValue>(SU->getValue()); 10749 return false; 10750 }); 10751 } 10752 10753 namespace { 10754 10755 // Collect all steps of SCEV expressions. 10756 struct SCEVCollectStrides { 10757 ScalarEvolution &SE; 10758 SmallVectorImpl<const SCEV *> &Strides; 10759 10760 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10761 : SE(SE), Strides(S) {} 10762 10763 bool follow(const SCEV *S) { 10764 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10765 Strides.push_back(AR->getStepRecurrence(SE)); 10766 return true; 10767 } 10768 10769 bool isDone() const { return false; } 10770 }; 10771 10772 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10773 struct SCEVCollectTerms { 10774 SmallVectorImpl<const SCEV *> &Terms; 10775 10776 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10777 10778 bool follow(const SCEV *S) { 10779 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10780 isa<SCEVSignExtendExpr>(S)) { 10781 if (!containsUndefs(S)) 10782 Terms.push_back(S); 10783 10784 // Stop recursion: once we collected a term, do not walk its operands. 10785 return false; 10786 } 10787 10788 // Keep looking. 10789 return true; 10790 } 10791 10792 bool isDone() const { return false; } 10793 }; 10794 10795 // Check if a SCEV contains an AddRecExpr. 10796 struct SCEVHasAddRec { 10797 bool &ContainsAddRec; 10798 10799 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10800 ContainsAddRec = false; 10801 } 10802 10803 bool follow(const SCEV *S) { 10804 if (isa<SCEVAddRecExpr>(S)) { 10805 ContainsAddRec = true; 10806 10807 // Stop recursion: once we collected a term, do not walk its operands. 10808 return false; 10809 } 10810 10811 // Keep looking. 10812 return true; 10813 } 10814 10815 bool isDone() const { return false; } 10816 }; 10817 10818 // Find factors that are multiplied with an expression that (possibly as a 10819 // subexpression) contains an AddRecExpr. In the expression: 10820 // 10821 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10822 // 10823 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 10824 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 10825 // parameters as they form a product with an induction variable. 10826 // 10827 // This collector expects all array size parameters to be in the same MulExpr. 10828 // It might be necessary to later add support for collecting parameters that are 10829 // spread over different nested MulExpr. 10830 struct SCEVCollectAddRecMultiplies { 10831 SmallVectorImpl<const SCEV *> &Terms; 10832 ScalarEvolution &SE; 10833 10834 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 10835 : Terms(T), SE(SE) {} 10836 10837 bool follow(const SCEV *S) { 10838 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 10839 bool HasAddRec = false; 10840 SmallVector<const SCEV *, 0> Operands; 10841 for (auto Op : Mul->operands()) { 10842 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 10843 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 10844 Operands.push_back(Op); 10845 } else if (Unknown) { 10846 HasAddRec = true; 10847 } else { 10848 bool ContainsAddRec = false; 10849 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 10850 visitAll(Op, ContiansAddRec); 10851 HasAddRec |= ContainsAddRec; 10852 } 10853 } 10854 if (Operands.size() == 0) 10855 return true; 10856 10857 if (!HasAddRec) 10858 return false; 10859 10860 Terms.push_back(SE.getMulExpr(Operands)); 10861 // Stop recursion: once we collected a term, do not walk its operands. 10862 return false; 10863 } 10864 10865 // Keep looking. 10866 return true; 10867 } 10868 10869 bool isDone() const { return false; } 10870 }; 10871 10872 } // end anonymous namespace 10873 10874 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 10875 /// two places: 10876 /// 1) The strides of AddRec expressions. 10877 /// 2) Unknowns that are multiplied with AddRec expressions. 10878 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 10879 SmallVectorImpl<const SCEV *> &Terms) { 10880 SmallVector<const SCEV *, 4> Strides; 10881 SCEVCollectStrides StrideCollector(*this, Strides); 10882 visitAll(Expr, StrideCollector); 10883 10884 LLVM_DEBUG({ 10885 dbgs() << "Strides:\n"; 10886 for (const SCEV *S : Strides) 10887 dbgs() << *S << "\n"; 10888 }); 10889 10890 for (const SCEV *S : Strides) { 10891 SCEVCollectTerms TermCollector(Terms); 10892 visitAll(S, TermCollector); 10893 } 10894 10895 LLVM_DEBUG({ 10896 dbgs() << "Terms:\n"; 10897 for (const SCEV *T : Terms) 10898 dbgs() << *T << "\n"; 10899 }); 10900 10901 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 10902 visitAll(Expr, MulCollector); 10903 } 10904 10905 static bool findArrayDimensionsRec(ScalarEvolution &SE, 10906 SmallVectorImpl<const SCEV *> &Terms, 10907 SmallVectorImpl<const SCEV *> &Sizes) { 10908 int Last = Terms.size() - 1; 10909 const SCEV *Step = Terms[Last]; 10910 10911 // End of recursion. 10912 if (Last == 0) { 10913 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 10914 SmallVector<const SCEV *, 2> Qs; 10915 for (const SCEV *Op : M->operands()) 10916 if (!isa<SCEVConstant>(Op)) 10917 Qs.push_back(Op); 10918 10919 Step = SE.getMulExpr(Qs); 10920 } 10921 10922 Sizes.push_back(Step); 10923 return true; 10924 } 10925 10926 for (const SCEV *&Term : Terms) { 10927 // Normalize the terms before the next call to findArrayDimensionsRec. 10928 const SCEV *Q, *R; 10929 SCEVDivision::divide(SE, Term, Step, &Q, &R); 10930 10931 // Bail out when GCD does not evenly divide one of the terms. 10932 if (!R->isZero()) 10933 return false; 10934 10935 Term = Q; 10936 } 10937 10938 // Remove all SCEVConstants. 10939 Terms.erase( 10940 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 10941 Terms.end()); 10942 10943 if (Terms.size() > 0) 10944 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 10945 return false; 10946 10947 Sizes.push_back(Step); 10948 return true; 10949 } 10950 10951 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 10952 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 10953 for (const SCEV *T : Terms) 10954 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 10955 return true; 10956 10957 return false; 10958 } 10959 10960 // Return the number of product terms in S. 10961 static inline int numberOfTerms(const SCEV *S) { 10962 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 10963 return Expr->getNumOperands(); 10964 return 1; 10965 } 10966 10967 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 10968 if (isa<SCEVConstant>(T)) 10969 return nullptr; 10970 10971 if (isa<SCEVUnknown>(T)) 10972 return T; 10973 10974 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 10975 SmallVector<const SCEV *, 2> Factors; 10976 for (const SCEV *Op : M->operands()) 10977 if (!isa<SCEVConstant>(Op)) 10978 Factors.push_back(Op); 10979 10980 return SE.getMulExpr(Factors); 10981 } 10982 10983 return T; 10984 } 10985 10986 /// Return the size of an element read or written by Inst. 10987 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 10988 Type *Ty; 10989 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 10990 Ty = Store->getValueOperand()->getType(); 10991 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 10992 Ty = Load->getType(); 10993 else 10994 return nullptr; 10995 10996 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 10997 return getSizeOfExpr(ETy, Ty); 10998 } 10999 11000 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11001 SmallVectorImpl<const SCEV *> &Sizes, 11002 const SCEV *ElementSize) { 11003 if (Terms.size() < 1 || !ElementSize) 11004 return; 11005 11006 // Early return when Terms do not contain parameters: we do not delinearize 11007 // non parametric SCEVs. 11008 if (!containsParameters(Terms)) 11009 return; 11010 11011 LLVM_DEBUG({ 11012 dbgs() << "Terms:\n"; 11013 for (const SCEV *T : Terms) 11014 dbgs() << *T << "\n"; 11015 }); 11016 11017 // Remove duplicates. 11018 array_pod_sort(Terms.begin(), Terms.end()); 11019 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11020 11021 // Put larger terms first. 11022 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11023 return numberOfTerms(LHS) > numberOfTerms(RHS); 11024 }); 11025 11026 // Try to divide all terms by the element size. If term is not divisible by 11027 // element size, proceed with the original term. 11028 for (const SCEV *&Term : Terms) { 11029 const SCEV *Q, *R; 11030 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11031 if (!Q->isZero()) 11032 Term = Q; 11033 } 11034 11035 SmallVector<const SCEV *, 4> NewTerms; 11036 11037 // Remove constant factors. 11038 for (const SCEV *T : Terms) 11039 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11040 NewTerms.push_back(NewT); 11041 11042 LLVM_DEBUG({ 11043 dbgs() << "Terms after sorting:\n"; 11044 for (const SCEV *T : NewTerms) 11045 dbgs() << *T << "\n"; 11046 }); 11047 11048 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11049 Sizes.clear(); 11050 return; 11051 } 11052 11053 // The last element to be pushed into Sizes is the size of an element. 11054 Sizes.push_back(ElementSize); 11055 11056 LLVM_DEBUG({ 11057 dbgs() << "Sizes:\n"; 11058 for (const SCEV *S : Sizes) 11059 dbgs() << *S << "\n"; 11060 }); 11061 } 11062 11063 void ScalarEvolution::computeAccessFunctions( 11064 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11065 SmallVectorImpl<const SCEV *> &Sizes) { 11066 // Early exit in case this SCEV is not an affine multivariate function. 11067 if (Sizes.empty()) 11068 return; 11069 11070 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11071 if (!AR->isAffine()) 11072 return; 11073 11074 const SCEV *Res = Expr; 11075 int Last = Sizes.size() - 1; 11076 for (int i = Last; i >= 0; i--) { 11077 const SCEV *Q, *R; 11078 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11079 11080 LLVM_DEBUG({ 11081 dbgs() << "Res: " << *Res << "\n"; 11082 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11083 dbgs() << "Res divided by Sizes[i]:\n"; 11084 dbgs() << "Quotient: " << *Q << "\n"; 11085 dbgs() << "Remainder: " << *R << "\n"; 11086 }); 11087 11088 Res = Q; 11089 11090 // Do not record the last subscript corresponding to the size of elements in 11091 // the array. 11092 if (i == Last) { 11093 11094 // Bail out if the remainder is too complex. 11095 if (isa<SCEVAddRecExpr>(R)) { 11096 Subscripts.clear(); 11097 Sizes.clear(); 11098 return; 11099 } 11100 11101 continue; 11102 } 11103 11104 // Record the access function for the current subscript. 11105 Subscripts.push_back(R); 11106 } 11107 11108 // Also push in last position the remainder of the last division: it will be 11109 // the access function of the innermost dimension. 11110 Subscripts.push_back(Res); 11111 11112 std::reverse(Subscripts.begin(), Subscripts.end()); 11113 11114 LLVM_DEBUG({ 11115 dbgs() << "Subscripts:\n"; 11116 for (const SCEV *S : Subscripts) 11117 dbgs() << *S << "\n"; 11118 }); 11119 } 11120 11121 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11122 /// sizes of an array access. Returns the remainder of the delinearization that 11123 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11124 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11125 /// expressions in the stride and base of a SCEV corresponding to the 11126 /// computation of a GCD (greatest common divisor) of base and stride. When 11127 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11128 /// 11129 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11130 /// 11131 /// void foo(long n, long m, long o, double A[n][m][o]) { 11132 /// 11133 /// for (long i = 0; i < n; i++) 11134 /// for (long j = 0; j < m; j++) 11135 /// for (long k = 0; k < o; k++) 11136 /// A[i][j][k] = 1.0; 11137 /// } 11138 /// 11139 /// the delinearization input is the following AddRec SCEV: 11140 /// 11141 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11142 /// 11143 /// From this SCEV, we are able to say that the base offset of the access is %A 11144 /// because it appears as an offset that does not divide any of the strides in 11145 /// the loops: 11146 /// 11147 /// CHECK: Base offset: %A 11148 /// 11149 /// and then SCEV->delinearize determines the size of some of the dimensions of 11150 /// the array as these are the multiples by which the strides are happening: 11151 /// 11152 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11153 /// 11154 /// Note that the outermost dimension remains of UnknownSize because there are 11155 /// no strides that would help identifying the size of the last dimension: when 11156 /// the array has been statically allocated, one could compute the size of that 11157 /// dimension by dividing the overall size of the array by the size of the known 11158 /// dimensions: %m * %o * 8. 11159 /// 11160 /// Finally delinearize provides the access functions for the array reference 11161 /// that does correspond to A[i][j][k] of the above C testcase: 11162 /// 11163 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11164 /// 11165 /// The testcases are checking the output of a function pass: 11166 /// DelinearizationPass that walks through all loads and stores of a function 11167 /// asking for the SCEV of the memory access with respect to all enclosing 11168 /// loops, calling SCEV->delinearize on that and printing the results. 11169 void ScalarEvolution::delinearize(const SCEV *Expr, 11170 SmallVectorImpl<const SCEV *> &Subscripts, 11171 SmallVectorImpl<const SCEV *> &Sizes, 11172 const SCEV *ElementSize) { 11173 // First step: collect parametric terms. 11174 SmallVector<const SCEV *, 4> Terms; 11175 collectParametricTerms(Expr, Terms); 11176 11177 if (Terms.empty()) 11178 return; 11179 11180 // Second step: find subscript sizes. 11181 findArrayDimensions(Terms, Sizes, ElementSize); 11182 11183 if (Sizes.empty()) 11184 return; 11185 11186 // Third step: compute the access functions for each subscript. 11187 computeAccessFunctions(Expr, Subscripts, Sizes); 11188 11189 if (Subscripts.empty()) 11190 return; 11191 11192 LLVM_DEBUG({ 11193 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11194 dbgs() << "ArrayDecl[UnknownSize]"; 11195 for (const SCEV *S : Sizes) 11196 dbgs() << "[" << *S << "]"; 11197 11198 dbgs() << "\nArrayRef"; 11199 for (const SCEV *S : Subscripts) 11200 dbgs() << "[" << *S << "]"; 11201 dbgs() << "\n"; 11202 }); 11203 } 11204 11205 bool ScalarEvolution::getIndexExpressionsFromGEP( 11206 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11207 SmallVectorImpl<int> &Sizes) { 11208 assert(Subscripts.empty() && Sizes.empty() && 11209 "Expected output lists to be empty on entry to this function."); 11210 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11211 Type *Ty = GEP->getPointerOperandType(); 11212 bool DroppedFirstDim = false; 11213 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11214 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11215 if (i == 1) { 11216 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11217 Ty = PtrTy->getElementType(); 11218 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11219 Ty = ArrayTy->getElementType(); 11220 } else { 11221 Subscripts.clear(); 11222 Sizes.clear(); 11223 return false; 11224 } 11225 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11226 if (Const->getValue()->isZero()) { 11227 DroppedFirstDim = true; 11228 continue; 11229 } 11230 Subscripts.push_back(Expr); 11231 continue; 11232 } 11233 11234 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11235 if (!ArrayTy) { 11236 Subscripts.clear(); 11237 Sizes.clear(); 11238 return false; 11239 } 11240 11241 Subscripts.push_back(Expr); 11242 if (!(DroppedFirstDim && i == 2)) 11243 Sizes.push_back(ArrayTy->getNumElements()); 11244 11245 Ty = ArrayTy->getElementType(); 11246 } 11247 return !Subscripts.empty(); 11248 } 11249 11250 //===----------------------------------------------------------------------===// 11251 // SCEVCallbackVH Class Implementation 11252 //===----------------------------------------------------------------------===// 11253 11254 void ScalarEvolution::SCEVCallbackVH::deleted() { 11255 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11256 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11257 SE->ConstantEvolutionLoopExitValue.erase(PN); 11258 SE->eraseValueFromMap(getValPtr()); 11259 // this now dangles! 11260 } 11261 11262 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11263 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11264 11265 // Forget all the expressions associated with users of the old value, 11266 // so that future queries will recompute the expressions using the new 11267 // value. 11268 Value *Old = getValPtr(); 11269 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11270 SmallPtrSet<User *, 8> Visited; 11271 while (!Worklist.empty()) { 11272 User *U = Worklist.pop_back_val(); 11273 // Deleting the Old value will cause this to dangle. Postpone 11274 // that until everything else is done. 11275 if (U == Old) 11276 continue; 11277 if (!Visited.insert(U).second) 11278 continue; 11279 if (PHINode *PN = dyn_cast<PHINode>(U)) 11280 SE->ConstantEvolutionLoopExitValue.erase(PN); 11281 SE->eraseValueFromMap(U); 11282 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11283 } 11284 // Delete the Old value. 11285 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11286 SE->ConstantEvolutionLoopExitValue.erase(PN); 11287 SE->eraseValueFromMap(Old); 11288 // this now dangles! 11289 } 11290 11291 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11292 : CallbackVH(V), SE(se) {} 11293 11294 //===----------------------------------------------------------------------===// 11295 // ScalarEvolution Class Implementation 11296 //===----------------------------------------------------------------------===// 11297 11298 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11299 AssumptionCache &AC, DominatorTree &DT, 11300 LoopInfo &LI) 11301 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11302 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11303 LoopDispositions(64), BlockDispositions(64) { 11304 // To use guards for proving predicates, we need to scan every instruction in 11305 // relevant basic blocks, and not just terminators. Doing this is a waste of 11306 // time if the IR does not actually contain any calls to 11307 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11308 // 11309 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11310 // to _add_ guards to the module when there weren't any before, and wants 11311 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11312 // efficient in lieu of being smart in that rather obscure case. 11313 11314 auto *GuardDecl = F.getParent()->getFunction( 11315 Intrinsic::getName(Intrinsic::experimental_guard)); 11316 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11317 } 11318 11319 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11320 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11321 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11322 ValueExprMap(std::move(Arg.ValueExprMap)), 11323 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11324 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11325 PendingMerges(std::move(Arg.PendingMerges)), 11326 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11327 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11328 PredicatedBackedgeTakenCounts( 11329 std::move(Arg.PredicatedBackedgeTakenCounts)), 11330 ConstantEvolutionLoopExitValue( 11331 std::move(Arg.ConstantEvolutionLoopExitValue)), 11332 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11333 LoopDispositions(std::move(Arg.LoopDispositions)), 11334 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11335 BlockDispositions(std::move(Arg.BlockDispositions)), 11336 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11337 SignedRanges(std::move(Arg.SignedRanges)), 11338 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11339 UniquePreds(std::move(Arg.UniquePreds)), 11340 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11341 LoopUsers(std::move(Arg.LoopUsers)), 11342 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11343 FirstUnknown(Arg.FirstUnknown) { 11344 Arg.FirstUnknown = nullptr; 11345 } 11346 11347 ScalarEvolution::~ScalarEvolution() { 11348 // Iterate through all the SCEVUnknown instances and call their 11349 // destructors, so that they release their references to their values. 11350 for (SCEVUnknown *U = FirstUnknown; U;) { 11351 SCEVUnknown *Tmp = U; 11352 U = U->Next; 11353 Tmp->~SCEVUnknown(); 11354 } 11355 FirstUnknown = nullptr; 11356 11357 ExprValueMap.clear(); 11358 ValueExprMap.clear(); 11359 HasRecMap.clear(); 11360 11361 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11362 // that a loop had multiple computable exits. 11363 for (auto &BTCI : BackedgeTakenCounts) 11364 BTCI.second.clear(); 11365 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11366 BTCI.second.clear(); 11367 11368 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11369 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11370 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11371 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11372 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11373 } 11374 11375 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11376 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11377 } 11378 11379 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11380 const Loop *L) { 11381 // Print all inner loops first 11382 for (Loop *I : *L) 11383 PrintLoopInfo(OS, SE, I); 11384 11385 OS << "Loop "; 11386 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11387 OS << ": "; 11388 11389 SmallVector<BasicBlock *, 8> ExitingBlocks; 11390 L->getExitingBlocks(ExitingBlocks); 11391 if (ExitingBlocks.size() != 1) 11392 OS << "<multiple exits> "; 11393 11394 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11395 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11396 else 11397 OS << "Unpredictable backedge-taken count.\n"; 11398 11399 if (ExitingBlocks.size() > 1) 11400 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11401 OS << " exit count for " << ExitingBlock->getName() << ": " 11402 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11403 } 11404 11405 OS << "Loop "; 11406 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11407 OS << ": "; 11408 11409 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11410 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11411 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11412 OS << ", actual taken count either this or zero."; 11413 } else { 11414 OS << "Unpredictable max backedge-taken count. "; 11415 } 11416 11417 OS << "\n" 11418 "Loop "; 11419 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11420 OS << ": "; 11421 11422 SCEVUnionPredicate Pred; 11423 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11424 if (!isa<SCEVCouldNotCompute>(PBT)) { 11425 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11426 OS << " Predicates:\n"; 11427 Pred.print(OS, 4); 11428 } else { 11429 OS << "Unpredictable predicated backedge-taken count. "; 11430 } 11431 OS << "\n"; 11432 11433 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11434 OS << "Loop "; 11435 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11436 OS << ": "; 11437 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11438 } 11439 } 11440 11441 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11442 switch (LD) { 11443 case ScalarEvolution::LoopVariant: 11444 return "Variant"; 11445 case ScalarEvolution::LoopInvariant: 11446 return "Invariant"; 11447 case ScalarEvolution::LoopComputable: 11448 return "Computable"; 11449 } 11450 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11451 } 11452 11453 void ScalarEvolution::print(raw_ostream &OS) const { 11454 // ScalarEvolution's implementation of the print method is to print 11455 // out SCEV values of all instructions that are interesting. Doing 11456 // this potentially causes it to create new SCEV objects though, 11457 // which technically conflicts with the const qualifier. This isn't 11458 // observable from outside the class though, so casting away the 11459 // const isn't dangerous. 11460 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11461 11462 if (ClassifyExpressions) { 11463 OS << "Classifying expressions for: "; 11464 F.printAsOperand(OS, /*PrintType=*/false); 11465 OS << "\n"; 11466 for (Instruction &I : instructions(F)) 11467 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11468 OS << I << '\n'; 11469 OS << " --> "; 11470 const SCEV *SV = SE.getSCEV(&I); 11471 SV->print(OS); 11472 if (!isa<SCEVCouldNotCompute>(SV)) { 11473 OS << " U: "; 11474 SE.getUnsignedRange(SV).print(OS); 11475 OS << " S: "; 11476 SE.getSignedRange(SV).print(OS); 11477 } 11478 11479 const Loop *L = LI.getLoopFor(I.getParent()); 11480 11481 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11482 if (AtUse != SV) { 11483 OS << " --> "; 11484 AtUse->print(OS); 11485 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11486 OS << " U: "; 11487 SE.getUnsignedRange(AtUse).print(OS); 11488 OS << " S: "; 11489 SE.getSignedRange(AtUse).print(OS); 11490 } 11491 } 11492 11493 if (L) { 11494 OS << "\t\t" "Exits: "; 11495 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11496 if (!SE.isLoopInvariant(ExitValue, L)) { 11497 OS << "<<Unknown>>"; 11498 } else { 11499 OS << *ExitValue; 11500 } 11501 11502 bool First = true; 11503 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11504 if (First) { 11505 OS << "\t\t" "LoopDispositions: { "; 11506 First = false; 11507 } else { 11508 OS << ", "; 11509 } 11510 11511 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11512 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11513 } 11514 11515 for (auto *InnerL : depth_first(L)) { 11516 if (InnerL == L) 11517 continue; 11518 if (First) { 11519 OS << "\t\t" "LoopDispositions: { "; 11520 First = false; 11521 } else { 11522 OS << ", "; 11523 } 11524 11525 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11526 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11527 } 11528 11529 OS << " }"; 11530 } 11531 11532 OS << "\n"; 11533 } 11534 } 11535 11536 OS << "Determining loop execution counts for: "; 11537 F.printAsOperand(OS, /*PrintType=*/false); 11538 OS << "\n"; 11539 for (Loop *I : LI) 11540 PrintLoopInfo(OS, &SE, I); 11541 } 11542 11543 ScalarEvolution::LoopDisposition 11544 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11545 auto &Values = LoopDispositions[S]; 11546 for (auto &V : Values) { 11547 if (V.getPointer() == L) 11548 return V.getInt(); 11549 } 11550 Values.emplace_back(L, LoopVariant); 11551 LoopDisposition D = computeLoopDisposition(S, L); 11552 auto &Values2 = LoopDispositions[S]; 11553 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11554 if (V.getPointer() == L) { 11555 V.setInt(D); 11556 break; 11557 } 11558 } 11559 return D; 11560 } 11561 11562 ScalarEvolution::LoopDisposition 11563 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11564 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11565 case scConstant: 11566 return LoopInvariant; 11567 case scTruncate: 11568 case scZeroExtend: 11569 case scSignExtend: 11570 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11571 case scAddRecExpr: { 11572 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11573 11574 // If L is the addrec's loop, it's computable. 11575 if (AR->getLoop() == L) 11576 return LoopComputable; 11577 11578 // Add recurrences are never invariant in the function-body (null loop). 11579 if (!L) 11580 return LoopVariant; 11581 11582 // Everything that is not defined at loop entry is variant. 11583 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11584 return LoopVariant; 11585 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11586 " dominate the contained loop's header?"); 11587 11588 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11589 if (AR->getLoop()->contains(L)) 11590 return LoopInvariant; 11591 11592 // This recurrence is variant w.r.t. L if any of its operands 11593 // are variant. 11594 for (auto *Op : AR->operands()) 11595 if (!isLoopInvariant(Op, L)) 11596 return LoopVariant; 11597 11598 // Otherwise it's loop-invariant. 11599 return LoopInvariant; 11600 } 11601 case scAddExpr: 11602 case scMulExpr: 11603 case scUMaxExpr: 11604 case scSMaxExpr: 11605 case scUMinExpr: 11606 case scSMinExpr: { 11607 bool HasVarying = false; 11608 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11609 LoopDisposition D = getLoopDisposition(Op, L); 11610 if (D == LoopVariant) 11611 return LoopVariant; 11612 if (D == LoopComputable) 11613 HasVarying = true; 11614 } 11615 return HasVarying ? LoopComputable : LoopInvariant; 11616 } 11617 case scUDivExpr: { 11618 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11619 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11620 if (LD == LoopVariant) 11621 return LoopVariant; 11622 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11623 if (RD == LoopVariant) 11624 return LoopVariant; 11625 return (LD == LoopInvariant && RD == LoopInvariant) ? 11626 LoopInvariant : LoopComputable; 11627 } 11628 case scUnknown: 11629 // All non-instruction values are loop invariant. All instructions are loop 11630 // invariant if they are not contained in the specified loop. 11631 // Instructions are never considered invariant in the function body 11632 // (null loop) because they are defined within the "loop". 11633 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11634 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11635 return LoopInvariant; 11636 case scCouldNotCompute: 11637 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11638 } 11639 llvm_unreachable("Unknown SCEV kind!"); 11640 } 11641 11642 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11643 return getLoopDisposition(S, L) == LoopInvariant; 11644 } 11645 11646 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11647 return getLoopDisposition(S, L) == LoopComputable; 11648 } 11649 11650 ScalarEvolution::BlockDisposition 11651 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11652 auto &Values = BlockDispositions[S]; 11653 for (auto &V : Values) { 11654 if (V.getPointer() == BB) 11655 return V.getInt(); 11656 } 11657 Values.emplace_back(BB, DoesNotDominateBlock); 11658 BlockDisposition D = computeBlockDisposition(S, BB); 11659 auto &Values2 = BlockDispositions[S]; 11660 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11661 if (V.getPointer() == BB) { 11662 V.setInt(D); 11663 break; 11664 } 11665 } 11666 return D; 11667 } 11668 11669 ScalarEvolution::BlockDisposition 11670 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11671 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11672 case scConstant: 11673 return ProperlyDominatesBlock; 11674 case scTruncate: 11675 case scZeroExtend: 11676 case scSignExtend: 11677 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11678 case scAddRecExpr: { 11679 // This uses a "dominates" query instead of "properly dominates" query 11680 // to test for proper dominance too, because the instruction which 11681 // produces the addrec's value is a PHI, and a PHI effectively properly 11682 // dominates its entire containing block. 11683 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11684 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11685 return DoesNotDominateBlock; 11686 11687 // Fall through into SCEVNAryExpr handling. 11688 LLVM_FALLTHROUGH; 11689 } 11690 case scAddExpr: 11691 case scMulExpr: 11692 case scUMaxExpr: 11693 case scSMaxExpr: 11694 case scUMinExpr: 11695 case scSMinExpr: { 11696 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11697 bool Proper = true; 11698 for (const SCEV *NAryOp : NAry->operands()) { 11699 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11700 if (D == DoesNotDominateBlock) 11701 return DoesNotDominateBlock; 11702 if (D == DominatesBlock) 11703 Proper = false; 11704 } 11705 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11706 } 11707 case scUDivExpr: { 11708 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11709 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11710 BlockDisposition LD = getBlockDisposition(LHS, BB); 11711 if (LD == DoesNotDominateBlock) 11712 return DoesNotDominateBlock; 11713 BlockDisposition RD = getBlockDisposition(RHS, BB); 11714 if (RD == DoesNotDominateBlock) 11715 return DoesNotDominateBlock; 11716 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11717 ProperlyDominatesBlock : DominatesBlock; 11718 } 11719 case scUnknown: 11720 if (Instruction *I = 11721 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11722 if (I->getParent() == BB) 11723 return DominatesBlock; 11724 if (DT.properlyDominates(I->getParent(), BB)) 11725 return ProperlyDominatesBlock; 11726 return DoesNotDominateBlock; 11727 } 11728 return ProperlyDominatesBlock; 11729 case scCouldNotCompute: 11730 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11731 } 11732 llvm_unreachable("Unknown SCEV kind!"); 11733 } 11734 11735 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11736 return getBlockDisposition(S, BB) >= DominatesBlock; 11737 } 11738 11739 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11740 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11741 } 11742 11743 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11744 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11745 } 11746 11747 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11748 auto IsS = [&](const SCEV *X) { return S == X; }; 11749 auto ContainsS = [&](const SCEV *X) { 11750 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11751 }; 11752 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11753 } 11754 11755 void 11756 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11757 ValuesAtScopes.erase(S); 11758 LoopDispositions.erase(S); 11759 BlockDispositions.erase(S); 11760 UnsignedRanges.erase(S); 11761 SignedRanges.erase(S); 11762 ExprValueMap.erase(S); 11763 HasRecMap.erase(S); 11764 MinTrailingZerosCache.erase(S); 11765 11766 for (auto I = PredicatedSCEVRewrites.begin(); 11767 I != PredicatedSCEVRewrites.end();) { 11768 std::pair<const SCEV *, const Loop *> Entry = I->first; 11769 if (Entry.first == S) 11770 PredicatedSCEVRewrites.erase(I++); 11771 else 11772 ++I; 11773 } 11774 11775 auto RemoveSCEVFromBackedgeMap = 11776 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11777 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11778 BackedgeTakenInfo &BEInfo = I->second; 11779 if (BEInfo.hasOperand(S, this)) { 11780 BEInfo.clear(); 11781 Map.erase(I++); 11782 } else 11783 ++I; 11784 } 11785 }; 11786 11787 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11788 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11789 } 11790 11791 void 11792 ScalarEvolution::getUsedLoops(const SCEV *S, 11793 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11794 struct FindUsedLoops { 11795 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11796 : LoopsUsed(LoopsUsed) {} 11797 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11798 bool follow(const SCEV *S) { 11799 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11800 LoopsUsed.insert(AR->getLoop()); 11801 return true; 11802 } 11803 11804 bool isDone() const { return false; } 11805 }; 11806 11807 FindUsedLoops F(LoopsUsed); 11808 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11809 } 11810 11811 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11812 SmallPtrSet<const Loop *, 8> LoopsUsed; 11813 getUsedLoops(S, LoopsUsed); 11814 for (auto *L : LoopsUsed) 11815 LoopUsers[L].push_back(S); 11816 } 11817 11818 void ScalarEvolution::verify() const { 11819 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11820 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11821 11822 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11823 11824 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11825 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11826 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11827 11828 const SCEV *visitConstant(const SCEVConstant *Constant) { 11829 return SE.getConstant(Constant->getAPInt()); 11830 } 11831 11832 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11833 return SE.getUnknown(Expr->getValue()); 11834 } 11835 11836 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11837 return SE.getCouldNotCompute(); 11838 } 11839 }; 11840 11841 SCEVMapper SCM(SE2); 11842 11843 while (!LoopStack.empty()) { 11844 auto *L = LoopStack.pop_back_val(); 11845 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11846 11847 auto *CurBECount = SCM.visit( 11848 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11849 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11850 11851 if (CurBECount == SE2.getCouldNotCompute() || 11852 NewBECount == SE2.getCouldNotCompute()) { 11853 // NB! This situation is legal, but is very suspicious -- whatever pass 11854 // change the loop to make a trip count go from could not compute to 11855 // computable or vice-versa *should have* invalidated SCEV. However, we 11856 // choose not to assert here (for now) since we don't want false 11857 // positives. 11858 continue; 11859 } 11860 11861 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11862 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11863 // not propagate undef aggressively). This means we can (and do) fail 11864 // verification in cases where a transform makes the trip count of a loop 11865 // go from "undef" to "undef+1" (say). The transform is fine, since in 11866 // both cases the loop iterates "undef" times, but SCEV thinks we 11867 // increased the trip count of the loop by 1 incorrectly. 11868 continue; 11869 } 11870 11871 if (SE.getTypeSizeInBits(CurBECount->getType()) > 11872 SE.getTypeSizeInBits(NewBECount->getType())) 11873 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 11874 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 11875 SE.getTypeSizeInBits(NewBECount->getType())) 11876 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 11877 11878 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 11879 11880 // Unless VerifySCEVStrict is set, we only compare constant deltas. 11881 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 11882 dbgs() << "Trip Count for " << *L << " Changed!\n"; 11883 dbgs() << "Old: " << *CurBECount << "\n"; 11884 dbgs() << "New: " << *NewBECount << "\n"; 11885 dbgs() << "Delta: " << *Delta << "\n"; 11886 std::abort(); 11887 } 11888 } 11889 } 11890 11891 bool ScalarEvolution::invalidate( 11892 Function &F, const PreservedAnalyses &PA, 11893 FunctionAnalysisManager::Invalidator &Inv) { 11894 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 11895 // of its dependencies is invalidated. 11896 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 11897 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 11898 Inv.invalidate<AssumptionAnalysis>(F, PA) || 11899 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 11900 Inv.invalidate<LoopAnalysis>(F, PA); 11901 } 11902 11903 AnalysisKey ScalarEvolutionAnalysis::Key; 11904 11905 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 11906 FunctionAnalysisManager &AM) { 11907 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 11908 AM.getResult<AssumptionAnalysis>(F), 11909 AM.getResult<DominatorTreeAnalysis>(F), 11910 AM.getResult<LoopAnalysis>(F)); 11911 } 11912 11913 PreservedAnalyses 11914 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 11915 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 11916 return PreservedAnalyses::all(); 11917 } 11918 11919 PreservedAnalyses 11920 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 11921 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 11922 return PreservedAnalyses::all(); 11923 } 11924 11925 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 11926 "Scalar Evolution Analysis", false, true) 11927 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 11928 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 11929 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 11930 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 11931 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 11932 "Scalar Evolution Analysis", false, true) 11933 11934 char ScalarEvolutionWrapperPass::ID = 0; 11935 11936 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 11937 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 11938 } 11939 11940 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 11941 SE.reset(new ScalarEvolution( 11942 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 11943 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 11944 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 11945 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 11946 return false; 11947 } 11948 11949 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 11950 11951 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 11952 SE->print(OS); 11953 } 11954 11955 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 11956 if (!VerifySCEV) 11957 return; 11958 11959 SE->verify(); 11960 } 11961 11962 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 11963 AU.setPreservesAll(); 11964 AU.addRequiredTransitive<AssumptionCacheTracker>(); 11965 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 11966 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 11967 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 11968 } 11969 11970 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 11971 const SCEV *RHS) { 11972 FoldingSetNodeID ID; 11973 assert(LHS->getType() == RHS->getType() && 11974 "Type mismatch between LHS and RHS"); 11975 // Unique this node based on the arguments 11976 ID.AddInteger(SCEVPredicate::P_Equal); 11977 ID.AddPointer(LHS); 11978 ID.AddPointer(RHS); 11979 void *IP = nullptr; 11980 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11981 return S; 11982 SCEVEqualPredicate *Eq = new (SCEVAllocator) 11983 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 11984 UniquePreds.InsertNode(Eq, IP); 11985 return Eq; 11986 } 11987 11988 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 11989 const SCEVAddRecExpr *AR, 11990 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 11991 FoldingSetNodeID ID; 11992 // Unique this node based on the arguments 11993 ID.AddInteger(SCEVPredicate::P_Wrap); 11994 ID.AddPointer(AR); 11995 ID.AddInteger(AddedFlags); 11996 void *IP = nullptr; 11997 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 11998 return S; 11999 auto *OF = new (SCEVAllocator) 12000 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12001 UniquePreds.InsertNode(OF, IP); 12002 return OF; 12003 } 12004 12005 namespace { 12006 12007 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12008 public: 12009 12010 /// Rewrites \p S in the context of a loop L and the SCEV predication 12011 /// infrastructure. 12012 /// 12013 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12014 /// equivalences present in \p Pred. 12015 /// 12016 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12017 /// \p NewPreds such that the result will be an AddRecExpr. 12018 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12019 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12020 SCEVUnionPredicate *Pred) { 12021 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12022 return Rewriter.visit(S); 12023 } 12024 12025 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12026 if (Pred) { 12027 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12028 for (auto *Pred : ExprPreds) 12029 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12030 if (IPred->getLHS() == Expr) 12031 return IPred->getRHS(); 12032 } 12033 return convertToAddRecWithPreds(Expr); 12034 } 12035 12036 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12037 const SCEV *Operand = visit(Expr->getOperand()); 12038 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12039 if (AR && AR->getLoop() == L && AR->isAffine()) { 12040 // This couldn't be folded because the operand didn't have the nuw 12041 // flag. Add the nusw flag as an assumption that we could make. 12042 const SCEV *Step = AR->getStepRecurrence(SE); 12043 Type *Ty = Expr->getType(); 12044 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12045 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12046 SE.getSignExtendExpr(Step, Ty), L, 12047 AR->getNoWrapFlags()); 12048 } 12049 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12050 } 12051 12052 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12053 const SCEV *Operand = visit(Expr->getOperand()); 12054 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12055 if (AR && AR->getLoop() == L && AR->isAffine()) { 12056 // This couldn't be folded because the operand didn't have the nsw 12057 // flag. Add the nssw flag as an assumption that we could make. 12058 const SCEV *Step = AR->getStepRecurrence(SE); 12059 Type *Ty = Expr->getType(); 12060 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12061 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12062 SE.getSignExtendExpr(Step, Ty), L, 12063 AR->getNoWrapFlags()); 12064 } 12065 return SE.getSignExtendExpr(Operand, Expr->getType()); 12066 } 12067 12068 private: 12069 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12070 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12071 SCEVUnionPredicate *Pred) 12072 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12073 12074 bool addOverflowAssumption(const SCEVPredicate *P) { 12075 if (!NewPreds) { 12076 // Check if we've already made this assumption. 12077 return Pred && Pred->implies(P); 12078 } 12079 NewPreds->insert(P); 12080 return true; 12081 } 12082 12083 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12084 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12085 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12086 return addOverflowAssumption(A); 12087 } 12088 12089 // If \p Expr represents a PHINode, we try to see if it can be represented 12090 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12091 // to add this predicate as a runtime overflow check, we return the AddRec. 12092 // If \p Expr does not meet these conditions (is not a PHI node, or we 12093 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12094 // return \p Expr. 12095 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12096 if (!isa<PHINode>(Expr->getValue())) 12097 return Expr; 12098 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12099 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12100 if (!PredicatedRewrite) 12101 return Expr; 12102 for (auto *P : PredicatedRewrite->second){ 12103 // Wrap predicates from outer loops are not supported. 12104 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12105 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12106 if (L != AR->getLoop()) 12107 return Expr; 12108 } 12109 if (!addOverflowAssumption(P)) 12110 return Expr; 12111 } 12112 return PredicatedRewrite->first; 12113 } 12114 12115 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12116 SCEVUnionPredicate *Pred; 12117 const Loop *L; 12118 }; 12119 12120 } // end anonymous namespace 12121 12122 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12123 SCEVUnionPredicate &Preds) { 12124 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12125 } 12126 12127 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12128 const SCEV *S, const Loop *L, 12129 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12130 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12131 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12132 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12133 12134 if (!AddRec) 12135 return nullptr; 12136 12137 // Since the transformation was successful, we can now transfer the SCEV 12138 // predicates. 12139 for (auto *P : TransformPreds) 12140 Preds.insert(P); 12141 12142 return AddRec; 12143 } 12144 12145 /// SCEV predicates 12146 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12147 SCEVPredicateKind Kind) 12148 : FastID(ID), Kind(Kind) {} 12149 12150 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12151 const SCEV *LHS, const SCEV *RHS) 12152 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12153 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12154 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12155 } 12156 12157 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12158 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12159 12160 if (!Op) 12161 return false; 12162 12163 return Op->LHS == LHS && Op->RHS == RHS; 12164 } 12165 12166 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12167 12168 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12169 12170 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12171 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12172 } 12173 12174 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12175 const SCEVAddRecExpr *AR, 12176 IncrementWrapFlags Flags) 12177 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12178 12179 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12180 12181 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12182 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12183 12184 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12185 } 12186 12187 bool SCEVWrapPredicate::isAlwaysTrue() const { 12188 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12189 IncrementWrapFlags IFlags = Flags; 12190 12191 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12192 IFlags = clearFlags(IFlags, IncrementNSSW); 12193 12194 return IFlags == IncrementAnyWrap; 12195 } 12196 12197 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12198 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12199 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12200 OS << "<nusw>"; 12201 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12202 OS << "<nssw>"; 12203 OS << "\n"; 12204 } 12205 12206 SCEVWrapPredicate::IncrementWrapFlags 12207 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12208 ScalarEvolution &SE) { 12209 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12210 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12211 12212 // We can safely transfer the NSW flag as NSSW. 12213 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12214 ImpliedFlags = IncrementNSSW; 12215 12216 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12217 // If the increment is positive, the SCEV NUW flag will also imply the 12218 // WrapPredicate NUSW flag. 12219 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12220 if (Step->getValue()->getValue().isNonNegative()) 12221 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12222 } 12223 12224 return ImpliedFlags; 12225 } 12226 12227 /// Union predicates don't get cached so create a dummy set ID for it. 12228 SCEVUnionPredicate::SCEVUnionPredicate() 12229 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12230 12231 bool SCEVUnionPredicate::isAlwaysTrue() const { 12232 return all_of(Preds, 12233 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12234 } 12235 12236 ArrayRef<const SCEVPredicate *> 12237 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12238 auto I = SCEVToPreds.find(Expr); 12239 if (I == SCEVToPreds.end()) 12240 return ArrayRef<const SCEVPredicate *>(); 12241 return I->second; 12242 } 12243 12244 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12245 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12246 return all_of(Set->Preds, 12247 [this](const SCEVPredicate *I) { return this->implies(I); }); 12248 12249 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12250 if (ScevPredsIt == SCEVToPreds.end()) 12251 return false; 12252 auto &SCEVPreds = ScevPredsIt->second; 12253 12254 return any_of(SCEVPreds, 12255 [N](const SCEVPredicate *I) { return I->implies(N); }); 12256 } 12257 12258 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12259 12260 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12261 for (auto Pred : Preds) 12262 Pred->print(OS, Depth); 12263 } 12264 12265 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12266 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12267 for (auto Pred : Set->Preds) 12268 add(Pred); 12269 return; 12270 } 12271 12272 if (implies(N)) 12273 return; 12274 12275 const SCEV *Key = N->getExpr(); 12276 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12277 " associated expression!"); 12278 12279 SCEVToPreds[Key].push_back(N); 12280 Preds.push_back(N); 12281 } 12282 12283 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12284 Loop &L) 12285 : SE(SE), L(L) {} 12286 12287 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12288 const SCEV *Expr = SE.getSCEV(V); 12289 RewriteEntry &Entry = RewriteMap[Expr]; 12290 12291 // If we already have an entry and the version matches, return it. 12292 if (Entry.second && Generation == Entry.first) 12293 return Entry.second; 12294 12295 // We found an entry but it's stale. Rewrite the stale entry 12296 // according to the current predicate. 12297 if (Entry.second) 12298 Expr = Entry.second; 12299 12300 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12301 Entry = {Generation, NewSCEV}; 12302 12303 return NewSCEV; 12304 } 12305 12306 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12307 if (!BackedgeCount) { 12308 SCEVUnionPredicate BackedgePred; 12309 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12310 addPredicate(BackedgePred); 12311 } 12312 return BackedgeCount; 12313 } 12314 12315 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12316 if (Preds.implies(&Pred)) 12317 return; 12318 Preds.add(&Pred); 12319 updateGeneration(); 12320 } 12321 12322 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12323 return Preds; 12324 } 12325 12326 void PredicatedScalarEvolution::updateGeneration() { 12327 // If the generation number wrapped recompute everything. 12328 if (++Generation == 0) { 12329 for (auto &II : RewriteMap) { 12330 const SCEV *Rewritten = II.second.second; 12331 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12332 } 12333 } 12334 } 12335 12336 void PredicatedScalarEvolution::setNoOverflow( 12337 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12338 const SCEV *Expr = getSCEV(V); 12339 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12340 12341 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12342 12343 // Clear the statically implied flags. 12344 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12345 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12346 12347 auto II = FlagsMap.insert({V, Flags}); 12348 if (!II.second) 12349 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12350 } 12351 12352 bool PredicatedScalarEvolution::hasNoOverflow( 12353 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12354 const SCEV *Expr = getSCEV(V); 12355 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12356 12357 Flags = SCEVWrapPredicate::clearFlags( 12358 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12359 12360 auto II = FlagsMap.find(V); 12361 12362 if (II != FlagsMap.end()) 12363 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12364 12365 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12366 } 12367 12368 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12369 const SCEV *Expr = this->getSCEV(V); 12370 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12371 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12372 12373 if (!New) 12374 return nullptr; 12375 12376 for (auto *P : NewPreds) 12377 Preds.add(P); 12378 12379 updateGeneration(); 12380 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12381 return New; 12382 } 12383 12384 PredicatedScalarEvolution::PredicatedScalarEvolution( 12385 const PredicatedScalarEvolution &Init) 12386 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12387 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12388 for (auto I : Init.FlagsMap) 12389 FlagsMap.insert(I); 12390 } 12391 12392 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12393 // For each block. 12394 for (auto *BB : L.getBlocks()) 12395 for (auto &I : *BB) { 12396 if (!SE.isSCEVable(I.getType())) 12397 continue; 12398 12399 auto *Expr = SE.getSCEV(&I); 12400 auto II = RewriteMap.find(Expr); 12401 12402 if (II == RewriteMap.end()) 12403 continue; 12404 12405 // Don't print things that are not interesting. 12406 if (II->second.second == Expr) 12407 continue; 12408 12409 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12410 OS.indent(Depth + 2) << *Expr << "\n"; 12411 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12412 } 12413 } 12414 12415 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12416 // arbitrary expressions. 12417 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12418 // 4, A / B becomes X / 8). 12419 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12420 const SCEV *&RHS) { 12421 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12422 if (Add == nullptr || Add->getNumOperands() != 2) 12423 return false; 12424 12425 const SCEV *A = Add->getOperand(1); 12426 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12427 12428 if (Mul == nullptr) 12429 return false; 12430 12431 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12432 // (SomeExpr + (-(SomeExpr / B) * B)). 12433 if (Expr == getURemExpr(A, B)) { 12434 LHS = A; 12435 RHS = B; 12436 return true; 12437 } 12438 return false; 12439 }; 12440 12441 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12442 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12443 return MatchURemWithDivisor(Mul->getOperand(1)) || 12444 MatchURemWithDivisor(Mul->getOperand(2)); 12445 12446 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12447 if (Mul->getNumOperands() == 2) 12448 return MatchURemWithDivisor(Mul->getOperand(1)) || 12449 MatchURemWithDivisor(Mul->getOperand(0)) || 12450 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12451 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12452 return false; 12453 } 12454