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/ScalarEvolutionExpressions.h" 83 #include "llvm/Analysis/TargetLibraryInfo.h" 84 #include "llvm/Analysis/ValueTracking.h" 85 #include "llvm/Config/llvm-config.h" 86 #include "llvm/IR/Argument.h" 87 #include "llvm/IR/BasicBlock.h" 88 #include "llvm/IR/CFG.h" 89 #include "llvm/IR/CallSite.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 the size of the SCEV S. 852 static inline int sizeOfSCEV(const SCEV *S) { 853 struct FindSCEVSize { 854 int Size = 0; 855 856 FindSCEVSize() = default; 857 858 bool follow(const SCEV *S) { 859 ++Size; 860 // Keep looking at all operands of S. 861 return true; 862 } 863 864 bool isDone() const { 865 return false; 866 } 867 }; 868 869 FindSCEVSize F; 870 SCEVTraversal<FindSCEVSize> ST(F); 871 ST.visitAll(S); 872 return F.Size; 873 } 874 875 /// Returns true if the subtree of \p S contains at least HugeExprThreshold 876 /// nodes. 877 static bool isHugeExpression(const SCEV *S) { 878 return S->getExpressionSize() >= HugeExprThreshold; 879 } 880 881 /// Returns true of \p Ops contains a huge SCEV (see definition above). 882 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 883 return any_of(Ops, isHugeExpression); 884 } 885 886 namespace { 887 888 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 889 public: 890 // Computes the Quotient and Remainder of the division of Numerator by 891 // Denominator. 892 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 893 const SCEV *Denominator, const SCEV **Quotient, 894 const SCEV **Remainder) { 895 assert(Numerator && Denominator && "Uninitialized SCEV"); 896 897 SCEVDivision D(SE, Numerator, Denominator); 898 899 // Check for the trivial case here to avoid having to check for it in the 900 // rest of the code. 901 if (Numerator == Denominator) { 902 *Quotient = D.One; 903 *Remainder = D.Zero; 904 return; 905 } 906 907 if (Numerator->isZero()) { 908 *Quotient = D.Zero; 909 *Remainder = D.Zero; 910 return; 911 } 912 913 // A simple case when N/1. The quotient is N. 914 if (Denominator->isOne()) { 915 *Quotient = Numerator; 916 *Remainder = D.Zero; 917 return; 918 } 919 920 // Split the Denominator when it is a product. 921 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 922 const SCEV *Q, *R; 923 *Quotient = Numerator; 924 for (const SCEV *Op : T->operands()) { 925 divide(SE, *Quotient, Op, &Q, &R); 926 *Quotient = Q; 927 928 // Bail out when the Numerator is not divisible by one of the terms of 929 // the Denominator. 930 if (!R->isZero()) { 931 *Quotient = D.Zero; 932 *Remainder = Numerator; 933 return; 934 } 935 } 936 *Remainder = D.Zero; 937 return; 938 } 939 940 D.visit(Numerator); 941 *Quotient = D.Quotient; 942 *Remainder = D.Remainder; 943 } 944 945 // Except in the trivial case described above, we do not know how to divide 946 // Expr by Denominator for the following functions with empty implementation. 947 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 948 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 949 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 950 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 951 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 952 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 953 void visitSMinExpr(const SCEVSMinExpr *Numerator) {} 954 void visitUMinExpr(const SCEVUMinExpr *Numerator) {} 955 void visitUnknown(const SCEVUnknown *Numerator) {} 956 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 957 958 void visitConstant(const SCEVConstant *Numerator) { 959 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 960 APInt NumeratorVal = Numerator->getAPInt(); 961 APInt DenominatorVal = D->getAPInt(); 962 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 963 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 964 965 if (NumeratorBW > DenominatorBW) 966 DenominatorVal = DenominatorVal.sext(NumeratorBW); 967 else if (NumeratorBW < DenominatorBW) 968 NumeratorVal = NumeratorVal.sext(DenominatorBW); 969 970 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 971 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 972 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 973 Quotient = SE.getConstant(QuotientVal); 974 Remainder = SE.getConstant(RemainderVal); 975 return; 976 } 977 } 978 979 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 980 const SCEV *StartQ, *StartR, *StepQ, *StepR; 981 if (!Numerator->isAffine()) 982 return cannotDivide(Numerator); 983 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 984 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 985 // Bail out if the types do not match. 986 Type *Ty = Denominator->getType(); 987 if (Ty != StartQ->getType() || Ty != StartR->getType() || 988 Ty != StepQ->getType() || Ty != StepR->getType()) 989 return cannotDivide(Numerator); 990 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 991 Numerator->getNoWrapFlags()); 992 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 993 Numerator->getNoWrapFlags()); 994 } 995 996 void visitAddExpr(const SCEVAddExpr *Numerator) { 997 SmallVector<const SCEV *, 2> Qs, Rs; 998 Type *Ty = Denominator->getType(); 999 1000 for (const SCEV *Op : Numerator->operands()) { 1001 const SCEV *Q, *R; 1002 divide(SE, Op, Denominator, &Q, &R); 1003 1004 // Bail out if types do not match. 1005 if (Ty != Q->getType() || Ty != R->getType()) 1006 return cannotDivide(Numerator); 1007 1008 Qs.push_back(Q); 1009 Rs.push_back(R); 1010 } 1011 1012 if (Qs.size() == 1) { 1013 Quotient = Qs[0]; 1014 Remainder = Rs[0]; 1015 return; 1016 } 1017 1018 Quotient = SE.getAddExpr(Qs); 1019 Remainder = SE.getAddExpr(Rs); 1020 } 1021 1022 void visitMulExpr(const SCEVMulExpr *Numerator) { 1023 SmallVector<const SCEV *, 2> Qs; 1024 Type *Ty = Denominator->getType(); 1025 1026 bool FoundDenominatorTerm = false; 1027 for (const SCEV *Op : Numerator->operands()) { 1028 // Bail out if types do not match. 1029 if (Ty != Op->getType()) 1030 return cannotDivide(Numerator); 1031 1032 if (FoundDenominatorTerm) { 1033 Qs.push_back(Op); 1034 continue; 1035 } 1036 1037 // Check whether Denominator divides one of the product operands. 1038 const SCEV *Q, *R; 1039 divide(SE, Op, Denominator, &Q, &R); 1040 if (!R->isZero()) { 1041 Qs.push_back(Op); 1042 continue; 1043 } 1044 1045 // Bail out if types do not match. 1046 if (Ty != Q->getType()) 1047 return cannotDivide(Numerator); 1048 1049 FoundDenominatorTerm = true; 1050 Qs.push_back(Q); 1051 } 1052 1053 if (FoundDenominatorTerm) { 1054 Remainder = Zero; 1055 if (Qs.size() == 1) 1056 Quotient = Qs[0]; 1057 else 1058 Quotient = SE.getMulExpr(Qs); 1059 return; 1060 } 1061 1062 if (!isa<SCEVUnknown>(Denominator)) 1063 return cannotDivide(Numerator); 1064 1065 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1066 ValueToValueMap RewriteMap; 1067 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1068 cast<SCEVConstant>(Zero)->getValue(); 1069 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1070 1071 if (Remainder->isZero()) { 1072 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1073 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1074 cast<SCEVConstant>(One)->getValue(); 1075 Quotient = 1076 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1077 return; 1078 } 1079 1080 // Quotient is (Numerator - Remainder) divided by Denominator. 1081 const SCEV *Q, *R; 1082 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1083 // This SCEV does not seem to simplify: fail the division here. 1084 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1085 return cannotDivide(Numerator); 1086 divide(SE, Diff, Denominator, &Q, &R); 1087 if (R != Zero) 1088 return cannotDivide(Numerator); 1089 Quotient = Q; 1090 } 1091 1092 private: 1093 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1094 const SCEV *Denominator) 1095 : SE(S), Denominator(Denominator) { 1096 Zero = SE.getZero(Denominator->getType()); 1097 One = SE.getOne(Denominator->getType()); 1098 1099 // We generally do not know how to divide Expr by Denominator. We 1100 // initialize the division to a "cannot divide" state to simplify the rest 1101 // of the code. 1102 cannotDivide(Numerator); 1103 } 1104 1105 // Convenience function for giving up on the division. We set the quotient to 1106 // be equal to zero and the remainder to be equal to the numerator. 1107 void cannotDivide(const SCEV *Numerator) { 1108 Quotient = Zero; 1109 Remainder = Numerator; 1110 } 1111 1112 ScalarEvolution &SE; 1113 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1114 }; 1115 1116 } // end anonymous namespace 1117 1118 //===----------------------------------------------------------------------===// 1119 // Simple SCEV method implementations 1120 //===----------------------------------------------------------------------===// 1121 1122 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1123 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1124 ScalarEvolution &SE, 1125 Type *ResultTy) { 1126 // Handle the simplest case efficiently. 1127 if (K == 1) 1128 return SE.getTruncateOrZeroExtend(It, ResultTy); 1129 1130 // We are using the following formula for BC(It, K): 1131 // 1132 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1133 // 1134 // Suppose, W is the bitwidth of the return value. We must be prepared for 1135 // overflow. Hence, we must assure that the result of our computation is 1136 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1137 // safe in modular arithmetic. 1138 // 1139 // However, this code doesn't use exactly that formula; the formula it uses 1140 // is something like the following, where T is the number of factors of 2 in 1141 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1142 // exponentiation: 1143 // 1144 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1145 // 1146 // This formula is trivially equivalent to the previous formula. However, 1147 // this formula can be implemented much more efficiently. The trick is that 1148 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1149 // arithmetic. To do exact division in modular arithmetic, all we have 1150 // to do is multiply by the inverse. Therefore, this step can be done at 1151 // width W. 1152 // 1153 // The next issue is how to safely do the division by 2^T. The way this 1154 // is done is by doing the multiplication step at a width of at least W + T 1155 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1156 // when we perform the division by 2^T (which is equivalent to a right shift 1157 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1158 // truncated out after the division by 2^T. 1159 // 1160 // In comparison to just directly using the first formula, this technique 1161 // is much more efficient; using the first formula requires W * K bits, 1162 // but this formula less than W + K bits. Also, the first formula requires 1163 // a division step, whereas this formula only requires multiplies and shifts. 1164 // 1165 // It doesn't matter whether the subtraction step is done in the calculation 1166 // width or the input iteration count's width; if the subtraction overflows, 1167 // the result must be zero anyway. We prefer here to do it in the width of 1168 // the induction variable because it helps a lot for certain cases; CodeGen 1169 // isn't smart enough to ignore the overflow, which leads to much less 1170 // efficient code if the width of the subtraction is wider than the native 1171 // register width. 1172 // 1173 // (It's possible to not widen at all by pulling out factors of 2 before 1174 // the multiplication; for example, K=2 can be calculated as 1175 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1176 // extra arithmetic, so it's not an obvious win, and it gets 1177 // much more complicated for K > 3.) 1178 1179 // Protection from insane SCEVs; this bound is conservative, 1180 // but it probably doesn't matter. 1181 if (K > 1000) 1182 return SE.getCouldNotCompute(); 1183 1184 unsigned W = SE.getTypeSizeInBits(ResultTy); 1185 1186 // Calculate K! / 2^T and T; we divide out the factors of two before 1187 // multiplying for calculating K! / 2^T to avoid overflow. 1188 // Other overflow doesn't matter because we only care about the bottom 1189 // W bits of the result. 1190 APInt OddFactorial(W, 1); 1191 unsigned T = 1; 1192 for (unsigned i = 3; i <= K; ++i) { 1193 APInt Mult(W, i); 1194 unsigned TwoFactors = Mult.countTrailingZeros(); 1195 T += TwoFactors; 1196 Mult.lshrInPlace(TwoFactors); 1197 OddFactorial *= Mult; 1198 } 1199 1200 // We need at least W + T bits for the multiplication step 1201 unsigned CalculationBits = W + T; 1202 1203 // Calculate 2^T, at width T+W. 1204 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1205 1206 // Calculate the multiplicative inverse of K! / 2^T; 1207 // this multiplication factor will perform the exact division by 1208 // K! / 2^T. 1209 APInt Mod = APInt::getSignedMinValue(W+1); 1210 APInt MultiplyFactor = OddFactorial.zext(W+1); 1211 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1212 MultiplyFactor = MultiplyFactor.trunc(W); 1213 1214 // Calculate the product, at width T+W 1215 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1216 CalculationBits); 1217 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1218 for (unsigned i = 1; i != K; ++i) { 1219 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1220 Dividend = SE.getMulExpr(Dividend, 1221 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1222 } 1223 1224 // Divide by 2^T 1225 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1226 1227 // Truncate the result, and divide by K! / 2^T. 1228 1229 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1230 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1231 } 1232 1233 /// Return the value of this chain of recurrences at the specified iteration 1234 /// number. We can evaluate this recurrence by multiplying each element in the 1235 /// chain by the binomial coefficient corresponding to it. In other words, we 1236 /// can evaluate {A,+,B,+,C,+,D} as: 1237 /// 1238 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1239 /// 1240 /// where BC(It, k) stands for binomial coefficient. 1241 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1242 ScalarEvolution &SE) const { 1243 const SCEV *Result = getStart(); 1244 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1245 // The computation is correct in the face of overflow provided that the 1246 // multiplication is performed _after_ the evaluation of the binomial 1247 // coefficient. 1248 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1249 if (isa<SCEVCouldNotCompute>(Coeff)) 1250 return Coeff; 1251 1252 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1253 } 1254 return Result; 1255 } 1256 1257 //===----------------------------------------------------------------------===// 1258 // SCEV Expression folder implementations 1259 //===----------------------------------------------------------------------===// 1260 1261 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1262 unsigned Depth) { 1263 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1264 "This is not a truncating conversion!"); 1265 assert(isSCEVable(Ty) && 1266 "This is not a conversion to a SCEVable type!"); 1267 Ty = getEffectiveSCEVType(Ty); 1268 1269 FoldingSetNodeID ID; 1270 ID.AddInteger(scTruncate); 1271 ID.AddPointer(Op); 1272 ID.AddPointer(Ty); 1273 void *IP = nullptr; 1274 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1275 1276 // Fold if the operand is constant. 1277 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1278 return getConstant( 1279 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1280 1281 // trunc(trunc(x)) --> trunc(x) 1282 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1283 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1284 1285 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1286 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1287 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1288 1289 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1290 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1291 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1292 1293 if (Depth > MaxCastDepth) { 1294 SCEV *S = 1295 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1296 UniqueSCEVs.InsertNode(S, IP); 1297 addToLoopUseLists(S); 1298 return S; 1299 } 1300 1301 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1302 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1303 // if after transforming we have at most one truncate, not counting truncates 1304 // that replace other casts. 1305 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1306 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1307 SmallVector<const SCEV *, 4> Operands; 1308 unsigned numTruncs = 0; 1309 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1310 ++i) { 1311 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1312 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1313 numTruncs++; 1314 Operands.push_back(S); 1315 } 1316 if (numTruncs < 2) { 1317 if (isa<SCEVAddExpr>(Op)) 1318 return getAddExpr(Operands); 1319 else if (isa<SCEVMulExpr>(Op)) 1320 return getMulExpr(Operands); 1321 else 1322 llvm_unreachable("Unexpected SCEV type for Op."); 1323 } 1324 // Although we checked in the beginning that ID is not in the cache, it is 1325 // possible that during recursion and different modification ID was inserted 1326 // into the cache. So if we find it, just return it. 1327 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1328 return S; 1329 } 1330 1331 // If the input value is a chrec scev, truncate the chrec's operands. 1332 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1333 SmallVector<const SCEV *, 4> Operands; 1334 for (const SCEV *Op : AddRec->operands()) 1335 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1336 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1337 } 1338 1339 // The cast wasn't folded; create an explicit cast node. We can reuse 1340 // the existing insert position since if we get here, we won't have 1341 // made any changes which would invalidate it. 1342 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1343 Op, Ty); 1344 UniqueSCEVs.InsertNode(S, IP); 1345 addToLoopUseLists(S); 1346 return S; 1347 } 1348 1349 // Get the limit of a recurrence such that incrementing by Step cannot cause 1350 // signed overflow as long as the value of the recurrence within the 1351 // loop does not exceed this limit before incrementing. 1352 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1353 ICmpInst::Predicate *Pred, 1354 ScalarEvolution *SE) { 1355 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1356 if (SE->isKnownPositive(Step)) { 1357 *Pred = ICmpInst::ICMP_SLT; 1358 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1359 SE->getSignedRangeMax(Step)); 1360 } 1361 if (SE->isKnownNegative(Step)) { 1362 *Pred = ICmpInst::ICMP_SGT; 1363 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1364 SE->getSignedRangeMin(Step)); 1365 } 1366 return nullptr; 1367 } 1368 1369 // Get the limit of a recurrence such that incrementing by Step cannot cause 1370 // unsigned overflow as long as the value of the recurrence within the loop does 1371 // not exceed this limit before incrementing. 1372 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1373 ICmpInst::Predicate *Pred, 1374 ScalarEvolution *SE) { 1375 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1376 *Pred = ICmpInst::ICMP_ULT; 1377 1378 return SE->getConstant(APInt::getMinValue(BitWidth) - 1379 SE->getUnsignedRangeMax(Step)); 1380 } 1381 1382 namespace { 1383 1384 struct ExtendOpTraitsBase { 1385 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1386 unsigned); 1387 }; 1388 1389 // Used to make code generic over signed and unsigned overflow. 1390 template <typename ExtendOp> struct ExtendOpTraits { 1391 // Members present: 1392 // 1393 // static const SCEV::NoWrapFlags WrapType; 1394 // 1395 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1396 // 1397 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1398 // ICmpInst::Predicate *Pred, 1399 // ScalarEvolution *SE); 1400 }; 1401 1402 template <> 1403 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1404 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1405 1406 static const GetExtendExprTy GetExtendExpr; 1407 1408 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1409 ICmpInst::Predicate *Pred, 1410 ScalarEvolution *SE) { 1411 return getSignedOverflowLimitForStep(Step, Pred, SE); 1412 } 1413 }; 1414 1415 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1416 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1417 1418 template <> 1419 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1420 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1421 1422 static const GetExtendExprTy GetExtendExpr; 1423 1424 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1425 ICmpInst::Predicate *Pred, 1426 ScalarEvolution *SE) { 1427 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1428 } 1429 }; 1430 1431 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1432 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1433 1434 } // end anonymous namespace 1435 1436 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1437 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1438 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1439 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1440 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1441 // expression "Step + sext/zext(PreIncAR)" is congruent with 1442 // "sext/zext(PostIncAR)" 1443 template <typename ExtendOpTy> 1444 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1445 ScalarEvolution *SE, unsigned Depth) { 1446 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1447 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1448 1449 const Loop *L = AR->getLoop(); 1450 const SCEV *Start = AR->getStart(); 1451 const SCEV *Step = AR->getStepRecurrence(*SE); 1452 1453 // Check for a simple looking step prior to loop entry. 1454 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1455 if (!SA) 1456 return nullptr; 1457 1458 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1459 // subtraction is expensive. For this purpose, perform a quick and dirty 1460 // difference, by checking for Step in the operand list. 1461 SmallVector<const SCEV *, 4> DiffOps; 1462 for (const SCEV *Op : SA->operands()) 1463 if (Op != Step) 1464 DiffOps.push_back(Op); 1465 1466 if (DiffOps.size() == SA->getNumOperands()) 1467 return nullptr; 1468 1469 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1470 // `Step`: 1471 1472 // 1. NSW/NUW flags on the step increment. 1473 auto PreStartFlags = 1474 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1475 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1476 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1477 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1478 1479 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1480 // "S+X does not sign/unsign-overflow". 1481 // 1482 1483 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1484 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1485 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1486 return PreStart; 1487 1488 // 2. Direct overflow check on the step operation's expression. 1489 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1490 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1491 const SCEV *OperandExtendedStart = 1492 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1493 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1494 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1495 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1496 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1497 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1498 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1499 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1500 } 1501 return PreStart; 1502 } 1503 1504 // 3. Loop precondition. 1505 ICmpInst::Predicate Pred; 1506 const SCEV *OverflowLimit = 1507 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1508 1509 if (OverflowLimit && 1510 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1511 return PreStart; 1512 1513 return nullptr; 1514 } 1515 1516 // Get the normalized zero or sign extended expression for this AddRec's Start. 1517 template <typename ExtendOpTy> 1518 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1519 ScalarEvolution *SE, 1520 unsigned Depth) { 1521 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1522 1523 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1524 if (!PreStart) 1525 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1526 1527 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1528 Depth), 1529 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1530 } 1531 1532 // Try to prove away overflow by looking at "nearby" add recurrences. A 1533 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1534 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1535 // 1536 // Formally: 1537 // 1538 // {S,+,X} == {S-T,+,X} + T 1539 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1540 // 1541 // If ({S-T,+,X} + T) does not overflow ... (1) 1542 // 1543 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1544 // 1545 // If {S-T,+,X} does not overflow ... (2) 1546 // 1547 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1548 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1549 // 1550 // If (S-T)+T does not overflow ... (3) 1551 // 1552 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1553 // == {Ext(S),+,Ext(X)} == LHS 1554 // 1555 // Thus, if (1), (2) and (3) are true for some T, then 1556 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1557 // 1558 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1559 // does not overflow" restricted to the 0th iteration. Therefore we only need 1560 // to check for (1) and (2). 1561 // 1562 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1563 // is `Delta` (defined below). 1564 template <typename ExtendOpTy> 1565 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1566 const SCEV *Step, 1567 const Loop *L) { 1568 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1569 1570 // We restrict `Start` to a constant to prevent SCEV from spending too much 1571 // time here. It is correct (but more expensive) to continue with a 1572 // non-constant `Start` and do a general SCEV subtraction to compute 1573 // `PreStart` below. 1574 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1575 if (!StartC) 1576 return false; 1577 1578 APInt StartAI = StartC->getAPInt(); 1579 1580 for (unsigned Delta : {-2, -1, 1, 2}) { 1581 const SCEV *PreStart = getConstant(StartAI - Delta); 1582 1583 FoldingSetNodeID ID; 1584 ID.AddInteger(scAddRecExpr); 1585 ID.AddPointer(PreStart); 1586 ID.AddPointer(Step); 1587 ID.AddPointer(L); 1588 void *IP = nullptr; 1589 const auto *PreAR = 1590 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1591 1592 // Give up if we don't already have the add recurrence we need because 1593 // actually constructing an add recurrence is relatively expensive. 1594 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1595 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1596 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1597 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1598 DeltaS, &Pred, this); 1599 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1600 return true; 1601 } 1602 } 1603 1604 return false; 1605 } 1606 1607 // Finds an integer D for an expression (C + x + y + ...) such that the top 1608 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1609 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1610 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1611 // the (C + x + y + ...) expression is \p WholeAddExpr. 1612 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1613 const SCEVConstant *ConstantTerm, 1614 const SCEVAddExpr *WholeAddExpr) { 1615 const APInt C = ConstantTerm->getAPInt(); 1616 const unsigned BitWidth = C.getBitWidth(); 1617 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1618 uint32_t TZ = BitWidth; 1619 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1620 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1621 if (TZ) { 1622 // Set D to be as many least significant bits of C as possible while still 1623 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1624 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1625 } 1626 return APInt(BitWidth, 0); 1627 } 1628 1629 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1630 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1631 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1632 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1633 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1634 const APInt &ConstantStart, 1635 const SCEV *Step) { 1636 const unsigned BitWidth = ConstantStart.getBitWidth(); 1637 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1638 if (TZ) 1639 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1640 : ConstantStart; 1641 return APInt(BitWidth, 0); 1642 } 1643 1644 const SCEV * 1645 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1646 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1647 "This is not an extending conversion!"); 1648 assert(isSCEVable(Ty) && 1649 "This is not a conversion to a SCEVable type!"); 1650 Ty = getEffectiveSCEVType(Ty); 1651 1652 // Fold if the operand is constant. 1653 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1654 return getConstant( 1655 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1656 1657 // zext(zext(x)) --> zext(x) 1658 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1659 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1660 1661 // Before doing any expensive analysis, check to see if we've already 1662 // computed a SCEV for this Op and Ty. 1663 FoldingSetNodeID ID; 1664 ID.AddInteger(scZeroExtend); 1665 ID.AddPointer(Op); 1666 ID.AddPointer(Ty); 1667 void *IP = nullptr; 1668 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1669 if (Depth > MaxCastDepth) { 1670 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1671 Op, Ty); 1672 UniqueSCEVs.InsertNode(S, IP); 1673 addToLoopUseLists(S); 1674 return S; 1675 } 1676 1677 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1678 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1679 // It's possible the bits taken off by the truncate were all zero bits. If 1680 // so, we should be able to simplify this further. 1681 const SCEV *X = ST->getOperand(); 1682 ConstantRange CR = getUnsignedRange(X); 1683 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1684 unsigned NewBits = getTypeSizeInBits(Ty); 1685 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1686 CR.zextOrTrunc(NewBits))) 1687 return getTruncateOrZeroExtend(X, Ty, Depth); 1688 } 1689 1690 // If the input value is a chrec scev, and we can prove that the value 1691 // did not overflow the old, smaller, value, we can zero extend all of the 1692 // operands (often constants). This allows analysis of something like 1693 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1694 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1695 if (AR->isAffine()) { 1696 const SCEV *Start = AR->getStart(); 1697 const SCEV *Step = AR->getStepRecurrence(*this); 1698 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1699 const Loop *L = AR->getLoop(); 1700 1701 if (!AR->hasNoUnsignedWrap()) { 1702 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1703 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1704 } 1705 1706 // If we have special knowledge that this addrec won't overflow, 1707 // we don't need to do any further analysis. 1708 if (AR->hasNoUnsignedWrap()) 1709 return getAddRecExpr( 1710 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1711 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1712 1713 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1714 // Note that this serves two purposes: It filters out loops that are 1715 // simply not analyzable, and it covers the case where this code is 1716 // being called from within backedge-taken count analysis, such that 1717 // attempting to ask for the backedge-taken count would likely result 1718 // in infinite recursion. In the later case, the analysis code will 1719 // cope with a conservative value, and it will take care to purge 1720 // that value once it has finished. 1721 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1722 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1723 // Manually compute the final value for AR, checking for 1724 // overflow. 1725 1726 // Check whether the backedge-taken count can be losslessly casted to 1727 // the addrec's type. The count is always unsigned. 1728 const SCEV *CastedMaxBECount = 1729 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1730 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1731 CastedMaxBECount, MaxBECount->getType(), Depth); 1732 if (MaxBECount == RecastedMaxBECount) { 1733 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1734 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1735 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1736 SCEV::FlagAnyWrap, Depth + 1); 1737 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1738 SCEV::FlagAnyWrap, 1739 Depth + 1), 1740 WideTy, Depth + 1); 1741 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1742 const SCEV *WideMaxBECount = 1743 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1744 const SCEV *OperandExtendedAdd = 1745 getAddExpr(WideStart, 1746 getMulExpr(WideMaxBECount, 1747 getZeroExtendExpr(Step, WideTy, Depth + 1), 1748 SCEV::FlagAnyWrap, Depth + 1), 1749 SCEV::FlagAnyWrap, Depth + 1); 1750 if (ZAdd == OperandExtendedAdd) { 1751 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1752 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1753 // Return the expression with the addrec on the outside. 1754 return getAddRecExpr( 1755 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1756 Depth + 1), 1757 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1758 AR->getNoWrapFlags()); 1759 } 1760 // Similar to above, only this time treat the step value as signed. 1761 // This covers loops that count down. 1762 OperandExtendedAdd = 1763 getAddExpr(WideStart, 1764 getMulExpr(WideMaxBECount, 1765 getSignExtendExpr(Step, WideTy, Depth + 1), 1766 SCEV::FlagAnyWrap, Depth + 1), 1767 SCEV::FlagAnyWrap, Depth + 1); 1768 if (ZAdd == OperandExtendedAdd) { 1769 // Cache knowledge of AR NW, which is propagated to this AddRec. 1770 // Negative step causes unsigned wrap, but it still can't self-wrap. 1771 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1772 // Return the expression with the addrec on the outside. 1773 return getAddRecExpr( 1774 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1775 Depth + 1), 1776 getSignExtendExpr(Step, Ty, Depth + 1), L, 1777 AR->getNoWrapFlags()); 1778 } 1779 } 1780 } 1781 1782 // Normally, in the cases we can prove no-overflow via a 1783 // backedge guarding condition, we can also compute a backedge 1784 // taken count for the loop. The exceptions are assumptions and 1785 // guards present in the loop -- SCEV is not great at exploiting 1786 // these to compute max backedge taken counts, but can still use 1787 // these to prove lack of overflow. Use this fact to avoid 1788 // doing extra work that may not pay off. 1789 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1790 !AC.assumptions().empty()) { 1791 // If the backedge is guarded by a comparison with the pre-inc 1792 // value the addrec is safe. Also, if the entry is guarded by 1793 // a comparison with the start value and the backedge is 1794 // guarded by a comparison with the post-inc value, the addrec 1795 // is safe. 1796 if (isKnownPositive(Step)) { 1797 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1798 getUnsignedRangeMax(Step)); 1799 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1800 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1801 // Cache knowledge of AR NUW, which is propagated to this 1802 // AddRec. 1803 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1804 // Return the expression with the addrec on the outside. 1805 return getAddRecExpr( 1806 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1807 Depth + 1), 1808 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1809 AR->getNoWrapFlags()); 1810 } 1811 } else if (isKnownNegative(Step)) { 1812 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1813 getSignedRangeMin(Step)); 1814 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1815 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1816 // Cache knowledge of AR NW, which is propagated to this 1817 // AddRec. Negative step causes unsigned wrap, but it 1818 // still can't self-wrap. 1819 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1820 // Return the expression with the addrec on the outside. 1821 return getAddRecExpr( 1822 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1823 Depth + 1), 1824 getSignExtendExpr(Step, Ty, Depth + 1), L, 1825 AR->getNoWrapFlags()); 1826 } 1827 } 1828 } 1829 1830 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1831 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1832 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1833 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1834 const APInt &C = SC->getAPInt(); 1835 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1836 if (D != 0) { 1837 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1838 const SCEV *SResidual = 1839 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1840 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1841 return getAddExpr(SZExtD, SZExtR, 1842 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1843 Depth + 1); 1844 } 1845 } 1846 1847 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1848 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1849 return getAddRecExpr( 1850 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1851 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1852 } 1853 } 1854 1855 // zext(A % B) --> zext(A) % zext(B) 1856 { 1857 const SCEV *LHS; 1858 const SCEV *RHS; 1859 if (matchURem(Op, LHS, RHS)) 1860 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1861 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1862 } 1863 1864 // zext(A / B) --> zext(A) / zext(B). 1865 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1866 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1867 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1868 1869 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1870 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1871 if (SA->hasNoUnsignedWrap()) { 1872 // If the addition does not unsign overflow then we can, by definition, 1873 // commute the zero extension with the addition operation. 1874 SmallVector<const SCEV *, 4> Ops; 1875 for (const auto *Op : SA->operands()) 1876 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1877 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1878 } 1879 1880 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1881 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1882 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1883 // 1884 // Often address arithmetics contain expressions like 1885 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1886 // This transformation is useful while proving that such expressions are 1887 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1888 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1889 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1890 if (D != 0) { 1891 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1892 const SCEV *SResidual = 1893 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1894 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1895 return getAddExpr(SZExtD, SZExtR, 1896 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1897 Depth + 1); 1898 } 1899 } 1900 } 1901 1902 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1903 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1904 if (SM->hasNoUnsignedWrap()) { 1905 // If the multiply does not unsign overflow then we can, by definition, 1906 // commute the zero extension with the multiply operation. 1907 SmallVector<const SCEV *, 4> Ops; 1908 for (const auto *Op : SM->operands()) 1909 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1910 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1911 } 1912 1913 // zext(2^K * (trunc X to iN)) to iM -> 1914 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1915 // 1916 // Proof: 1917 // 1918 // zext(2^K * (trunc X to iN)) to iM 1919 // = zext((trunc X to iN) << K) to iM 1920 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1921 // (because shl removes the top K bits) 1922 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1923 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1924 // 1925 if (SM->getNumOperands() == 2) 1926 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1927 if (MulLHS->getAPInt().isPowerOf2()) 1928 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1929 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1930 MulLHS->getAPInt().logBase2(); 1931 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1932 return getMulExpr( 1933 getZeroExtendExpr(MulLHS, Ty), 1934 getZeroExtendExpr( 1935 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1936 SCEV::FlagNUW, Depth + 1); 1937 } 1938 } 1939 1940 // The cast wasn't folded; create an explicit cast node. 1941 // Recompute the insert position, as it may have been invalidated. 1942 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1943 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1944 Op, Ty); 1945 UniqueSCEVs.InsertNode(S, IP); 1946 addToLoopUseLists(S); 1947 return S; 1948 } 1949 1950 const SCEV * 1951 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1952 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1953 "This is not an extending conversion!"); 1954 assert(isSCEVable(Ty) && 1955 "This is not a conversion to a SCEVable type!"); 1956 Ty = getEffectiveSCEVType(Ty); 1957 1958 // Fold if the operand is constant. 1959 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1960 return getConstant( 1961 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1962 1963 // sext(sext(x)) --> sext(x) 1964 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1965 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1966 1967 // sext(zext(x)) --> zext(x) 1968 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1969 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1970 1971 // Before doing any expensive analysis, check to see if we've already 1972 // computed a SCEV for this Op and Ty. 1973 FoldingSetNodeID ID; 1974 ID.AddInteger(scSignExtend); 1975 ID.AddPointer(Op); 1976 ID.AddPointer(Ty); 1977 void *IP = nullptr; 1978 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1979 // Limit recursion depth. 1980 if (Depth > MaxCastDepth) { 1981 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1982 Op, Ty); 1983 UniqueSCEVs.InsertNode(S, IP); 1984 addToLoopUseLists(S); 1985 return S; 1986 } 1987 1988 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1989 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1990 // It's possible the bits taken off by the truncate were all sign bits. If 1991 // so, we should be able to simplify this further. 1992 const SCEV *X = ST->getOperand(); 1993 ConstantRange CR = getSignedRange(X); 1994 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1995 unsigned NewBits = getTypeSizeInBits(Ty); 1996 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1997 CR.sextOrTrunc(NewBits))) 1998 return getTruncateOrSignExtend(X, Ty, Depth); 1999 } 2000 2001 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 2002 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 2003 if (SA->hasNoSignedWrap()) { 2004 // If the addition does not sign overflow then we can, by definition, 2005 // commute the sign extension with the addition operation. 2006 SmallVector<const SCEV *, 4> Ops; 2007 for (const auto *Op : SA->operands()) 2008 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 2009 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 2010 } 2011 2012 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 2013 // if D + (C - D + x + y + ...) could be proven to not signed wrap 2014 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 2015 // 2016 // For instance, this will bring two seemingly different expressions: 2017 // 1 + sext(5 + 20 * %x + 24 * %y) and 2018 // sext(6 + 20 * %x + 24 * %y) 2019 // to the same form: 2020 // 2 + sext(4 + 20 * %x + 24 * %y) 2021 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 2022 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 2023 if (D != 0) { 2024 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2025 const SCEV *SResidual = 2026 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2027 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2028 return getAddExpr(SSExtD, SSExtR, 2029 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2030 Depth + 1); 2031 } 2032 } 2033 } 2034 // If the input value is a chrec scev, and we can prove that the value 2035 // did not overflow the old, smaller, value, we can sign extend all of the 2036 // operands (often constants). This allows analysis of something like 2037 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2038 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2039 if (AR->isAffine()) { 2040 const SCEV *Start = AR->getStart(); 2041 const SCEV *Step = AR->getStepRecurrence(*this); 2042 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2043 const Loop *L = AR->getLoop(); 2044 2045 if (!AR->hasNoSignedWrap()) { 2046 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2047 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2048 } 2049 2050 // If we have special knowledge that this addrec won't overflow, 2051 // we don't need to do any further analysis. 2052 if (AR->hasNoSignedWrap()) 2053 return getAddRecExpr( 2054 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2055 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2056 2057 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2058 // Note that this serves two purposes: It filters out loops that are 2059 // simply not analyzable, and it covers the case where this code is 2060 // being called from within backedge-taken count analysis, such that 2061 // attempting to ask for the backedge-taken count would likely result 2062 // in infinite recursion. In the later case, the analysis code will 2063 // cope with a conservative value, and it will take care to purge 2064 // that value once it has finished. 2065 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2066 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2067 // Manually compute the final value for AR, checking for 2068 // overflow. 2069 2070 // Check whether the backedge-taken count can be losslessly casted to 2071 // the addrec's type. The count is always unsigned. 2072 const SCEV *CastedMaxBECount = 2073 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2074 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2075 CastedMaxBECount, MaxBECount->getType(), Depth); 2076 if (MaxBECount == RecastedMaxBECount) { 2077 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2078 // Check whether Start+Step*MaxBECount has no signed overflow. 2079 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2080 SCEV::FlagAnyWrap, Depth + 1); 2081 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2082 SCEV::FlagAnyWrap, 2083 Depth + 1), 2084 WideTy, Depth + 1); 2085 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2086 const SCEV *WideMaxBECount = 2087 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2088 const SCEV *OperandExtendedAdd = 2089 getAddExpr(WideStart, 2090 getMulExpr(WideMaxBECount, 2091 getSignExtendExpr(Step, WideTy, Depth + 1), 2092 SCEV::FlagAnyWrap, Depth + 1), 2093 SCEV::FlagAnyWrap, Depth + 1); 2094 if (SAdd == OperandExtendedAdd) { 2095 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2096 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2097 // Return the expression with the addrec on the outside. 2098 return getAddRecExpr( 2099 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2100 Depth + 1), 2101 getSignExtendExpr(Step, Ty, Depth + 1), L, 2102 AR->getNoWrapFlags()); 2103 } 2104 // Similar to above, only this time treat the step value as unsigned. 2105 // This covers loops that count up with an unsigned step. 2106 OperandExtendedAdd = 2107 getAddExpr(WideStart, 2108 getMulExpr(WideMaxBECount, 2109 getZeroExtendExpr(Step, WideTy, Depth + 1), 2110 SCEV::FlagAnyWrap, Depth + 1), 2111 SCEV::FlagAnyWrap, Depth + 1); 2112 if (SAdd == OperandExtendedAdd) { 2113 // If AR wraps around then 2114 // 2115 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2116 // => SAdd != OperandExtendedAdd 2117 // 2118 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2119 // (SAdd == OperandExtendedAdd => AR is NW) 2120 2121 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2122 2123 // Return the expression with the addrec on the outside. 2124 return getAddRecExpr( 2125 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2126 Depth + 1), 2127 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2128 AR->getNoWrapFlags()); 2129 } 2130 } 2131 } 2132 2133 // Normally, in the cases we can prove no-overflow via a 2134 // backedge guarding condition, we can also compute a backedge 2135 // taken count for the loop. The exceptions are assumptions and 2136 // guards present in the loop -- SCEV is not great at exploiting 2137 // these to compute max backedge taken counts, but can still use 2138 // these to prove lack of overflow. Use this fact to avoid 2139 // doing extra work that may not pay off. 2140 2141 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2142 !AC.assumptions().empty()) { 2143 // If the backedge is guarded by a comparison with the pre-inc 2144 // value the addrec is safe. Also, if the entry is guarded by 2145 // a comparison with the start value and the backedge is 2146 // guarded by a comparison with the post-inc value, the addrec 2147 // is safe. 2148 ICmpInst::Predicate Pred; 2149 const SCEV *OverflowLimit = 2150 getSignedOverflowLimitForStep(Step, &Pred, this); 2151 if (OverflowLimit && 2152 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2153 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2154 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2155 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2156 return getAddRecExpr( 2157 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2158 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2159 } 2160 } 2161 2162 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2163 // if D + (C - D + Step * n) could be proven to not signed wrap 2164 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2165 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2166 const APInt &C = SC->getAPInt(); 2167 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2168 if (D != 0) { 2169 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2170 const SCEV *SResidual = 2171 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2172 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2173 return getAddExpr(SSExtD, SSExtR, 2174 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2175 Depth + 1); 2176 } 2177 } 2178 2179 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2180 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2181 return getAddRecExpr( 2182 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2183 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2184 } 2185 } 2186 2187 // If the input value is provably positive and we could not simplify 2188 // away the sext build a zext instead. 2189 if (isKnownNonNegative(Op)) 2190 return getZeroExtendExpr(Op, Ty, Depth + 1); 2191 2192 // The cast wasn't folded; create an explicit cast node. 2193 // Recompute the insert position, as it may have been invalidated. 2194 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2195 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2196 Op, Ty); 2197 UniqueSCEVs.InsertNode(S, IP); 2198 addToLoopUseLists(S); 2199 return S; 2200 } 2201 2202 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2203 /// unspecified bits out to the given type. 2204 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2205 Type *Ty) { 2206 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2207 "This is not an extending conversion!"); 2208 assert(isSCEVable(Ty) && 2209 "This is not a conversion to a SCEVable type!"); 2210 Ty = getEffectiveSCEVType(Ty); 2211 2212 // Sign-extend negative constants. 2213 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2214 if (SC->getAPInt().isNegative()) 2215 return getSignExtendExpr(Op, Ty); 2216 2217 // Peel off a truncate cast. 2218 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2219 const SCEV *NewOp = T->getOperand(); 2220 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2221 return getAnyExtendExpr(NewOp, Ty); 2222 return getTruncateOrNoop(NewOp, Ty); 2223 } 2224 2225 // Next try a zext cast. If the cast is folded, use it. 2226 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2227 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2228 return ZExt; 2229 2230 // Next try a sext cast. If the cast is folded, use it. 2231 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2232 if (!isa<SCEVSignExtendExpr>(SExt)) 2233 return SExt; 2234 2235 // Force the cast to be folded into the operands of an addrec. 2236 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2237 SmallVector<const SCEV *, 4> Ops; 2238 for (const SCEV *Op : AR->operands()) 2239 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2240 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2241 } 2242 2243 // If the expression is obviously signed, use the sext cast value. 2244 if (isa<SCEVSMaxExpr>(Op)) 2245 return SExt; 2246 2247 // Absent any other information, use the zext cast value. 2248 return ZExt; 2249 } 2250 2251 /// Process the given Ops list, which is a list of operands to be added under 2252 /// the given scale, update the given map. This is a helper function for 2253 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2254 /// that would form an add expression like this: 2255 /// 2256 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2257 /// 2258 /// where A and B are constants, update the map with these values: 2259 /// 2260 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2261 /// 2262 /// and add 13 + A*B*29 to AccumulatedConstant. 2263 /// This will allow getAddRecExpr to produce this: 2264 /// 2265 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2266 /// 2267 /// This form often exposes folding opportunities that are hidden in 2268 /// the original operand list. 2269 /// 2270 /// Return true iff it appears that any interesting folding opportunities 2271 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2272 /// the common case where no interesting opportunities are present, and 2273 /// is also used as a check to avoid infinite recursion. 2274 static bool 2275 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2276 SmallVectorImpl<const SCEV *> &NewOps, 2277 APInt &AccumulatedConstant, 2278 const SCEV *const *Ops, size_t NumOperands, 2279 const APInt &Scale, 2280 ScalarEvolution &SE) { 2281 bool Interesting = false; 2282 2283 // Iterate over the add operands. They are sorted, with constants first. 2284 unsigned i = 0; 2285 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2286 ++i; 2287 // Pull a buried constant out to the outside. 2288 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2289 Interesting = true; 2290 AccumulatedConstant += Scale * C->getAPInt(); 2291 } 2292 2293 // Next comes everything else. We're especially interested in multiplies 2294 // here, but they're in the middle, so just visit the rest with one loop. 2295 for (; i != NumOperands; ++i) { 2296 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2297 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2298 APInt NewScale = 2299 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2300 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2301 // A multiplication of a constant with another add; recurse. 2302 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2303 Interesting |= 2304 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2305 Add->op_begin(), Add->getNumOperands(), 2306 NewScale, SE); 2307 } else { 2308 // A multiplication of a constant with some other value. Update 2309 // the map. 2310 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2311 const SCEV *Key = SE.getMulExpr(MulOps); 2312 auto Pair = M.insert({Key, NewScale}); 2313 if (Pair.second) { 2314 NewOps.push_back(Pair.first->first); 2315 } else { 2316 Pair.first->second += NewScale; 2317 // The map already had an entry for this value, which may indicate 2318 // a folding opportunity. 2319 Interesting = true; 2320 } 2321 } 2322 } else { 2323 // An ordinary operand. Update the map. 2324 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2325 M.insert({Ops[i], Scale}); 2326 if (Pair.second) { 2327 NewOps.push_back(Pair.first->first); 2328 } else { 2329 Pair.first->second += Scale; 2330 // The map already had an entry for this value, which may indicate 2331 // a folding opportunity. 2332 Interesting = true; 2333 } 2334 } 2335 } 2336 2337 return Interesting; 2338 } 2339 2340 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2341 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2342 // can't-overflow flags for the operation if possible. 2343 static SCEV::NoWrapFlags 2344 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2345 const ArrayRef<const SCEV *> Ops, 2346 SCEV::NoWrapFlags Flags) { 2347 using namespace std::placeholders; 2348 2349 using OBO = OverflowingBinaryOperator; 2350 2351 bool CanAnalyze = 2352 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2353 (void)CanAnalyze; 2354 assert(CanAnalyze && "don't call from other places!"); 2355 2356 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2357 SCEV::NoWrapFlags SignOrUnsignWrap = 2358 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2359 2360 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2361 auto IsKnownNonNegative = [&](const SCEV *S) { 2362 return SE->isKnownNonNegative(S); 2363 }; 2364 2365 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2366 Flags = 2367 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2368 2369 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2370 2371 if (SignOrUnsignWrap != SignOrUnsignMask && 2372 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2373 isa<SCEVConstant>(Ops[0])) { 2374 2375 auto Opcode = [&] { 2376 switch (Type) { 2377 case scAddExpr: 2378 return Instruction::Add; 2379 case scMulExpr: 2380 return Instruction::Mul; 2381 default: 2382 llvm_unreachable("Unexpected SCEV op."); 2383 } 2384 }(); 2385 2386 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2387 2388 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2389 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2390 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2391 Opcode, C, OBO::NoSignedWrap); 2392 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2393 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2394 } 2395 2396 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2397 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2398 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2399 Opcode, C, OBO::NoUnsignedWrap); 2400 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2401 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2402 } 2403 } 2404 2405 return Flags; 2406 } 2407 2408 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2409 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2410 } 2411 2412 /// Get a canonical add expression, or something simpler if possible. 2413 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2414 SCEV::NoWrapFlags Flags, 2415 unsigned Depth) { 2416 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2417 "only nuw or nsw allowed"); 2418 assert(!Ops.empty() && "Cannot get empty add!"); 2419 if (Ops.size() == 1) return Ops[0]; 2420 #ifndef NDEBUG 2421 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2422 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2423 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2424 "SCEVAddExpr operand types don't match!"); 2425 #endif 2426 2427 // Sort by complexity, this groups all similar expression types together. 2428 GroupByComplexity(Ops, &LI, DT); 2429 2430 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2431 2432 // If there are any constants, fold them together. 2433 unsigned Idx = 0; 2434 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2435 ++Idx; 2436 assert(Idx < Ops.size()); 2437 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2438 // We found two constants, fold them together! 2439 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2440 if (Ops.size() == 2) return Ops[0]; 2441 Ops.erase(Ops.begin()+1); // Erase the folded element 2442 LHSC = cast<SCEVConstant>(Ops[0]); 2443 } 2444 2445 // If we are left with a constant zero being added, strip it off. 2446 if (LHSC->getValue()->isZero()) { 2447 Ops.erase(Ops.begin()); 2448 --Idx; 2449 } 2450 2451 if (Ops.size() == 1) return Ops[0]; 2452 } 2453 2454 // Limit recursion calls depth. 2455 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2456 return getOrCreateAddExpr(Ops, Flags); 2457 2458 // Okay, check to see if the same value occurs in the operand list more than 2459 // once. If so, merge them together into an multiply expression. Since we 2460 // sorted the list, these values are required to be adjacent. 2461 Type *Ty = Ops[0]->getType(); 2462 bool FoundMatch = false; 2463 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2464 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2465 // Scan ahead to count how many equal operands there are. 2466 unsigned Count = 2; 2467 while (i+Count != e && Ops[i+Count] == Ops[i]) 2468 ++Count; 2469 // Merge the values into a multiply. 2470 const SCEV *Scale = getConstant(Ty, Count); 2471 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2472 if (Ops.size() == Count) 2473 return Mul; 2474 Ops[i] = Mul; 2475 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2476 --i; e -= Count - 1; 2477 FoundMatch = true; 2478 } 2479 if (FoundMatch) 2480 return getAddExpr(Ops, Flags, Depth + 1); 2481 2482 // Check for truncates. If all the operands are truncated from the same 2483 // type, see if factoring out the truncate would permit the result to be 2484 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2485 // if the contents of the resulting outer trunc fold to something simple. 2486 auto FindTruncSrcType = [&]() -> Type * { 2487 // We're ultimately looking to fold an addrec of truncs and muls of only 2488 // constants and truncs, so if we find any other types of SCEV 2489 // as operands of the addrec then we bail and return nullptr here. 2490 // Otherwise, we return the type of the operand of a trunc that we find. 2491 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2492 return T->getOperand()->getType(); 2493 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2494 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2495 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2496 return T->getOperand()->getType(); 2497 } 2498 return nullptr; 2499 }; 2500 if (auto *SrcType = FindTruncSrcType()) { 2501 SmallVector<const SCEV *, 8> LargeOps; 2502 bool Ok = true; 2503 // Check all the operands to see if they can be represented in the 2504 // source type of the truncate. 2505 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2506 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2507 if (T->getOperand()->getType() != SrcType) { 2508 Ok = false; 2509 break; 2510 } 2511 LargeOps.push_back(T->getOperand()); 2512 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2513 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2514 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2515 SmallVector<const SCEV *, 8> LargeMulOps; 2516 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2517 if (const SCEVTruncateExpr *T = 2518 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2519 if (T->getOperand()->getType() != SrcType) { 2520 Ok = false; 2521 break; 2522 } 2523 LargeMulOps.push_back(T->getOperand()); 2524 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2525 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2526 } else { 2527 Ok = false; 2528 break; 2529 } 2530 } 2531 if (Ok) 2532 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2533 } else { 2534 Ok = false; 2535 break; 2536 } 2537 } 2538 if (Ok) { 2539 // Evaluate the expression in the larger type. 2540 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2541 // If it folds to something simple, use it. Otherwise, don't. 2542 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2543 return getTruncateExpr(Fold, Ty); 2544 } 2545 } 2546 2547 // Skip past any other cast SCEVs. 2548 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2549 ++Idx; 2550 2551 // If there are add operands they would be next. 2552 if (Idx < Ops.size()) { 2553 bool DeletedAdd = false; 2554 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2555 if (Ops.size() > AddOpsInlineThreshold || 2556 Add->getNumOperands() > AddOpsInlineThreshold) 2557 break; 2558 // If we have an add, expand the add operands onto the end of the operands 2559 // list. 2560 Ops.erase(Ops.begin()+Idx); 2561 Ops.append(Add->op_begin(), Add->op_end()); 2562 DeletedAdd = true; 2563 } 2564 2565 // If we deleted at least one add, we added operands to the end of the list, 2566 // and they are not necessarily sorted. Recurse to resort and resimplify 2567 // any operands we just acquired. 2568 if (DeletedAdd) 2569 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2570 } 2571 2572 // Skip over the add expression until we get to a multiply. 2573 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2574 ++Idx; 2575 2576 // Check to see if there are any folding opportunities present with 2577 // operands multiplied by constant values. 2578 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2579 uint64_t BitWidth = getTypeSizeInBits(Ty); 2580 DenseMap<const SCEV *, APInt> M; 2581 SmallVector<const SCEV *, 8> NewOps; 2582 APInt AccumulatedConstant(BitWidth, 0); 2583 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2584 Ops.data(), Ops.size(), 2585 APInt(BitWidth, 1), *this)) { 2586 struct APIntCompare { 2587 bool operator()(const APInt &LHS, const APInt &RHS) const { 2588 return LHS.ult(RHS); 2589 } 2590 }; 2591 2592 // Some interesting folding opportunity is present, so its worthwhile to 2593 // re-generate the operands list. Group the operands by constant scale, 2594 // to avoid multiplying by the same constant scale multiple times. 2595 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2596 for (const SCEV *NewOp : NewOps) 2597 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2598 // Re-generate the operands list. 2599 Ops.clear(); 2600 if (AccumulatedConstant != 0) 2601 Ops.push_back(getConstant(AccumulatedConstant)); 2602 for (auto &MulOp : MulOpLists) 2603 if (MulOp.first != 0) 2604 Ops.push_back(getMulExpr( 2605 getConstant(MulOp.first), 2606 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2607 SCEV::FlagAnyWrap, Depth + 1)); 2608 if (Ops.empty()) 2609 return getZero(Ty); 2610 if (Ops.size() == 1) 2611 return Ops[0]; 2612 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2613 } 2614 } 2615 2616 // If we are adding something to a multiply expression, make sure the 2617 // something is not already an operand of the multiply. If so, merge it into 2618 // the multiply. 2619 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2620 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2621 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2622 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2623 if (isa<SCEVConstant>(MulOpSCEV)) 2624 continue; 2625 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2626 if (MulOpSCEV == Ops[AddOp]) { 2627 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2628 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2629 if (Mul->getNumOperands() != 2) { 2630 // If the multiply has more than two operands, we must get the 2631 // Y*Z term. 2632 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2633 Mul->op_begin()+MulOp); 2634 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2635 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2636 } 2637 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2638 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2639 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2640 SCEV::FlagAnyWrap, Depth + 1); 2641 if (Ops.size() == 2) return OuterMul; 2642 if (AddOp < Idx) { 2643 Ops.erase(Ops.begin()+AddOp); 2644 Ops.erase(Ops.begin()+Idx-1); 2645 } else { 2646 Ops.erase(Ops.begin()+Idx); 2647 Ops.erase(Ops.begin()+AddOp-1); 2648 } 2649 Ops.push_back(OuterMul); 2650 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2651 } 2652 2653 // Check this multiply against other multiplies being added together. 2654 for (unsigned OtherMulIdx = Idx+1; 2655 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2656 ++OtherMulIdx) { 2657 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2658 // If MulOp occurs in OtherMul, we can fold the two multiplies 2659 // together. 2660 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2661 OMulOp != e; ++OMulOp) 2662 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2663 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2664 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2665 if (Mul->getNumOperands() != 2) { 2666 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2667 Mul->op_begin()+MulOp); 2668 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2669 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2670 } 2671 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2672 if (OtherMul->getNumOperands() != 2) { 2673 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2674 OtherMul->op_begin()+OMulOp); 2675 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2676 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2677 } 2678 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2679 const SCEV *InnerMulSum = 2680 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2681 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2682 SCEV::FlagAnyWrap, Depth + 1); 2683 if (Ops.size() == 2) return OuterMul; 2684 Ops.erase(Ops.begin()+Idx); 2685 Ops.erase(Ops.begin()+OtherMulIdx-1); 2686 Ops.push_back(OuterMul); 2687 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2688 } 2689 } 2690 } 2691 } 2692 2693 // If there are any add recurrences in the operands list, see if any other 2694 // added values are loop invariant. If so, we can fold them into the 2695 // recurrence. 2696 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2697 ++Idx; 2698 2699 // Scan over all recurrences, trying to fold loop invariants into them. 2700 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2701 // Scan all of the other operands to this add and add them to the vector if 2702 // they are loop invariant w.r.t. the recurrence. 2703 SmallVector<const SCEV *, 8> LIOps; 2704 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2705 const Loop *AddRecLoop = AddRec->getLoop(); 2706 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2707 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2708 LIOps.push_back(Ops[i]); 2709 Ops.erase(Ops.begin()+i); 2710 --i; --e; 2711 } 2712 2713 // If we found some loop invariants, fold them into the recurrence. 2714 if (!LIOps.empty()) { 2715 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2716 LIOps.push_back(AddRec->getStart()); 2717 2718 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2719 AddRec->op_end()); 2720 // This follows from the fact that the no-wrap flags on the outer add 2721 // expression are applicable on the 0th iteration, when the add recurrence 2722 // will be equal to its start value. 2723 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2724 2725 // Build the new addrec. Propagate the NUW and NSW flags if both the 2726 // outer add and the inner addrec are guaranteed to have no overflow. 2727 // Always propagate NW. 2728 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2729 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2730 2731 // If all of the other operands were loop invariant, we are done. 2732 if (Ops.size() == 1) return NewRec; 2733 2734 // Otherwise, add the folded AddRec by the non-invariant parts. 2735 for (unsigned i = 0;; ++i) 2736 if (Ops[i] == AddRec) { 2737 Ops[i] = NewRec; 2738 break; 2739 } 2740 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2741 } 2742 2743 // Okay, if there weren't any loop invariants to be folded, check to see if 2744 // there are multiple AddRec's with the same loop induction variable being 2745 // added together. If so, we can fold them. 2746 for (unsigned OtherIdx = Idx+1; 2747 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2748 ++OtherIdx) { 2749 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2750 // so that the 1st found AddRecExpr is dominated by all others. 2751 assert(DT.dominates( 2752 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2753 AddRec->getLoop()->getHeader()) && 2754 "AddRecExprs are not sorted in reverse dominance order?"); 2755 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2756 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2757 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2758 AddRec->op_end()); 2759 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2760 ++OtherIdx) { 2761 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2762 if (OtherAddRec->getLoop() == AddRecLoop) { 2763 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2764 i != e; ++i) { 2765 if (i >= AddRecOps.size()) { 2766 AddRecOps.append(OtherAddRec->op_begin()+i, 2767 OtherAddRec->op_end()); 2768 break; 2769 } 2770 SmallVector<const SCEV *, 2> TwoOps = { 2771 AddRecOps[i], OtherAddRec->getOperand(i)}; 2772 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2773 } 2774 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2775 } 2776 } 2777 // Step size has changed, so we cannot guarantee no self-wraparound. 2778 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2779 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2780 } 2781 } 2782 2783 // Otherwise couldn't fold anything into this recurrence. Move onto the 2784 // next one. 2785 } 2786 2787 // Okay, it looks like we really DO need an add expr. Check to see if we 2788 // already have one, otherwise create a new one. 2789 return getOrCreateAddExpr(Ops, Flags); 2790 } 2791 2792 const SCEV * 2793 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2794 SCEV::NoWrapFlags Flags) { 2795 FoldingSetNodeID ID; 2796 ID.AddInteger(scAddExpr); 2797 for (const SCEV *Op : Ops) 2798 ID.AddPointer(Op); 2799 void *IP = nullptr; 2800 SCEVAddExpr *S = 2801 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2802 if (!S) { 2803 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2804 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2805 S = new (SCEVAllocator) 2806 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2807 UniqueSCEVs.InsertNode(S, IP); 2808 addToLoopUseLists(S); 2809 } 2810 S->setNoWrapFlags(Flags); 2811 return S; 2812 } 2813 2814 const SCEV * 2815 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2816 const Loop *L, SCEV::NoWrapFlags Flags) { 2817 FoldingSetNodeID ID; 2818 ID.AddInteger(scAddRecExpr); 2819 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2820 ID.AddPointer(Ops[i]); 2821 ID.AddPointer(L); 2822 void *IP = nullptr; 2823 SCEVAddRecExpr *S = 2824 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2825 if (!S) { 2826 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2827 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2828 S = new (SCEVAllocator) 2829 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2830 UniqueSCEVs.InsertNode(S, IP); 2831 addToLoopUseLists(S); 2832 } 2833 S->setNoWrapFlags(Flags); 2834 return S; 2835 } 2836 2837 const SCEV * 2838 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2839 SCEV::NoWrapFlags Flags) { 2840 FoldingSetNodeID ID; 2841 ID.AddInteger(scMulExpr); 2842 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2843 ID.AddPointer(Ops[i]); 2844 void *IP = nullptr; 2845 SCEVMulExpr *S = 2846 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2847 if (!S) { 2848 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2849 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2850 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2851 O, Ops.size()); 2852 UniqueSCEVs.InsertNode(S, IP); 2853 addToLoopUseLists(S); 2854 } 2855 S->setNoWrapFlags(Flags); 2856 return S; 2857 } 2858 2859 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2860 uint64_t k = i*j; 2861 if (j > 1 && k / j != i) Overflow = true; 2862 return k; 2863 } 2864 2865 /// Compute the result of "n choose k", the binomial coefficient. If an 2866 /// intermediate computation overflows, Overflow will be set and the return will 2867 /// be garbage. Overflow is not cleared on absence of overflow. 2868 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2869 // We use the multiplicative formula: 2870 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2871 // At each iteration, we take the n-th term of the numeral and divide by the 2872 // (k-n)th term of the denominator. This division will always produce an 2873 // integral result, and helps reduce the chance of overflow in the 2874 // intermediate computations. However, we can still overflow even when the 2875 // final result would fit. 2876 2877 if (n == 0 || n == k) return 1; 2878 if (k > n) return 0; 2879 2880 if (k > n/2) 2881 k = n-k; 2882 2883 uint64_t r = 1; 2884 for (uint64_t i = 1; i <= k; ++i) { 2885 r = umul_ov(r, n-(i-1), Overflow); 2886 r /= i; 2887 } 2888 return r; 2889 } 2890 2891 /// Determine if any of the operands in this SCEV are a constant or if 2892 /// any of the add or multiply expressions in this SCEV contain a constant. 2893 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2894 struct FindConstantInAddMulChain { 2895 bool FoundConstant = false; 2896 2897 bool follow(const SCEV *S) { 2898 FoundConstant |= isa<SCEVConstant>(S); 2899 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2900 } 2901 2902 bool isDone() const { 2903 return FoundConstant; 2904 } 2905 }; 2906 2907 FindConstantInAddMulChain F; 2908 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2909 ST.visitAll(StartExpr); 2910 return F.FoundConstant; 2911 } 2912 2913 /// Get a canonical multiply expression, or something simpler if possible. 2914 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2915 SCEV::NoWrapFlags Flags, 2916 unsigned Depth) { 2917 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2918 "only nuw or nsw allowed"); 2919 assert(!Ops.empty() && "Cannot get empty mul!"); 2920 if (Ops.size() == 1) return Ops[0]; 2921 #ifndef NDEBUG 2922 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2923 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2924 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2925 "SCEVMulExpr operand types don't match!"); 2926 #endif 2927 2928 // Sort by complexity, this groups all similar expression types together. 2929 GroupByComplexity(Ops, &LI, DT); 2930 2931 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2932 2933 // Limit recursion calls depth. 2934 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2935 return getOrCreateMulExpr(Ops, Flags); 2936 2937 // If there are any constants, fold them together. 2938 unsigned Idx = 0; 2939 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2940 2941 if (Ops.size() == 2) 2942 // C1*(C2+V) -> C1*C2 + C1*V 2943 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2944 // If any of Add's ops are Adds or Muls with a constant, apply this 2945 // transformation as well. 2946 // 2947 // TODO: There are some cases where this transformation is not 2948 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2949 // this transformation should be narrowed down. 2950 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2951 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2952 SCEV::FlagAnyWrap, Depth + 1), 2953 getMulExpr(LHSC, Add->getOperand(1), 2954 SCEV::FlagAnyWrap, Depth + 1), 2955 SCEV::FlagAnyWrap, Depth + 1); 2956 2957 ++Idx; 2958 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2959 // We found two constants, fold them together! 2960 ConstantInt *Fold = 2961 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2962 Ops[0] = getConstant(Fold); 2963 Ops.erase(Ops.begin()+1); // Erase the folded element 2964 if (Ops.size() == 1) return Ops[0]; 2965 LHSC = cast<SCEVConstant>(Ops[0]); 2966 } 2967 2968 // If we are left with a constant one being multiplied, strip it off. 2969 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2970 Ops.erase(Ops.begin()); 2971 --Idx; 2972 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2973 // If we have a multiply of zero, it will always be zero. 2974 return Ops[0]; 2975 } else if (Ops[0]->isAllOnesValue()) { 2976 // If we have a mul by -1 of an add, try distributing the -1 among the 2977 // add operands. 2978 if (Ops.size() == 2) { 2979 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2980 SmallVector<const SCEV *, 4> NewOps; 2981 bool AnyFolded = false; 2982 for (const SCEV *AddOp : Add->operands()) { 2983 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2984 Depth + 1); 2985 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2986 NewOps.push_back(Mul); 2987 } 2988 if (AnyFolded) 2989 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2990 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2991 // Negation preserves a recurrence's no self-wrap property. 2992 SmallVector<const SCEV *, 4> Operands; 2993 for (const SCEV *AddRecOp : AddRec->operands()) 2994 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2995 Depth + 1)); 2996 2997 return getAddRecExpr(Operands, AddRec->getLoop(), 2998 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2999 } 3000 } 3001 } 3002 3003 if (Ops.size() == 1) 3004 return Ops[0]; 3005 } 3006 3007 // Skip over the add expression until we get to a multiply. 3008 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3009 ++Idx; 3010 3011 // If there are mul operands inline them all into this expression. 3012 if (Idx < Ops.size()) { 3013 bool DeletedMul = false; 3014 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3015 if (Ops.size() > MulOpsInlineThreshold) 3016 break; 3017 // If we have an mul, expand the mul operands onto the end of the 3018 // operands list. 3019 Ops.erase(Ops.begin()+Idx); 3020 Ops.append(Mul->op_begin(), Mul->op_end()); 3021 DeletedMul = true; 3022 } 3023 3024 // If we deleted at least one mul, we added operands to the end of the 3025 // list, and they are not necessarily sorted. Recurse to resort and 3026 // resimplify any operands we just acquired. 3027 if (DeletedMul) 3028 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3029 } 3030 3031 // If there are any add recurrences in the operands list, see if any other 3032 // added values are loop invariant. If so, we can fold them into the 3033 // recurrence. 3034 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3035 ++Idx; 3036 3037 // Scan over all recurrences, trying to fold loop invariants into them. 3038 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3039 // Scan all of the other operands to this mul and add them to the vector 3040 // if they are loop invariant w.r.t. the recurrence. 3041 SmallVector<const SCEV *, 8> LIOps; 3042 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3043 const Loop *AddRecLoop = AddRec->getLoop(); 3044 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3045 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3046 LIOps.push_back(Ops[i]); 3047 Ops.erase(Ops.begin()+i); 3048 --i; --e; 3049 } 3050 3051 // If we found some loop invariants, fold them into the recurrence. 3052 if (!LIOps.empty()) { 3053 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3054 SmallVector<const SCEV *, 4> NewOps; 3055 NewOps.reserve(AddRec->getNumOperands()); 3056 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3057 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3058 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3059 SCEV::FlagAnyWrap, Depth + 1)); 3060 3061 // Build the new addrec. Propagate the NUW and NSW flags if both the 3062 // outer mul and the inner addrec are guaranteed to have no overflow. 3063 // 3064 // No self-wrap cannot be guaranteed after changing the step size, but 3065 // will be inferred if either NUW or NSW is true. 3066 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3067 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3068 3069 // If all of the other operands were loop invariant, we are done. 3070 if (Ops.size() == 1) return NewRec; 3071 3072 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3073 for (unsigned i = 0;; ++i) 3074 if (Ops[i] == AddRec) { 3075 Ops[i] = NewRec; 3076 break; 3077 } 3078 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3079 } 3080 3081 // Okay, if there weren't any loop invariants to be folded, check to see 3082 // if there are multiple AddRec's with the same loop induction variable 3083 // being multiplied together. If so, we can fold them. 3084 3085 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3086 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3087 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3088 // ]]],+,...up to x=2n}. 3089 // Note that the arguments to choose() are always integers with values 3090 // known at compile time, never SCEV objects. 3091 // 3092 // The implementation avoids pointless extra computations when the two 3093 // addrec's are of different length (mathematically, it's equivalent to 3094 // an infinite stream of zeros on the right). 3095 bool OpsModified = false; 3096 for (unsigned OtherIdx = Idx+1; 3097 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3098 ++OtherIdx) { 3099 const SCEVAddRecExpr *OtherAddRec = 3100 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3101 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3102 continue; 3103 3104 // Limit max number of arguments to avoid creation of unreasonably big 3105 // SCEVAddRecs with very complex operands. 3106 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3107 MaxAddRecSize || isHugeExpression(AddRec) || 3108 isHugeExpression(OtherAddRec)) 3109 continue; 3110 3111 bool Overflow = false; 3112 Type *Ty = AddRec->getType(); 3113 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3114 SmallVector<const SCEV*, 7> AddRecOps; 3115 for (int x = 0, xe = AddRec->getNumOperands() + 3116 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3117 SmallVector <const SCEV *, 7> SumOps; 3118 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3119 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3120 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3121 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3122 z < ze && !Overflow; ++z) { 3123 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3124 uint64_t Coeff; 3125 if (LargerThan64Bits) 3126 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3127 else 3128 Coeff = Coeff1*Coeff2; 3129 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3130 const SCEV *Term1 = AddRec->getOperand(y-z); 3131 const SCEV *Term2 = OtherAddRec->getOperand(z); 3132 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3133 SCEV::FlagAnyWrap, Depth + 1)); 3134 } 3135 } 3136 if (SumOps.empty()) 3137 SumOps.push_back(getZero(Ty)); 3138 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3139 } 3140 if (!Overflow) { 3141 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3142 SCEV::FlagAnyWrap); 3143 if (Ops.size() == 2) return NewAddRec; 3144 Ops[Idx] = NewAddRec; 3145 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3146 OpsModified = true; 3147 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3148 if (!AddRec) 3149 break; 3150 } 3151 } 3152 if (OpsModified) 3153 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3154 3155 // Otherwise couldn't fold anything into this recurrence. Move onto the 3156 // next one. 3157 } 3158 3159 // Okay, it looks like we really DO need an mul expr. Check to see if we 3160 // already have one, otherwise create a new one. 3161 return getOrCreateMulExpr(Ops, Flags); 3162 } 3163 3164 /// Represents an unsigned remainder expression based on unsigned division. 3165 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3166 const SCEV *RHS) { 3167 assert(getEffectiveSCEVType(LHS->getType()) == 3168 getEffectiveSCEVType(RHS->getType()) && 3169 "SCEVURemExpr operand types don't match!"); 3170 3171 // Short-circuit easy cases 3172 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3173 // If constant is one, the result is trivial 3174 if (RHSC->getValue()->isOne()) 3175 return getZero(LHS->getType()); // X urem 1 --> 0 3176 3177 // If constant is a power of two, fold into a zext(trunc(LHS)). 3178 if (RHSC->getAPInt().isPowerOf2()) { 3179 Type *FullTy = LHS->getType(); 3180 Type *TruncTy = 3181 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3182 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3183 } 3184 } 3185 3186 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3187 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3188 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3189 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3190 } 3191 3192 /// Get a canonical unsigned division expression, or something simpler if 3193 /// possible. 3194 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3195 const SCEV *RHS) { 3196 assert(getEffectiveSCEVType(LHS->getType()) == 3197 getEffectiveSCEVType(RHS->getType()) && 3198 "SCEVUDivExpr operand types don't match!"); 3199 3200 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3201 if (RHSC->getValue()->isOne()) 3202 return LHS; // X udiv 1 --> x 3203 // If the denominator is zero, the result of the udiv is undefined. Don't 3204 // try to analyze it, because the resolution chosen here may differ from 3205 // the resolution chosen in other parts of the compiler. 3206 if (!RHSC->getValue()->isZero()) { 3207 // Determine if the division can be folded into the operands of 3208 // its operands. 3209 // TODO: Generalize this to non-constants by using known-bits information. 3210 Type *Ty = LHS->getType(); 3211 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3212 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3213 // For non-power-of-two values, effectively round the value up to the 3214 // nearest power of two. 3215 if (!RHSC->getAPInt().isPowerOf2()) 3216 ++MaxShiftAmt; 3217 IntegerType *ExtTy = 3218 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3219 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3220 if (const SCEVConstant *Step = 3221 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3222 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3223 const APInt &StepInt = Step->getAPInt(); 3224 const APInt &DivInt = RHSC->getAPInt(); 3225 if (!StepInt.urem(DivInt) && 3226 getZeroExtendExpr(AR, ExtTy) == 3227 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3228 getZeroExtendExpr(Step, ExtTy), 3229 AR->getLoop(), SCEV::FlagAnyWrap)) { 3230 SmallVector<const SCEV *, 4> Operands; 3231 for (const SCEV *Op : AR->operands()) 3232 Operands.push_back(getUDivExpr(Op, RHS)); 3233 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3234 } 3235 /// Get a canonical UDivExpr for a recurrence. 3236 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3237 // We can currently only fold X%N if X is constant. 3238 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3239 if (StartC && !DivInt.urem(StepInt) && 3240 getZeroExtendExpr(AR, ExtTy) == 3241 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3242 getZeroExtendExpr(Step, ExtTy), 3243 AR->getLoop(), SCEV::FlagAnyWrap)) { 3244 const APInt &StartInt = StartC->getAPInt(); 3245 const APInt &StartRem = StartInt.urem(StepInt); 3246 if (StartRem != 0) 3247 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step, 3248 AR->getLoop(), SCEV::FlagNW); 3249 } 3250 } 3251 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3252 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3253 SmallVector<const SCEV *, 4> Operands; 3254 for (const SCEV *Op : M->operands()) 3255 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3256 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3257 // Find an operand that's safely divisible. 3258 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3259 const SCEV *Op = M->getOperand(i); 3260 const SCEV *Div = getUDivExpr(Op, RHSC); 3261 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3262 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3263 M->op_end()); 3264 Operands[i] = Div; 3265 return getMulExpr(Operands); 3266 } 3267 } 3268 } 3269 3270 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3271 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3272 if (auto *DivisorConstant = 3273 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3274 bool Overflow = false; 3275 APInt NewRHS = 3276 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3277 if (Overflow) { 3278 return getConstant(RHSC->getType(), 0, false); 3279 } 3280 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3281 } 3282 } 3283 3284 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3285 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3286 SmallVector<const SCEV *, 4> Operands; 3287 for (const SCEV *Op : A->operands()) 3288 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3289 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3290 Operands.clear(); 3291 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3292 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3293 if (isa<SCEVUDivExpr>(Op) || 3294 getMulExpr(Op, RHS) != A->getOperand(i)) 3295 break; 3296 Operands.push_back(Op); 3297 } 3298 if (Operands.size() == A->getNumOperands()) 3299 return getAddExpr(Operands); 3300 } 3301 } 3302 3303 // Fold if both operands are constant. 3304 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3305 Constant *LHSCV = LHSC->getValue(); 3306 Constant *RHSCV = RHSC->getValue(); 3307 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3308 RHSCV))); 3309 } 3310 } 3311 } 3312 3313 FoldingSetNodeID ID; 3314 ID.AddInteger(scUDivExpr); 3315 ID.AddPointer(LHS); 3316 ID.AddPointer(RHS); 3317 void *IP = nullptr; 3318 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3319 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3320 LHS, RHS); 3321 UniqueSCEVs.InsertNode(S, IP); 3322 addToLoopUseLists(S); 3323 return S; 3324 } 3325 3326 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3327 APInt A = C1->getAPInt().abs(); 3328 APInt B = C2->getAPInt().abs(); 3329 uint32_t ABW = A.getBitWidth(); 3330 uint32_t BBW = B.getBitWidth(); 3331 3332 if (ABW > BBW) 3333 B = B.zext(ABW); 3334 else if (ABW < BBW) 3335 A = A.zext(BBW); 3336 3337 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3338 } 3339 3340 /// Get a canonical unsigned division expression, or something simpler if 3341 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3342 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3343 /// it's not exact because the udiv may be clearing bits. 3344 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3345 const SCEV *RHS) { 3346 // TODO: we could try to find factors in all sorts of things, but for now we 3347 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3348 // end of this file for inspiration. 3349 3350 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3351 if (!Mul || !Mul->hasNoUnsignedWrap()) 3352 return getUDivExpr(LHS, RHS); 3353 3354 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3355 // If the mulexpr multiplies by a constant, then that constant must be the 3356 // first element of the mulexpr. 3357 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3358 if (LHSCst == RHSCst) { 3359 SmallVector<const SCEV *, 2> Operands; 3360 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3361 return getMulExpr(Operands); 3362 } 3363 3364 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3365 // that there's a factor provided by one of the other terms. We need to 3366 // check. 3367 APInt Factor = gcd(LHSCst, RHSCst); 3368 if (!Factor.isIntN(1)) { 3369 LHSCst = 3370 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3371 RHSCst = 3372 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3373 SmallVector<const SCEV *, 2> Operands; 3374 Operands.push_back(LHSCst); 3375 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3376 LHS = getMulExpr(Operands); 3377 RHS = RHSCst; 3378 Mul = dyn_cast<SCEVMulExpr>(LHS); 3379 if (!Mul) 3380 return getUDivExactExpr(LHS, RHS); 3381 } 3382 } 3383 } 3384 3385 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3386 if (Mul->getOperand(i) == RHS) { 3387 SmallVector<const SCEV *, 2> Operands; 3388 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3389 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3390 return getMulExpr(Operands); 3391 } 3392 } 3393 3394 return getUDivExpr(LHS, RHS); 3395 } 3396 3397 /// Get an add recurrence expression for the specified loop. Simplify the 3398 /// expression as much as possible. 3399 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3400 const Loop *L, 3401 SCEV::NoWrapFlags Flags) { 3402 SmallVector<const SCEV *, 4> Operands; 3403 Operands.push_back(Start); 3404 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3405 if (StepChrec->getLoop() == L) { 3406 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3407 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3408 } 3409 3410 Operands.push_back(Step); 3411 return getAddRecExpr(Operands, L, Flags); 3412 } 3413 3414 /// Get an add recurrence expression for the specified loop. Simplify the 3415 /// expression as much as possible. 3416 const SCEV * 3417 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3418 const Loop *L, SCEV::NoWrapFlags Flags) { 3419 if (Operands.size() == 1) return Operands[0]; 3420 #ifndef NDEBUG 3421 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3422 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3423 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3424 "SCEVAddRecExpr operand types don't match!"); 3425 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3426 assert(isLoopInvariant(Operands[i], L) && 3427 "SCEVAddRecExpr operand is not loop-invariant!"); 3428 #endif 3429 3430 if (Operands.back()->isZero()) { 3431 Operands.pop_back(); 3432 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3433 } 3434 3435 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3436 // use that information to infer NUW and NSW flags. However, computing a 3437 // BE count requires calling getAddRecExpr, so we may not yet have a 3438 // meaningful BE count at this point (and if we don't, we'd be stuck 3439 // with a SCEVCouldNotCompute as the cached BE count). 3440 3441 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3442 3443 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3444 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3445 const Loop *NestedLoop = NestedAR->getLoop(); 3446 if (L->contains(NestedLoop) 3447 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3448 : (!NestedLoop->contains(L) && 3449 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3450 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3451 NestedAR->op_end()); 3452 Operands[0] = NestedAR->getStart(); 3453 // AddRecs require their operands be loop-invariant with respect to their 3454 // loops. Don't perform this transformation if it would break this 3455 // requirement. 3456 bool AllInvariant = all_of( 3457 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3458 3459 if (AllInvariant) { 3460 // Create a recurrence for the outer loop with the same step size. 3461 // 3462 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3463 // inner recurrence has the same property. 3464 SCEV::NoWrapFlags OuterFlags = 3465 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3466 3467 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3468 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3469 return isLoopInvariant(Op, NestedLoop); 3470 }); 3471 3472 if (AllInvariant) { 3473 // Ok, both add recurrences are valid after the transformation. 3474 // 3475 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3476 // the outer recurrence has the same property. 3477 SCEV::NoWrapFlags InnerFlags = 3478 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3479 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3480 } 3481 } 3482 // Reset Operands to its original state. 3483 Operands[0] = NestedAR; 3484 } 3485 } 3486 3487 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3488 // already have one, otherwise create a new one. 3489 return getOrCreateAddRecExpr(Operands, L, Flags); 3490 } 3491 3492 const SCEV * 3493 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3494 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3495 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3496 // getSCEV(Base)->getType() has the same address space as Base->getType() 3497 // because SCEV::getType() preserves the address space. 3498 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType()); 3499 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3500 // instruction to its SCEV, because the Instruction may be guarded by control 3501 // flow and the no-overflow bits may not be valid for the expression in any 3502 // context. This can be fixed similarly to how these flags are handled for 3503 // adds. 3504 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3505 : SCEV::FlagAnyWrap; 3506 3507 const SCEV *TotalOffset = getZero(IntPtrTy); 3508 // The array size is unimportant. The first thing we do on CurTy is getting 3509 // its element type. 3510 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0); 3511 for (const SCEV *IndexExpr : IndexExprs) { 3512 // Compute the (potentially symbolic) offset in bytes for this index. 3513 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3514 // For a struct, add the member offset. 3515 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3516 unsigned FieldNo = Index->getZExtValue(); 3517 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo); 3518 3519 // Add the field offset to the running total offset. 3520 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3521 3522 // Update CurTy to the type of the field at Index. 3523 CurTy = STy->getTypeAtIndex(Index); 3524 } else { 3525 // Update CurTy to its element type. 3526 CurTy = cast<SequentialType>(CurTy)->getElementType(); 3527 // For an array, add the element offset, explicitly scaled. 3528 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy); 3529 // Getelementptr indices are signed. 3530 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy); 3531 3532 // Multiply the index by the element size to compute the element offset. 3533 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3534 3535 // Add the element offset to the running total offset. 3536 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3537 } 3538 } 3539 3540 // Add the total offset from all the GEP indices to the base. 3541 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3542 } 3543 3544 std::tuple<const SCEV *, FoldingSetNodeID, void *> 3545 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3546 ArrayRef<const SCEV *> Ops) { 3547 FoldingSetNodeID ID; 3548 void *IP = nullptr; 3549 ID.AddInteger(SCEVType); 3550 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3551 ID.AddPointer(Ops[i]); 3552 return std::tuple<const SCEV *, FoldingSetNodeID, void *>( 3553 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3554 } 3555 3556 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3557 SmallVectorImpl<const SCEV *> &Ops) { 3558 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3559 if (Ops.size() == 1) return Ops[0]; 3560 #ifndef NDEBUG 3561 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3562 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3563 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3564 "Operand types don't match!"); 3565 #endif 3566 3567 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3568 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3569 3570 // Sort by complexity, this groups all similar expression types together. 3571 GroupByComplexity(Ops, &LI, DT); 3572 3573 // Check if we have created the same expression before. 3574 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3575 return S; 3576 } 3577 3578 // If there are any constants, fold them together. 3579 unsigned Idx = 0; 3580 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3581 ++Idx; 3582 assert(Idx < Ops.size()); 3583 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3584 if (Kind == scSMaxExpr) 3585 return APIntOps::smax(LHS, RHS); 3586 else if (Kind == scSMinExpr) 3587 return APIntOps::smin(LHS, RHS); 3588 else if (Kind == scUMaxExpr) 3589 return APIntOps::umax(LHS, RHS); 3590 else if (Kind == scUMinExpr) 3591 return APIntOps::umin(LHS, RHS); 3592 llvm_unreachable("Unknown SCEV min/max opcode"); 3593 }; 3594 3595 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3596 // We found two constants, fold them together! 3597 ConstantInt *Fold = ConstantInt::get( 3598 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3599 Ops[0] = getConstant(Fold); 3600 Ops.erase(Ops.begin()+1); // Erase the folded element 3601 if (Ops.size() == 1) return Ops[0]; 3602 LHSC = cast<SCEVConstant>(Ops[0]); 3603 } 3604 3605 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3606 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3607 3608 if (IsMax ? IsMinV : IsMaxV) { 3609 // If we are left with a constant minimum(/maximum)-int, strip it off. 3610 Ops.erase(Ops.begin()); 3611 --Idx; 3612 } else if (IsMax ? IsMaxV : IsMinV) { 3613 // If we have a max(/min) with a constant maximum(/minimum)-int, 3614 // it will always be the extremum. 3615 return LHSC; 3616 } 3617 3618 if (Ops.size() == 1) return Ops[0]; 3619 } 3620 3621 // Find the first operation of the same kind 3622 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3623 ++Idx; 3624 3625 // Check to see if one of the operands is of the same kind. If so, expand its 3626 // operands onto our operand list, and recurse to simplify. 3627 if (Idx < Ops.size()) { 3628 bool DeletedAny = false; 3629 while (Ops[Idx]->getSCEVType() == Kind) { 3630 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3631 Ops.erase(Ops.begin()+Idx); 3632 Ops.append(SMME->op_begin(), SMME->op_end()); 3633 DeletedAny = true; 3634 } 3635 3636 if (DeletedAny) 3637 return getMinMaxExpr(Kind, Ops); 3638 } 3639 3640 // Okay, check to see if the same value occurs in the operand list twice. If 3641 // so, delete one. Since we sorted the list, these values are required to 3642 // be adjacent. 3643 llvm::CmpInst::Predicate GEPred = 3644 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3645 llvm::CmpInst::Predicate LEPred = 3646 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3647 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3648 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3649 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3650 if (Ops[i] == Ops[i + 1] || 3651 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3652 // X op Y op Y --> X op Y 3653 // X op Y --> X, if we know X, Y are ordered appropriately 3654 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3655 --i; 3656 --e; 3657 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3658 Ops[i + 1])) { 3659 // X op Y --> Y, if we know X, Y are ordered appropriately 3660 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3661 --i; 3662 --e; 3663 } 3664 } 3665 3666 if (Ops.size() == 1) return Ops[0]; 3667 3668 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3669 3670 // Okay, it looks like we really DO need an expr. Check to see if we 3671 // already have one, otherwise create a new one. 3672 const SCEV *ExistingSCEV; 3673 FoldingSetNodeID ID; 3674 void *IP; 3675 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3676 if (ExistingSCEV) 3677 return ExistingSCEV; 3678 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3679 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3680 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3681 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3682 3683 UniqueSCEVs.InsertNode(S, IP); 3684 addToLoopUseLists(S); 3685 return S; 3686 } 3687 3688 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3689 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3690 return getSMaxExpr(Ops); 3691 } 3692 3693 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3694 return getMinMaxExpr(scSMaxExpr, Ops); 3695 } 3696 3697 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3698 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3699 return getUMaxExpr(Ops); 3700 } 3701 3702 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3703 return getMinMaxExpr(scUMaxExpr, Ops); 3704 } 3705 3706 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3707 const SCEV *RHS) { 3708 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3709 return getSMinExpr(Ops); 3710 } 3711 3712 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3713 return getMinMaxExpr(scSMinExpr, Ops); 3714 } 3715 3716 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3717 const SCEV *RHS) { 3718 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3719 return getUMinExpr(Ops); 3720 } 3721 3722 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3723 return getMinMaxExpr(scUMinExpr, Ops); 3724 } 3725 3726 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3727 // We can bypass creating a target-independent 3728 // constant expression and then folding it back into a ConstantInt. 3729 // This is just a compile-time optimization. 3730 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3731 } 3732 3733 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3734 StructType *STy, 3735 unsigned FieldNo) { 3736 // We can bypass creating a target-independent 3737 // constant expression and then folding it back into a ConstantInt. 3738 // This is just a compile-time optimization. 3739 return getConstant( 3740 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3741 } 3742 3743 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3744 // Don't attempt to do anything other than create a SCEVUnknown object 3745 // here. createSCEV only calls getUnknown after checking for all other 3746 // interesting possibilities, and any other code that calls getUnknown 3747 // is doing so in order to hide a value from SCEV canonicalization. 3748 3749 FoldingSetNodeID ID; 3750 ID.AddInteger(scUnknown); 3751 ID.AddPointer(V); 3752 void *IP = nullptr; 3753 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3754 assert(cast<SCEVUnknown>(S)->getValue() == V && 3755 "Stale SCEVUnknown in uniquing map!"); 3756 return S; 3757 } 3758 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3759 FirstUnknown); 3760 FirstUnknown = cast<SCEVUnknown>(S); 3761 UniqueSCEVs.InsertNode(S, IP); 3762 return S; 3763 } 3764 3765 //===----------------------------------------------------------------------===// 3766 // Basic SCEV Analysis and PHI Idiom Recognition Code 3767 // 3768 3769 /// Test if values of the given type are analyzable within the SCEV 3770 /// framework. This primarily includes integer types, and it can optionally 3771 /// include pointer types if the ScalarEvolution class has access to 3772 /// target-specific information. 3773 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3774 // Integers and pointers are always SCEVable. 3775 return Ty->isIntOrPtrTy(); 3776 } 3777 3778 /// Return the size in bits of the specified type, for which isSCEVable must 3779 /// return true. 3780 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3781 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3782 if (Ty->isPointerTy()) 3783 return getDataLayout().getIndexTypeSizeInBits(Ty); 3784 return getDataLayout().getTypeSizeInBits(Ty); 3785 } 3786 3787 /// Return a type with the same bitwidth as the given type and which represents 3788 /// how SCEV will treat the given type, for which isSCEVable must return 3789 /// true. For pointer types, this is the pointer-sized integer type. 3790 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3791 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3792 3793 if (Ty->isIntegerTy()) 3794 return Ty; 3795 3796 // The only other support type is pointer. 3797 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3798 return getDataLayout().getIntPtrType(Ty); 3799 } 3800 3801 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3802 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3803 } 3804 3805 const SCEV *ScalarEvolution::getCouldNotCompute() { 3806 return CouldNotCompute.get(); 3807 } 3808 3809 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3810 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3811 auto *SU = dyn_cast<SCEVUnknown>(S); 3812 return SU && SU->getValue() == nullptr; 3813 }); 3814 3815 return !ContainsNulls; 3816 } 3817 3818 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3819 HasRecMapType::iterator I = HasRecMap.find(S); 3820 if (I != HasRecMap.end()) 3821 return I->second; 3822 3823 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3824 HasRecMap.insert({S, FoundAddRec}); 3825 return FoundAddRec; 3826 } 3827 3828 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3829 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3830 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3831 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3832 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3833 if (!Add) 3834 return {S, nullptr}; 3835 3836 if (Add->getNumOperands() != 2) 3837 return {S, nullptr}; 3838 3839 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3840 if (!ConstOp) 3841 return {S, nullptr}; 3842 3843 return {Add->getOperand(1), ConstOp->getValue()}; 3844 } 3845 3846 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3847 /// by the value and offset from any ValueOffsetPair in the set. 3848 SetVector<ScalarEvolution::ValueOffsetPair> * 3849 ScalarEvolution::getSCEVValues(const SCEV *S) { 3850 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3851 if (SI == ExprValueMap.end()) 3852 return nullptr; 3853 #ifndef NDEBUG 3854 if (VerifySCEVMap) { 3855 // Check there is no dangling Value in the set returned. 3856 for (const auto &VE : SI->second) 3857 assert(ValueExprMap.count(VE.first)); 3858 } 3859 #endif 3860 return &SI->second; 3861 } 3862 3863 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3864 /// cannot be used separately. eraseValueFromMap should be used to remove 3865 /// V from ValueExprMap and ExprValueMap at the same time. 3866 void ScalarEvolution::eraseValueFromMap(Value *V) { 3867 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3868 if (I != ValueExprMap.end()) { 3869 const SCEV *S = I->second; 3870 // Remove {V, 0} from the set of ExprValueMap[S] 3871 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3872 SV->remove({V, nullptr}); 3873 3874 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3875 const SCEV *Stripped; 3876 ConstantInt *Offset; 3877 std::tie(Stripped, Offset) = splitAddExpr(S); 3878 if (Offset != nullptr) { 3879 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3880 SV->remove({V, Offset}); 3881 } 3882 ValueExprMap.erase(V); 3883 } 3884 } 3885 3886 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3887 /// TODO: In reality it is better to check the poison recursively 3888 /// but this is better than nothing. 3889 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3890 if (auto *I = dyn_cast<Instruction>(V)) { 3891 if (isa<OverflowingBinaryOperator>(I)) { 3892 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3893 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3894 return true; 3895 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3896 return true; 3897 } 3898 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3899 return true; 3900 } 3901 return false; 3902 } 3903 3904 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3905 /// create a new one. 3906 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3907 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3908 3909 const SCEV *S = getExistingSCEV(V); 3910 if (S == nullptr) { 3911 S = createSCEV(V); 3912 // During PHI resolution, it is possible to create two SCEVs for the same 3913 // V, so it is needed to double check whether V->S is inserted into 3914 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3915 std::pair<ValueExprMapType::iterator, bool> Pair = 3916 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3917 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3918 ExprValueMap[S].insert({V, nullptr}); 3919 3920 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3921 // ExprValueMap. 3922 const SCEV *Stripped = S; 3923 ConstantInt *Offset = nullptr; 3924 std::tie(Stripped, Offset) = splitAddExpr(S); 3925 // If stripped is SCEVUnknown, don't bother to save 3926 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3927 // increase the complexity of the expansion code. 3928 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3929 // because it may generate add/sub instead of GEP in SCEV expansion. 3930 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3931 !isa<GetElementPtrInst>(V)) 3932 ExprValueMap[Stripped].insert({V, Offset}); 3933 } 3934 } 3935 return S; 3936 } 3937 3938 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3939 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3940 3941 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3942 if (I != ValueExprMap.end()) { 3943 const SCEV *S = I->second; 3944 if (checkValidity(S)) 3945 return S; 3946 eraseValueFromMap(V); 3947 forgetMemoizedResults(S); 3948 } 3949 return nullptr; 3950 } 3951 3952 /// Return a SCEV corresponding to -V = -1*V 3953 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3954 SCEV::NoWrapFlags Flags) { 3955 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3956 return getConstant( 3957 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3958 3959 Type *Ty = V->getType(); 3960 Ty = getEffectiveSCEVType(Ty); 3961 return getMulExpr( 3962 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 3963 } 3964 3965 /// If Expr computes ~A, return A else return nullptr 3966 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3967 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3968 if (!Add || Add->getNumOperands() != 2 || 3969 !Add->getOperand(0)->isAllOnesValue()) 3970 return nullptr; 3971 3972 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3973 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3974 !AddRHS->getOperand(0)->isAllOnesValue()) 3975 return nullptr; 3976 3977 return AddRHS->getOperand(1); 3978 } 3979 3980 /// Return a SCEV corresponding to ~V = -1-V 3981 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3982 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3983 return getConstant( 3984 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3985 3986 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3987 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3988 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3989 SmallVector<const SCEV *, 2> MatchedOperands; 3990 for (const SCEV *Operand : MME->operands()) { 3991 const SCEV *Matched = MatchNotExpr(Operand); 3992 if (!Matched) 3993 return (const SCEV *)nullptr; 3994 MatchedOperands.push_back(Matched); 3995 } 3996 return getMinMaxExpr( 3997 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 3998 MatchedOperands); 3999 }; 4000 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4001 return Replaced; 4002 } 4003 4004 Type *Ty = V->getType(); 4005 Ty = getEffectiveSCEVType(Ty); 4006 const SCEV *AllOnes = 4007 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4008 return getMinusSCEV(AllOnes, V); 4009 } 4010 4011 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4012 SCEV::NoWrapFlags Flags, 4013 unsigned Depth) { 4014 // Fast path: X - X --> 0. 4015 if (LHS == RHS) 4016 return getZero(LHS->getType()); 4017 4018 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4019 // makes it so that we cannot make much use of NUW. 4020 auto AddFlags = SCEV::FlagAnyWrap; 4021 const bool RHSIsNotMinSigned = 4022 !getSignedRangeMin(RHS).isMinSignedValue(); 4023 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4024 // Let M be the minimum representable signed value. Then (-1)*RHS 4025 // signed-wraps if and only if RHS is M. That can happen even for 4026 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4027 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4028 // (-1)*RHS, we need to prove that RHS != M. 4029 // 4030 // If LHS is non-negative and we know that LHS - RHS does not 4031 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4032 // either by proving that RHS > M or that LHS >= 0. 4033 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4034 AddFlags = SCEV::FlagNSW; 4035 } 4036 } 4037 4038 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4039 // RHS is NSW and LHS >= 0. 4040 // 4041 // The difficulty here is that the NSW flag may have been proven 4042 // relative to a loop that is to be found in a recurrence in LHS and 4043 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4044 // larger scope than intended. 4045 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4046 4047 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4048 } 4049 4050 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4051 unsigned Depth) { 4052 Type *SrcTy = V->getType(); 4053 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4054 "Cannot truncate or zero extend with non-integer arguments!"); 4055 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4056 return V; // No conversion 4057 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4058 return getTruncateExpr(V, Ty, Depth); 4059 return getZeroExtendExpr(V, Ty, Depth); 4060 } 4061 4062 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4063 unsigned Depth) { 4064 Type *SrcTy = V->getType(); 4065 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4066 "Cannot truncate or zero extend with non-integer arguments!"); 4067 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4068 return V; // No conversion 4069 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4070 return getTruncateExpr(V, Ty, Depth); 4071 return getSignExtendExpr(V, Ty, Depth); 4072 } 4073 4074 const SCEV * 4075 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4076 Type *SrcTy = V->getType(); 4077 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4078 "Cannot noop or zero extend with non-integer arguments!"); 4079 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4080 "getNoopOrZeroExtend cannot truncate!"); 4081 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4082 return V; // No conversion 4083 return getZeroExtendExpr(V, Ty); 4084 } 4085 4086 const SCEV * 4087 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4088 Type *SrcTy = V->getType(); 4089 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4090 "Cannot noop or sign extend with non-integer arguments!"); 4091 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4092 "getNoopOrSignExtend cannot truncate!"); 4093 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4094 return V; // No conversion 4095 return getSignExtendExpr(V, Ty); 4096 } 4097 4098 const SCEV * 4099 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4100 Type *SrcTy = V->getType(); 4101 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4102 "Cannot noop or any extend with non-integer arguments!"); 4103 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4104 "getNoopOrAnyExtend cannot truncate!"); 4105 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4106 return V; // No conversion 4107 return getAnyExtendExpr(V, Ty); 4108 } 4109 4110 const SCEV * 4111 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4112 Type *SrcTy = V->getType(); 4113 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4114 "Cannot truncate or noop with non-integer arguments!"); 4115 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4116 "getTruncateOrNoop cannot extend!"); 4117 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4118 return V; // No conversion 4119 return getTruncateExpr(V, Ty); 4120 } 4121 4122 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4123 const SCEV *RHS) { 4124 const SCEV *PromotedLHS = LHS; 4125 const SCEV *PromotedRHS = RHS; 4126 4127 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4128 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4129 else 4130 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4131 4132 return getUMaxExpr(PromotedLHS, PromotedRHS); 4133 } 4134 4135 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4136 const SCEV *RHS) { 4137 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4138 return getUMinFromMismatchedTypes(Ops); 4139 } 4140 4141 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4142 SmallVectorImpl<const SCEV *> &Ops) { 4143 assert(!Ops.empty() && "At least one operand must be!"); 4144 // Trivial case. 4145 if (Ops.size() == 1) 4146 return Ops[0]; 4147 4148 // Find the max type first. 4149 Type *MaxType = nullptr; 4150 for (auto *S : Ops) 4151 if (MaxType) 4152 MaxType = getWiderType(MaxType, S->getType()); 4153 else 4154 MaxType = S->getType(); 4155 4156 // Extend all ops to max type. 4157 SmallVector<const SCEV *, 2> PromotedOps; 4158 for (auto *S : Ops) 4159 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4160 4161 // Generate umin. 4162 return getUMinExpr(PromotedOps); 4163 } 4164 4165 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4166 // A pointer operand may evaluate to a nonpointer expression, such as null. 4167 if (!V->getType()->isPointerTy()) 4168 return V; 4169 4170 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4171 return getPointerBase(Cast->getOperand()); 4172 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4173 const SCEV *PtrOp = nullptr; 4174 for (const SCEV *NAryOp : NAry->operands()) { 4175 if (NAryOp->getType()->isPointerTy()) { 4176 // Cannot find the base of an expression with multiple pointer operands. 4177 if (PtrOp) 4178 return V; 4179 PtrOp = NAryOp; 4180 } 4181 } 4182 if (!PtrOp) 4183 return V; 4184 return getPointerBase(PtrOp); 4185 } 4186 return V; 4187 } 4188 4189 /// Push users of the given Instruction onto the given Worklist. 4190 static void 4191 PushDefUseChildren(Instruction *I, 4192 SmallVectorImpl<Instruction *> &Worklist) { 4193 // Push the def-use children onto the Worklist stack. 4194 for (User *U : I->users()) 4195 Worklist.push_back(cast<Instruction>(U)); 4196 } 4197 4198 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4199 SmallVector<Instruction *, 16> Worklist; 4200 PushDefUseChildren(PN, Worklist); 4201 4202 SmallPtrSet<Instruction *, 8> Visited; 4203 Visited.insert(PN); 4204 while (!Worklist.empty()) { 4205 Instruction *I = Worklist.pop_back_val(); 4206 if (!Visited.insert(I).second) 4207 continue; 4208 4209 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4210 if (It != ValueExprMap.end()) { 4211 const SCEV *Old = It->second; 4212 4213 // Short-circuit the def-use traversal if the symbolic name 4214 // ceases to appear in expressions. 4215 if (Old != SymName && !hasOperand(Old, SymName)) 4216 continue; 4217 4218 // SCEVUnknown for a PHI either means that it has an unrecognized 4219 // structure, it's a PHI that's in the progress of being computed 4220 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4221 // additional loop trip count information isn't going to change anything. 4222 // In the second case, createNodeForPHI will perform the necessary 4223 // updates on its own when it gets to that point. In the third, we do 4224 // want to forget the SCEVUnknown. 4225 if (!isa<PHINode>(I) || 4226 !isa<SCEVUnknown>(Old) || 4227 (I != PN && Old == SymName)) { 4228 eraseValueFromMap(It->first); 4229 forgetMemoizedResults(Old); 4230 } 4231 } 4232 4233 PushDefUseChildren(I, Worklist); 4234 } 4235 } 4236 4237 namespace { 4238 4239 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4240 /// expression in case its Loop is L. If it is not L then 4241 /// if IgnoreOtherLoops is true then use AddRec itself 4242 /// otherwise rewrite cannot be done. 4243 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4244 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4245 public: 4246 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4247 bool IgnoreOtherLoops = true) { 4248 SCEVInitRewriter Rewriter(L, SE); 4249 const SCEV *Result = Rewriter.visit(S); 4250 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4251 return SE.getCouldNotCompute(); 4252 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4253 ? SE.getCouldNotCompute() 4254 : Result; 4255 } 4256 4257 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4258 if (!SE.isLoopInvariant(Expr, L)) 4259 SeenLoopVariantSCEVUnknown = true; 4260 return Expr; 4261 } 4262 4263 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4264 // Only re-write AddRecExprs for this loop. 4265 if (Expr->getLoop() == L) 4266 return Expr->getStart(); 4267 SeenOtherLoops = true; 4268 return Expr; 4269 } 4270 4271 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4272 4273 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4274 4275 private: 4276 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4277 : SCEVRewriteVisitor(SE), L(L) {} 4278 4279 const Loop *L; 4280 bool SeenLoopVariantSCEVUnknown = false; 4281 bool SeenOtherLoops = false; 4282 }; 4283 4284 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4285 /// increment expression in case its Loop is L. If it is not L then 4286 /// use AddRec itself. 4287 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4288 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4289 public: 4290 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4291 SCEVPostIncRewriter Rewriter(L, SE); 4292 const SCEV *Result = Rewriter.visit(S); 4293 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4294 ? SE.getCouldNotCompute() 4295 : Result; 4296 } 4297 4298 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4299 if (!SE.isLoopInvariant(Expr, L)) 4300 SeenLoopVariantSCEVUnknown = true; 4301 return Expr; 4302 } 4303 4304 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4305 // Only re-write AddRecExprs for this loop. 4306 if (Expr->getLoop() == L) 4307 return Expr->getPostIncExpr(SE); 4308 SeenOtherLoops = true; 4309 return Expr; 4310 } 4311 4312 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4313 4314 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4315 4316 private: 4317 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4318 : SCEVRewriteVisitor(SE), L(L) {} 4319 4320 const Loop *L; 4321 bool SeenLoopVariantSCEVUnknown = false; 4322 bool SeenOtherLoops = false; 4323 }; 4324 4325 /// This class evaluates the compare condition by matching it against the 4326 /// condition of loop latch. If there is a match we assume a true value 4327 /// for the condition while building SCEV nodes. 4328 class SCEVBackedgeConditionFolder 4329 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4330 public: 4331 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4332 ScalarEvolution &SE) { 4333 bool IsPosBECond = false; 4334 Value *BECond = nullptr; 4335 if (BasicBlock *Latch = L->getLoopLatch()) { 4336 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4337 if (BI && BI->isConditional()) { 4338 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4339 "Both outgoing branches should not target same header!"); 4340 BECond = BI->getCondition(); 4341 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4342 } else { 4343 return S; 4344 } 4345 } 4346 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4347 return Rewriter.visit(S); 4348 } 4349 4350 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4351 const SCEV *Result = Expr; 4352 bool InvariantF = SE.isLoopInvariant(Expr, L); 4353 4354 if (!InvariantF) { 4355 Instruction *I = cast<Instruction>(Expr->getValue()); 4356 switch (I->getOpcode()) { 4357 case Instruction::Select: { 4358 SelectInst *SI = cast<SelectInst>(I); 4359 Optional<const SCEV *> Res = 4360 compareWithBackedgeCondition(SI->getCondition()); 4361 if (Res.hasValue()) { 4362 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4363 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4364 } 4365 break; 4366 } 4367 default: { 4368 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4369 if (Res.hasValue()) 4370 Result = Res.getValue(); 4371 break; 4372 } 4373 } 4374 } 4375 return Result; 4376 } 4377 4378 private: 4379 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4380 bool IsPosBECond, ScalarEvolution &SE) 4381 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4382 IsPositiveBECond(IsPosBECond) {} 4383 4384 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4385 4386 const Loop *L; 4387 /// Loop back condition. 4388 Value *BackedgeCond = nullptr; 4389 /// Set to true if loop back is on positive branch condition. 4390 bool IsPositiveBECond; 4391 }; 4392 4393 Optional<const SCEV *> 4394 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4395 4396 // If value matches the backedge condition for loop latch, 4397 // then return a constant evolution node based on loopback 4398 // branch taken. 4399 if (BackedgeCond == IC) 4400 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4401 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4402 return None; 4403 } 4404 4405 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4406 public: 4407 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4408 ScalarEvolution &SE) { 4409 SCEVShiftRewriter Rewriter(L, SE); 4410 const SCEV *Result = Rewriter.visit(S); 4411 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4412 } 4413 4414 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4415 // Only allow AddRecExprs for this loop. 4416 if (!SE.isLoopInvariant(Expr, L)) 4417 Valid = false; 4418 return Expr; 4419 } 4420 4421 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4422 if (Expr->getLoop() == L && Expr->isAffine()) 4423 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4424 Valid = false; 4425 return Expr; 4426 } 4427 4428 bool isValid() { return Valid; } 4429 4430 private: 4431 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4432 : SCEVRewriteVisitor(SE), L(L) {} 4433 4434 const Loop *L; 4435 bool Valid = true; 4436 }; 4437 4438 } // end anonymous namespace 4439 4440 SCEV::NoWrapFlags 4441 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4442 if (!AR->isAffine()) 4443 return SCEV::FlagAnyWrap; 4444 4445 using OBO = OverflowingBinaryOperator; 4446 4447 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4448 4449 if (!AR->hasNoSignedWrap()) { 4450 ConstantRange AddRecRange = getSignedRange(AR); 4451 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4452 4453 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4454 Instruction::Add, IncRange, OBO::NoSignedWrap); 4455 if (NSWRegion.contains(AddRecRange)) 4456 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4457 } 4458 4459 if (!AR->hasNoUnsignedWrap()) { 4460 ConstantRange AddRecRange = getUnsignedRange(AR); 4461 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4462 4463 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4464 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4465 if (NUWRegion.contains(AddRecRange)) 4466 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4467 } 4468 4469 return Result; 4470 } 4471 4472 namespace { 4473 4474 /// Represents an abstract binary operation. This may exist as a 4475 /// normal instruction or constant expression, or may have been 4476 /// derived from an expression tree. 4477 struct BinaryOp { 4478 unsigned Opcode; 4479 Value *LHS; 4480 Value *RHS; 4481 bool IsNSW = false; 4482 bool IsNUW = false; 4483 4484 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4485 /// constant expression. 4486 Operator *Op = nullptr; 4487 4488 explicit BinaryOp(Operator *Op) 4489 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4490 Op(Op) { 4491 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4492 IsNSW = OBO->hasNoSignedWrap(); 4493 IsNUW = OBO->hasNoUnsignedWrap(); 4494 } 4495 } 4496 4497 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4498 bool IsNUW = false) 4499 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4500 }; 4501 4502 } // end anonymous namespace 4503 4504 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4505 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4506 auto *Op = dyn_cast<Operator>(V); 4507 if (!Op) 4508 return None; 4509 4510 // Implementation detail: all the cleverness here should happen without 4511 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4512 // SCEV expressions when possible, and we should not break that. 4513 4514 switch (Op->getOpcode()) { 4515 case Instruction::Add: 4516 case Instruction::Sub: 4517 case Instruction::Mul: 4518 case Instruction::UDiv: 4519 case Instruction::URem: 4520 case Instruction::And: 4521 case Instruction::Or: 4522 case Instruction::AShr: 4523 case Instruction::Shl: 4524 return BinaryOp(Op); 4525 4526 case Instruction::Xor: 4527 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4528 // If the RHS of the xor is a signmask, then this is just an add. 4529 // Instcombine turns add of signmask into xor as a strength reduction step. 4530 if (RHSC->getValue().isSignMask()) 4531 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4532 return BinaryOp(Op); 4533 4534 case Instruction::LShr: 4535 // Turn logical shift right of a constant into a unsigned divide. 4536 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4537 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4538 4539 // If the shift count is not less than the bitwidth, the result of 4540 // the shift is undefined. Don't try to analyze it, because the 4541 // resolution chosen here may differ from the resolution chosen in 4542 // other parts of the compiler. 4543 if (SA->getValue().ult(BitWidth)) { 4544 Constant *X = 4545 ConstantInt::get(SA->getContext(), 4546 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4547 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4548 } 4549 } 4550 return BinaryOp(Op); 4551 4552 case Instruction::ExtractValue: { 4553 auto *EVI = cast<ExtractValueInst>(Op); 4554 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4555 break; 4556 4557 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4558 if (!WO) 4559 break; 4560 4561 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4562 bool Signed = WO->isSigned(); 4563 // TODO: Should add nuw/nsw flags for mul as well. 4564 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4565 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4566 4567 // Now that we know that all uses of the arithmetic-result component of 4568 // CI are guarded by the overflow check, we can go ahead and pretend 4569 // that the arithmetic is non-overflowing. 4570 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4571 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4572 } 4573 4574 default: 4575 break; 4576 } 4577 4578 return None; 4579 } 4580 4581 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4582 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4583 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4584 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4585 /// follows one of the following patterns: 4586 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4587 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4588 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4589 /// we return the type of the truncation operation, and indicate whether the 4590 /// truncated type should be treated as signed/unsigned by setting 4591 /// \p Signed to true/false, respectively. 4592 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4593 bool &Signed, ScalarEvolution &SE) { 4594 // The case where Op == SymbolicPHI (that is, with no type conversions on 4595 // the way) is handled by the regular add recurrence creating logic and 4596 // would have already been triggered in createAddRecForPHI. Reaching it here 4597 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4598 // because one of the other operands of the SCEVAddExpr updating this PHI is 4599 // not invariant). 4600 // 4601 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4602 // this case predicates that allow us to prove that Op == SymbolicPHI will 4603 // be added. 4604 if (Op == SymbolicPHI) 4605 return nullptr; 4606 4607 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4608 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4609 if (SourceBits != NewBits) 4610 return nullptr; 4611 4612 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4613 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4614 if (!SExt && !ZExt) 4615 return nullptr; 4616 const SCEVTruncateExpr *Trunc = 4617 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4618 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4619 if (!Trunc) 4620 return nullptr; 4621 const SCEV *X = Trunc->getOperand(); 4622 if (X != SymbolicPHI) 4623 return nullptr; 4624 Signed = SExt != nullptr; 4625 return Trunc->getType(); 4626 } 4627 4628 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4629 if (!PN->getType()->isIntegerTy()) 4630 return nullptr; 4631 const Loop *L = LI.getLoopFor(PN->getParent()); 4632 if (!L || L->getHeader() != PN->getParent()) 4633 return nullptr; 4634 return L; 4635 } 4636 4637 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4638 // computation that updates the phi follows the following pattern: 4639 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4640 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4641 // If so, try to see if it can be rewritten as an AddRecExpr under some 4642 // Predicates. If successful, return them as a pair. Also cache the results 4643 // of the analysis. 4644 // 4645 // Example usage scenario: 4646 // Say the Rewriter is called for the following SCEV: 4647 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4648 // where: 4649 // %X = phi i64 (%Start, %BEValue) 4650 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4651 // and call this function with %SymbolicPHI = %X. 4652 // 4653 // The analysis will find that the value coming around the backedge has 4654 // the following SCEV: 4655 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4656 // Upon concluding that this matches the desired pattern, the function 4657 // will return the pair {NewAddRec, SmallPredsVec} where: 4658 // NewAddRec = {%Start,+,%Step} 4659 // SmallPredsVec = {P1, P2, P3} as follows: 4660 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4661 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4662 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4663 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4664 // under the predicates {P1,P2,P3}. 4665 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4666 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4667 // 4668 // TODO's: 4669 // 4670 // 1) Extend the Induction descriptor to also support inductions that involve 4671 // casts: When needed (namely, when we are called in the context of the 4672 // vectorizer induction analysis), a Set of cast instructions will be 4673 // populated by this method, and provided back to isInductionPHI. This is 4674 // needed to allow the vectorizer to properly record them to be ignored by 4675 // the cost model and to avoid vectorizing them (otherwise these casts, 4676 // which are redundant under the runtime overflow checks, will be 4677 // vectorized, which can be costly). 4678 // 4679 // 2) Support additional induction/PHISCEV patterns: We also want to support 4680 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4681 // after the induction update operation (the induction increment): 4682 // 4683 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4684 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4685 // 4686 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4687 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4688 // 4689 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4690 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4691 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4692 SmallVector<const SCEVPredicate *, 3> Predicates; 4693 4694 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4695 // return an AddRec expression under some predicate. 4696 4697 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4698 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4699 assert(L && "Expecting an integer loop header phi"); 4700 4701 // The loop may have multiple entrances or multiple exits; we can analyze 4702 // this phi as an addrec if it has a unique entry value and a unique 4703 // backedge value. 4704 Value *BEValueV = nullptr, *StartValueV = nullptr; 4705 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4706 Value *V = PN->getIncomingValue(i); 4707 if (L->contains(PN->getIncomingBlock(i))) { 4708 if (!BEValueV) { 4709 BEValueV = V; 4710 } else if (BEValueV != V) { 4711 BEValueV = nullptr; 4712 break; 4713 } 4714 } else if (!StartValueV) { 4715 StartValueV = V; 4716 } else if (StartValueV != V) { 4717 StartValueV = nullptr; 4718 break; 4719 } 4720 } 4721 if (!BEValueV || !StartValueV) 4722 return None; 4723 4724 const SCEV *BEValue = getSCEV(BEValueV); 4725 4726 // If the value coming around the backedge is an add with the symbolic 4727 // value we just inserted, possibly with casts that we can ignore under 4728 // an appropriate runtime guard, then we found a simple induction variable! 4729 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4730 if (!Add) 4731 return None; 4732 4733 // If there is a single occurrence of the symbolic value, possibly 4734 // casted, replace it with a recurrence. 4735 unsigned FoundIndex = Add->getNumOperands(); 4736 Type *TruncTy = nullptr; 4737 bool Signed; 4738 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4739 if ((TruncTy = 4740 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4741 if (FoundIndex == e) { 4742 FoundIndex = i; 4743 break; 4744 } 4745 4746 if (FoundIndex == Add->getNumOperands()) 4747 return None; 4748 4749 // Create an add with everything but the specified operand. 4750 SmallVector<const SCEV *, 8> Ops; 4751 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4752 if (i != FoundIndex) 4753 Ops.push_back(Add->getOperand(i)); 4754 const SCEV *Accum = getAddExpr(Ops); 4755 4756 // The runtime checks will not be valid if the step amount is 4757 // varying inside the loop. 4758 if (!isLoopInvariant(Accum, L)) 4759 return None; 4760 4761 // *** Part2: Create the predicates 4762 4763 // Analysis was successful: we have a phi-with-cast pattern for which we 4764 // can return an AddRec expression under the following predicates: 4765 // 4766 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4767 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4768 // P2: An Equal predicate that guarantees that 4769 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4770 // P3: An Equal predicate that guarantees that 4771 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4772 // 4773 // As we next prove, the above predicates guarantee that: 4774 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4775 // 4776 // 4777 // More formally, we want to prove that: 4778 // Expr(i+1) = Start + (i+1) * Accum 4779 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4780 // 4781 // Given that: 4782 // 1) Expr(0) = Start 4783 // 2) Expr(1) = Start + Accum 4784 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4785 // 3) Induction hypothesis (step i): 4786 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4787 // 4788 // Proof: 4789 // Expr(i+1) = 4790 // = Start + (i+1)*Accum 4791 // = (Start + i*Accum) + Accum 4792 // = Expr(i) + Accum 4793 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4794 // :: from step i 4795 // 4796 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4797 // 4798 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4799 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4800 // + Accum :: from P3 4801 // 4802 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4803 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4804 // 4805 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4806 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4807 // 4808 // By induction, the same applies to all iterations 1<=i<n: 4809 // 4810 4811 // Create a truncated addrec for which we will add a no overflow check (P1). 4812 const SCEV *StartVal = getSCEV(StartValueV); 4813 const SCEV *PHISCEV = 4814 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4815 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4816 4817 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4818 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4819 // will be constant. 4820 // 4821 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4822 // add P1. 4823 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4824 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4825 Signed ? SCEVWrapPredicate::IncrementNSSW 4826 : SCEVWrapPredicate::IncrementNUSW; 4827 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4828 Predicates.push_back(AddRecPred); 4829 } 4830 4831 // Create the Equal Predicates P2,P3: 4832 4833 // It is possible that the predicates P2 and/or P3 are computable at 4834 // compile time due to StartVal and/or Accum being constants. 4835 // If either one is, then we can check that now and escape if either P2 4836 // or P3 is false. 4837 4838 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4839 // for each of StartVal and Accum 4840 auto getExtendedExpr = [&](const SCEV *Expr, 4841 bool CreateSignExtend) -> const SCEV * { 4842 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4843 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4844 const SCEV *ExtendedExpr = 4845 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4846 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4847 return ExtendedExpr; 4848 }; 4849 4850 // Given: 4851 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4852 // = getExtendedExpr(Expr) 4853 // Determine whether the predicate P: Expr == ExtendedExpr 4854 // is known to be false at compile time 4855 auto PredIsKnownFalse = [&](const SCEV *Expr, 4856 const SCEV *ExtendedExpr) -> bool { 4857 return Expr != ExtendedExpr && 4858 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4859 }; 4860 4861 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4862 if (PredIsKnownFalse(StartVal, StartExtended)) { 4863 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4864 return None; 4865 } 4866 4867 // The Step is always Signed (because the overflow checks are either 4868 // NSSW or NUSW) 4869 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4870 if (PredIsKnownFalse(Accum, AccumExtended)) { 4871 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4872 return None; 4873 } 4874 4875 auto AppendPredicate = [&](const SCEV *Expr, 4876 const SCEV *ExtendedExpr) -> void { 4877 if (Expr != ExtendedExpr && 4878 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4879 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4880 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4881 Predicates.push_back(Pred); 4882 } 4883 }; 4884 4885 AppendPredicate(StartVal, StartExtended); 4886 AppendPredicate(Accum, AccumExtended); 4887 4888 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4889 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4890 // into NewAR if it will also add the runtime overflow checks specified in 4891 // Predicates. 4892 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4893 4894 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4895 std::make_pair(NewAR, Predicates); 4896 // Remember the result of the analysis for this SCEV at this locayyytion. 4897 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4898 return PredRewrite; 4899 } 4900 4901 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4902 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4903 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4904 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4905 if (!L) 4906 return None; 4907 4908 // Check to see if we already analyzed this PHI. 4909 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4910 if (I != PredicatedSCEVRewrites.end()) { 4911 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4912 I->second; 4913 // Analysis was done before and failed to create an AddRec: 4914 if (Rewrite.first == SymbolicPHI) 4915 return None; 4916 // Analysis was done before and succeeded to create an AddRec under 4917 // a predicate: 4918 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4919 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4920 return Rewrite; 4921 } 4922 4923 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4924 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4925 4926 // Record in the cache that the analysis failed 4927 if (!Rewrite) { 4928 SmallVector<const SCEVPredicate *, 3> Predicates; 4929 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4930 return None; 4931 } 4932 4933 return Rewrite; 4934 } 4935 4936 // FIXME: This utility is currently required because the Rewriter currently 4937 // does not rewrite this expression: 4938 // {0, +, (sext ix (trunc iy to ix) to iy)} 4939 // into {0, +, %step}, 4940 // even when the following Equal predicate exists: 4941 // "%step == (sext ix (trunc iy to ix) to iy)". 4942 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4943 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4944 if (AR1 == AR2) 4945 return true; 4946 4947 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4948 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4949 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4950 return false; 4951 return true; 4952 }; 4953 4954 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4955 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4956 return false; 4957 return true; 4958 } 4959 4960 /// A helper function for createAddRecFromPHI to handle simple cases. 4961 /// 4962 /// This function tries to find an AddRec expression for the simplest (yet most 4963 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4964 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4965 /// technique for finding the AddRec expression. 4966 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4967 Value *BEValueV, 4968 Value *StartValueV) { 4969 const Loop *L = LI.getLoopFor(PN->getParent()); 4970 assert(L && L->getHeader() == PN->getParent()); 4971 assert(BEValueV && StartValueV); 4972 4973 auto BO = MatchBinaryOp(BEValueV, DT); 4974 if (!BO) 4975 return nullptr; 4976 4977 if (BO->Opcode != Instruction::Add) 4978 return nullptr; 4979 4980 const SCEV *Accum = nullptr; 4981 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4982 Accum = getSCEV(BO->RHS); 4983 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4984 Accum = getSCEV(BO->LHS); 4985 4986 if (!Accum) 4987 return nullptr; 4988 4989 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4990 if (BO->IsNUW) 4991 Flags = setFlags(Flags, SCEV::FlagNUW); 4992 if (BO->IsNSW) 4993 Flags = setFlags(Flags, SCEV::FlagNSW); 4994 4995 const SCEV *StartVal = getSCEV(StartValueV); 4996 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4997 4998 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4999 5000 // We can add Flags to the post-inc expression only if we 5001 // know that it is *undefined behavior* for BEValueV to 5002 // overflow. 5003 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5004 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5005 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5006 5007 return PHISCEV; 5008 } 5009 5010 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5011 const Loop *L = LI.getLoopFor(PN->getParent()); 5012 if (!L || L->getHeader() != PN->getParent()) 5013 return nullptr; 5014 5015 // The loop may have multiple entrances or multiple exits; we can analyze 5016 // this phi as an addrec if it has a unique entry value and a unique 5017 // backedge value. 5018 Value *BEValueV = nullptr, *StartValueV = nullptr; 5019 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5020 Value *V = PN->getIncomingValue(i); 5021 if (L->contains(PN->getIncomingBlock(i))) { 5022 if (!BEValueV) { 5023 BEValueV = V; 5024 } else if (BEValueV != V) { 5025 BEValueV = nullptr; 5026 break; 5027 } 5028 } else if (!StartValueV) { 5029 StartValueV = V; 5030 } else if (StartValueV != V) { 5031 StartValueV = nullptr; 5032 break; 5033 } 5034 } 5035 if (!BEValueV || !StartValueV) 5036 return nullptr; 5037 5038 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5039 "PHI node already processed?"); 5040 5041 // First, try to find AddRec expression without creating a fictituos symbolic 5042 // value for PN. 5043 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5044 return S; 5045 5046 // Handle PHI node value symbolically. 5047 const SCEV *SymbolicName = getUnknown(PN); 5048 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5049 5050 // Using this symbolic name for the PHI, analyze the value coming around 5051 // the back-edge. 5052 const SCEV *BEValue = getSCEV(BEValueV); 5053 5054 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5055 // has a special value for the first iteration of the loop. 5056 5057 // If the value coming around the backedge is an add with the symbolic 5058 // value we just inserted, then we found a simple induction variable! 5059 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5060 // If there is a single occurrence of the symbolic value, replace it 5061 // with a recurrence. 5062 unsigned FoundIndex = Add->getNumOperands(); 5063 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5064 if (Add->getOperand(i) == SymbolicName) 5065 if (FoundIndex == e) { 5066 FoundIndex = i; 5067 break; 5068 } 5069 5070 if (FoundIndex != Add->getNumOperands()) { 5071 // Create an add with everything but the specified operand. 5072 SmallVector<const SCEV *, 8> Ops; 5073 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5074 if (i != FoundIndex) 5075 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5076 L, *this)); 5077 const SCEV *Accum = getAddExpr(Ops); 5078 5079 // This is not a valid addrec if the step amount is varying each 5080 // loop iteration, but is not itself an addrec in this loop. 5081 if (isLoopInvariant(Accum, L) || 5082 (isa<SCEVAddRecExpr>(Accum) && 5083 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5084 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5085 5086 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5087 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5088 if (BO->IsNUW) 5089 Flags = setFlags(Flags, SCEV::FlagNUW); 5090 if (BO->IsNSW) 5091 Flags = setFlags(Flags, SCEV::FlagNSW); 5092 } 5093 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5094 // If the increment is an inbounds GEP, then we know the address 5095 // space cannot be wrapped around. We cannot make any guarantee 5096 // about signed or unsigned overflow because pointers are 5097 // unsigned but we may have a negative index from the base 5098 // pointer. We can guarantee that no unsigned wrap occurs if the 5099 // indices form a positive value. 5100 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5101 Flags = setFlags(Flags, SCEV::FlagNW); 5102 5103 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5104 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5105 Flags = setFlags(Flags, SCEV::FlagNUW); 5106 } 5107 5108 // We cannot transfer nuw and nsw flags from subtraction 5109 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5110 // for instance. 5111 } 5112 5113 const SCEV *StartVal = getSCEV(StartValueV); 5114 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5115 5116 // Okay, for the entire analysis of this edge we assumed the PHI 5117 // to be symbolic. We now need to go back and purge all of the 5118 // entries for the scalars that use the symbolic expression. 5119 forgetSymbolicName(PN, SymbolicName); 5120 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5121 5122 // We can add Flags to the post-inc expression only if we 5123 // know that it is *undefined behavior* for BEValueV to 5124 // overflow. 5125 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5126 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5127 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5128 5129 return PHISCEV; 5130 } 5131 } 5132 } else { 5133 // Otherwise, this could be a loop like this: 5134 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5135 // In this case, j = {1,+,1} and BEValue is j. 5136 // Because the other in-value of i (0) fits the evolution of BEValue 5137 // i really is an addrec evolution. 5138 // 5139 // We can generalize this saying that i is the shifted value of BEValue 5140 // by one iteration: 5141 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5142 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5143 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5144 if (Shifted != getCouldNotCompute() && 5145 Start != getCouldNotCompute()) { 5146 const SCEV *StartVal = getSCEV(StartValueV); 5147 if (Start == StartVal) { 5148 // Okay, for the entire analysis of this edge we assumed the PHI 5149 // to be symbolic. We now need to go back and purge all of the 5150 // entries for the scalars that use the symbolic expression. 5151 forgetSymbolicName(PN, SymbolicName); 5152 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5153 return Shifted; 5154 } 5155 } 5156 } 5157 5158 // Remove the temporary PHI node SCEV that has been inserted while intending 5159 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5160 // as it will prevent later (possibly simpler) SCEV expressions to be added 5161 // to the ValueExprMap. 5162 eraseValueFromMap(PN); 5163 5164 return nullptr; 5165 } 5166 5167 // Checks if the SCEV S is available at BB. S is considered available at BB 5168 // if S can be materialized at BB without introducing a fault. 5169 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5170 BasicBlock *BB) { 5171 struct CheckAvailable { 5172 bool TraversalDone = false; 5173 bool Available = true; 5174 5175 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5176 BasicBlock *BB = nullptr; 5177 DominatorTree &DT; 5178 5179 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5180 : L(L), BB(BB), DT(DT) {} 5181 5182 bool setUnavailable() { 5183 TraversalDone = true; 5184 Available = false; 5185 return false; 5186 } 5187 5188 bool follow(const SCEV *S) { 5189 switch (S->getSCEVType()) { 5190 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5191 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5192 case scUMinExpr: 5193 case scSMinExpr: 5194 // These expressions are available if their operand(s) is/are. 5195 return true; 5196 5197 case scAddRecExpr: { 5198 // We allow add recurrences that are on the loop BB is in, or some 5199 // outer loop. This guarantees availability because the value of the 5200 // add recurrence at BB is simply the "current" value of the induction 5201 // variable. We can relax this in the future; for instance an add 5202 // recurrence on a sibling dominating loop is also available at BB. 5203 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5204 if (L && (ARLoop == L || ARLoop->contains(L))) 5205 return true; 5206 5207 return setUnavailable(); 5208 } 5209 5210 case scUnknown: { 5211 // For SCEVUnknown, we check for simple dominance. 5212 const auto *SU = cast<SCEVUnknown>(S); 5213 Value *V = SU->getValue(); 5214 5215 if (isa<Argument>(V)) 5216 return false; 5217 5218 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5219 return false; 5220 5221 return setUnavailable(); 5222 } 5223 5224 case scUDivExpr: 5225 case scCouldNotCompute: 5226 // We do not try to smart about these at all. 5227 return setUnavailable(); 5228 } 5229 llvm_unreachable("switch should be fully covered!"); 5230 } 5231 5232 bool isDone() { return TraversalDone; } 5233 }; 5234 5235 CheckAvailable CA(L, BB, DT); 5236 SCEVTraversal<CheckAvailable> ST(CA); 5237 5238 ST.visitAll(S); 5239 return CA.Available; 5240 } 5241 5242 // Try to match a control flow sequence that branches out at BI and merges back 5243 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5244 // match. 5245 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5246 Value *&C, Value *&LHS, Value *&RHS) { 5247 C = BI->getCondition(); 5248 5249 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5250 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5251 5252 if (!LeftEdge.isSingleEdge()) 5253 return false; 5254 5255 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5256 5257 Use &LeftUse = Merge->getOperandUse(0); 5258 Use &RightUse = Merge->getOperandUse(1); 5259 5260 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5261 LHS = LeftUse; 5262 RHS = RightUse; 5263 return true; 5264 } 5265 5266 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5267 LHS = RightUse; 5268 RHS = LeftUse; 5269 return true; 5270 } 5271 5272 return false; 5273 } 5274 5275 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5276 auto IsReachable = 5277 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5278 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5279 const Loop *L = LI.getLoopFor(PN->getParent()); 5280 5281 // We don't want to break LCSSA, even in a SCEV expression tree. 5282 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5283 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5284 return nullptr; 5285 5286 // Try to match 5287 // 5288 // br %cond, label %left, label %right 5289 // left: 5290 // br label %merge 5291 // right: 5292 // br label %merge 5293 // merge: 5294 // V = phi [ %x, %left ], [ %y, %right ] 5295 // 5296 // as "select %cond, %x, %y" 5297 5298 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5299 assert(IDom && "At least the entry block should dominate PN"); 5300 5301 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5302 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5303 5304 if (BI && BI->isConditional() && 5305 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5306 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5307 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5308 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5309 } 5310 5311 return nullptr; 5312 } 5313 5314 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5315 if (const SCEV *S = createAddRecFromPHI(PN)) 5316 return S; 5317 5318 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5319 return S; 5320 5321 // If the PHI has a single incoming value, follow that value, unless the 5322 // PHI's incoming blocks are in a different loop, in which case doing so 5323 // risks breaking LCSSA form. Instcombine would normally zap these, but 5324 // it doesn't have DominatorTree information, so it may miss cases. 5325 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5326 if (LI.replacementPreservesLCSSAForm(PN, V)) 5327 return getSCEV(V); 5328 5329 // If it's not a loop phi, we can't handle it yet. 5330 return getUnknown(PN); 5331 } 5332 5333 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5334 Value *Cond, 5335 Value *TrueVal, 5336 Value *FalseVal) { 5337 // Handle "constant" branch or select. This can occur for instance when a 5338 // loop pass transforms an inner loop and moves on to process the outer loop. 5339 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5340 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5341 5342 // Try to match some simple smax or umax patterns. 5343 auto *ICI = dyn_cast<ICmpInst>(Cond); 5344 if (!ICI) 5345 return getUnknown(I); 5346 5347 Value *LHS = ICI->getOperand(0); 5348 Value *RHS = ICI->getOperand(1); 5349 5350 switch (ICI->getPredicate()) { 5351 case ICmpInst::ICMP_SLT: 5352 case ICmpInst::ICMP_SLE: 5353 std::swap(LHS, RHS); 5354 LLVM_FALLTHROUGH; 5355 case ICmpInst::ICMP_SGT: 5356 case ICmpInst::ICMP_SGE: 5357 // a >s b ? a+x : b+x -> smax(a, b)+x 5358 // a >s b ? b+x : a+x -> smin(a, b)+x 5359 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5360 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5361 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5362 const SCEV *LA = getSCEV(TrueVal); 5363 const SCEV *RA = getSCEV(FalseVal); 5364 const SCEV *LDiff = getMinusSCEV(LA, LS); 5365 const SCEV *RDiff = getMinusSCEV(RA, RS); 5366 if (LDiff == RDiff) 5367 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5368 LDiff = getMinusSCEV(LA, RS); 5369 RDiff = getMinusSCEV(RA, LS); 5370 if (LDiff == RDiff) 5371 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5372 } 5373 break; 5374 case ICmpInst::ICMP_ULT: 5375 case ICmpInst::ICMP_ULE: 5376 std::swap(LHS, RHS); 5377 LLVM_FALLTHROUGH; 5378 case ICmpInst::ICMP_UGT: 5379 case ICmpInst::ICMP_UGE: 5380 // a >u b ? a+x : b+x -> umax(a, b)+x 5381 // a >u b ? b+x : a+x -> umin(a, b)+x 5382 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5383 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5384 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5385 const SCEV *LA = getSCEV(TrueVal); 5386 const SCEV *RA = getSCEV(FalseVal); 5387 const SCEV *LDiff = getMinusSCEV(LA, LS); 5388 const SCEV *RDiff = getMinusSCEV(RA, RS); 5389 if (LDiff == RDiff) 5390 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5391 LDiff = getMinusSCEV(LA, RS); 5392 RDiff = getMinusSCEV(RA, LS); 5393 if (LDiff == RDiff) 5394 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5395 } 5396 break; 5397 case ICmpInst::ICMP_NE: 5398 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5399 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5400 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5401 const SCEV *One = getOne(I->getType()); 5402 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5403 const SCEV *LA = getSCEV(TrueVal); 5404 const SCEV *RA = getSCEV(FalseVal); 5405 const SCEV *LDiff = getMinusSCEV(LA, LS); 5406 const SCEV *RDiff = getMinusSCEV(RA, One); 5407 if (LDiff == RDiff) 5408 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5409 } 5410 break; 5411 case ICmpInst::ICMP_EQ: 5412 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5413 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5414 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5415 const SCEV *One = getOne(I->getType()); 5416 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5417 const SCEV *LA = getSCEV(TrueVal); 5418 const SCEV *RA = getSCEV(FalseVal); 5419 const SCEV *LDiff = getMinusSCEV(LA, One); 5420 const SCEV *RDiff = getMinusSCEV(RA, LS); 5421 if (LDiff == RDiff) 5422 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5423 } 5424 break; 5425 default: 5426 break; 5427 } 5428 5429 return getUnknown(I); 5430 } 5431 5432 /// Expand GEP instructions into add and multiply operations. This allows them 5433 /// to be analyzed by regular SCEV code. 5434 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5435 // Don't attempt to analyze GEPs over unsized objects. 5436 if (!GEP->getSourceElementType()->isSized()) 5437 return getUnknown(GEP); 5438 5439 SmallVector<const SCEV *, 4> IndexExprs; 5440 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5441 IndexExprs.push_back(getSCEV(*Index)); 5442 return getGEPExpr(GEP, IndexExprs); 5443 } 5444 5445 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5446 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5447 return C->getAPInt().countTrailingZeros(); 5448 5449 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5450 return std::min(GetMinTrailingZeros(T->getOperand()), 5451 (uint32_t)getTypeSizeInBits(T->getType())); 5452 5453 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5454 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5455 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5456 ? getTypeSizeInBits(E->getType()) 5457 : OpRes; 5458 } 5459 5460 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5461 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5462 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5463 ? getTypeSizeInBits(E->getType()) 5464 : OpRes; 5465 } 5466 5467 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5468 // The result is the min of all operands results. 5469 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5470 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5471 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5472 return MinOpRes; 5473 } 5474 5475 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5476 // The result is the sum of all operands results. 5477 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5478 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5479 for (unsigned i = 1, e = M->getNumOperands(); 5480 SumOpRes != BitWidth && i != e; ++i) 5481 SumOpRes = 5482 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5483 return SumOpRes; 5484 } 5485 5486 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5487 // The result is the min of all operands results. 5488 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5489 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5490 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5491 return MinOpRes; 5492 } 5493 5494 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5495 // The result is the min of all operands results. 5496 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5497 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5498 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5499 return MinOpRes; 5500 } 5501 5502 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5503 // The result is the min of all operands results. 5504 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5505 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5506 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5507 return MinOpRes; 5508 } 5509 5510 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5511 // For a SCEVUnknown, ask ValueTracking. 5512 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5513 return Known.countMinTrailingZeros(); 5514 } 5515 5516 // SCEVUDivExpr 5517 return 0; 5518 } 5519 5520 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5521 auto I = MinTrailingZerosCache.find(S); 5522 if (I != MinTrailingZerosCache.end()) 5523 return I->second; 5524 5525 uint32_t Result = GetMinTrailingZerosImpl(S); 5526 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5527 assert(InsertPair.second && "Should insert a new key"); 5528 return InsertPair.first->second; 5529 } 5530 5531 /// Helper method to assign a range to V from metadata present in the IR. 5532 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5533 if (Instruction *I = dyn_cast<Instruction>(V)) 5534 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5535 return getConstantRangeFromMetadata(*MD); 5536 5537 return None; 5538 } 5539 5540 /// Determine the range for a particular SCEV. If SignHint is 5541 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5542 /// with a "cleaner" unsigned (resp. signed) representation. 5543 const ConstantRange & 5544 ScalarEvolution::getRangeRef(const SCEV *S, 5545 ScalarEvolution::RangeSignHint SignHint) { 5546 DenseMap<const SCEV *, ConstantRange> &Cache = 5547 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5548 : SignedRanges; 5549 ConstantRange::PreferredRangeType RangeType = 5550 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5551 ? ConstantRange::Unsigned : ConstantRange::Signed; 5552 5553 // See if we've computed this range already. 5554 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5555 if (I != Cache.end()) 5556 return I->second; 5557 5558 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5559 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5560 5561 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5562 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5563 5564 // If the value has known zeros, the maximum value will have those known zeros 5565 // as well. 5566 uint32_t TZ = GetMinTrailingZeros(S); 5567 if (TZ != 0) { 5568 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5569 ConservativeResult = 5570 ConstantRange(APInt::getMinValue(BitWidth), 5571 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5572 else 5573 ConservativeResult = ConstantRange( 5574 APInt::getSignedMinValue(BitWidth), 5575 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5576 } 5577 5578 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5579 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5580 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5581 X = X.add(getRangeRef(Add->getOperand(i), SignHint)); 5582 return setRange(Add, SignHint, 5583 ConservativeResult.intersectWith(X, RangeType)); 5584 } 5585 5586 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5587 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5588 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5589 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5590 return setRange(Mul, SignHint, 5591 ConservativeResult.intersectWith(X, RangeType)); 5592 } 5593 5594 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5595 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5596 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5597 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5598 return setRange(SMax, SignHint, 5599 ConservativeResult.intersectWith(X, RangeType)); 5600 } 5601 5602 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5603 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5604 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5605 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5606 return setRange(UMax, SignHint, 5607 ConservativeResult.intersectWith(X, RangeType)); 5608 } 5609 5610 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5611 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5612 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5613 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5614 return setRange(SMin, SignHint, 5615 ConservativeResult.intersectWith(X, RangeType)); 5616 } 5617 5618 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5619 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5620 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5621 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5622 return setRange(UMin, SignHint, 5623 ConservativeResult.intersectWith(X, RangeType)); 5624 } 5625 5626 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5627 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5628 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5629 return setRange(UDiv, SignHint, 5630 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5631 } 5632 5633 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5634 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5635 return setRange(ZExt, SignHint, 5636 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5637 RangeType)); 5638 } 5639 5640 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5641 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5642 return setRange(SExt, SignHint, 5643 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5644 RangeType)); 5645 } 5646 5647 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5648 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5649 return setRange(Trunc, SignHint, 5650 ConservativeResult.intersectWith(X.truncate(BitWidth), 5651 RangeType)); 5652 } 5653 5654 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5655 // If there's no unsigned wrap, the value will never be less than its 5656 // initial value. 5657 if (AddRec->hasNoUnsignedWrap()) 5658 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart())) 5659 if (!C->getValue()->isZero()) 5660 ConservativeResult = ConservativeResult.intersectWith( 5661 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)), RangeType); 5662 5663 // If there's no signed wrap, and all the operands have the same sign or 5664 // zero, the value won't ever change sign. 5665 if (AddRec->hasNoSignedWrap()) { 5666 bool AllNonNeg = true; 5667 bool AllNonPos = true; 5668 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 5669 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false; 5670 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false; 5671 } 5672 if (AllNonNeg) 5673 ConservativeResult = ConservativeResult.intersectWith( 5674 ConstantRange(APInt(BitWidth, 0), 5675 APInt::getSignedMinValue(BitWidth)), RangeType); 5676 else if (AllNonPos) 5677 ConservativeResult = ConservativeResult.intersectWith( 5678 ConstantRange(APInt::getSignedMinValue(BitWidth), 5679 APInt(BitWidth, 1)), RangeType); 5680 } 5681 5682 // TODO: non-affine addrec 5683 if (AddRec->isAffine()) { 5684 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5685 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5686 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5687 auto RangeFromAffine = getRangeForAffineAR( 5688 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5689 BitWidth); 5690 if (!RangeFromAffine.isFullSet()) 5691 ConservativeResult = 5692 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5693 5694 auto RangeFromFactoring = getRangeViaFactoring( 5695 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5696 BitWidth); 5697 if (!RangeFromFactoring.isFullSet()) 5698 ConservativeResult = 5699 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5700 } 5701 } 5702 5703 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5704 } 5705 5706 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5707 // Check if the IR explicitly contains !range metadata. 5708 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5709 if (MDRange.hasValue()) 5710 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5711 RangeType); 5712 5713 // Split here to avoid paying the compile-time cost of calling both 5714 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5715 // if needed. 5716 const DataLayout &DL = getDataLayout(); 5717 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5718 // For a SCEVUnknown, ask ValueTracking. 5719 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5720 if (Known.One != ~Known.Zero + 1) 5721 ConservativeResult = 5722 ConservativeResult.intersectWith( 5723 ConstantRange(Known.One, ~Known.Zero + 1), RangeType); 5724 } else { 5725 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5726 "generalize as needed!"); 5727 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5728 if (NS > 1) 5729 ConservativeResult = ConservativeResult.intersectWith( 5730 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5731 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5732 RangeType); 5733 } 5734 5735 // A range of Phi is a subset of union of all ranges of its input. 5736 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5737 // Make sure that we do not run over cycled Phis. 5738 if (PendingPhiRanges.insert(Phi).second) { 5739 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5740 for (auto &Op : Phi->operands()) { 5741 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5742 RangeFromOps = RangeFromOps.unionWith(OpRange); 5743 // No point to continue if we already have a full set. 5744 if (RangeFromOps.isFullSet()) 5745 break; 5746 } 5747 ConservativeResult = 5748 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5749 bool Erased = PendingPhiRanges.erase(Phi); 5750 assert(Erased && "Failed to erase Phi properly?"); 5751 (void) Erased; 5752 } 5753 } 5754 5755 return setRange(U, SignHint, std::move(ConservativeResult)); 5756 } 5757 5758 return setRange(S, SignHint, std::move(ConservativeResult)); 5759 } 5760 5761 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5762 // values that the expression can take. Initially, the expression has a value 5763 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5764 // argument defines if we treat Step as signed or unsigned. 5765 static ConstantRange getRangeForAffineARHelper(APInt Step, 5766 const ConstantRange &StartRange, 5767 const APInt &MaxBECount, 5768 unsigned BitWidth, bool Signed) { 5769 // If either Step or MaxBECount is 0, then the expression won't change, and we 5770 // just need to return the initial range. 5771 if (Step == 0 || MaxBECount == 0) 5772 return StartRange; 5773 5774 // If we don't know anything about the initial value (i.e. StartRange is 5775 // FullRange), then we don't know anything about the final range either. 5776 // Return FullRange. 5777 if (StartRange.isFullSet()) 5778 return ConstantRange::getFull(BitWidth); 5779 5780 // If Step is signed and negative, then we use its absolute value, but we also 5781 // note that we're moving in the opposite direction. 5782 bool Descending = Signed && Step.isNegative(); 5783 5784 if (Signed) 5785 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5786 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5787 // This equations hold true due to the well-defined wrap-around behavior of 5788 // APInt. 5789 Step = Step.abs(); 5790 5791 // Check if Offset is more than full span of BitWidth. If it is, the 5792 // expression is guaranteed to overflow. 5793 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5794 return ConstantRange::getFull(BitWidth); 5795 5796 // Offset is by how much the expression can change. Checks above guarantee no 5797 // overflow here. 5798 APInt Offset = Step * MaxBECount; 5799 5800 // Minimum value of the final range will match the minimal value of StartRange 5801 // if the expression is increasing and will be decreased by Offset otherwise. 5802 // Maximum value of the final range will match the maximal value of StartRange 5803 // if the expression is decreasing and will be increased by Offset otherwise. 5804 APInt StartLower = StartRange.getLower(); 5805 APInt StartUpper = StartRange.getUpper() - 1; 5806 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5807 : (StartUpper + std::move(Offset)); 5808 5809 // It's possible that the new minimum/maximum value will fall into the initial 5810 // range (due to wrap around). This means that the expression can take any 5811 // value in this bitwidth, and we have to return full range. 5812 if (StartRange.contains(MovedBoundary)) 5813 return ConstantRange::getFull(BitWidth); 5814 5815 APInt NewLower = 5816 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5817 APInt NewUpper = 5818 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5819 NewUpper += 1; 5820 5821 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5822 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5823 } 5824 5825 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5826 const SCEV *Step, 5827 const SCEV *MaxBECount, 5828 unsigned BitWidth) { 5829 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5830 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5831 "Precondition!"); 5832 5833 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5834 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5835 5836 // First, consider step signed. 5837 ConstantRange StartSRange = getSignedRange(Start); 5838 ConstantRange StepSRange = getSignedRange(Step); 5839 5840 // If Step can be both positive and negative, we need to find ranges for the 5841 // maximum absolute step values in both directions and union them. 5842 ConstantRange SR = 5843 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5844 MaxBECountValue, BitWidth, /* Signed = */ true); 5845 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5846 StartSRange, MaxBECountValue, 5847 BitWidth, /* Signed = */ true)); 5848 5849 // Next, consider step unsigned. 5850 ConstantRange UR = getRangeForAffineARHelper( 5851 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5852 MaxBECountValue, BitWidth, /* Signed = */ false); 5853 5854 // Finally, intersect signed and unsigned ranges. 5855 return SR.intersectWith(UR, ConstantRange::Smallest); 5856 } 5857 5858 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5859 const SCEV *Step, 5860 const SCEV *MaxBECount, 5861 unsigned BitWidth) { 5862 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5863 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5864 5865 struct SelectPattern { 5866 Value *Condition = nullptr; 5867 APInt TrueValue; 5868 APInt FalseValue; 5869 5870 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5871 const SCEV *S) { 5872 Optional<unsigned> CastOp; 5873 APInt Offset(BitWidth, 0); 5874 5875 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5876 "Should be!"); 5877 5878 // Peel off a constant offset: 5879 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5880 // In the future we could consider being smarter here and handle 5881 // {Start+Step,+,Step} too. 5882 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5883 return; 5884 5885 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5886 S = SA->getOperand(1); 5887 } 5888 5889 // Peel off a cast operation 5890 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5891 CastOp = SCast->getSCEVType(); 5892 S = SCast->getOperand(); 5893 } 5894 5895 using namespace llvm::PatternMatch; 5896 5897 auto *SU = dyn_cast<SCEVUnknown>(S); 5898 const APInt *TrueVal, *FalseVal; 5899 if (!SU || 5900 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5901 m_APInt(FalseVal)))) { 5902 Condition = nullptr; 5903 return; 5904 } 5905 5906 TrueValue = *TrueVal; 5907 FalseValue = *FalseVal; 5908 5909 // Re-apply the cast we peeled off earlier 5910 if (CastOp.hasValue()) 5911 switch (*CastOp) { 5912 default: 5913 llvm_unreachable("Unknown SCEV cast type!"); 5914 5915 case scTruncate: 5916 TrueValue = TrueValue.trunc(BitWidth); 5917 FalseValue = FalseValue.trunc(BitWidth); 5918 break; 5919 case scZeroExtend: 5920 TrueValue = TrueValue.zext(BitWidth); 5921 FalseValue = FalseValue.zext(BitWidth); 5922 break; 5923 case scSignExtend: 5924 TrueValue = TrueValue.sext(BitWidth); 5925 FalseValue = FalseValue.sext(BitWidth); 5926 break; 5927 } 5928 5929 // Re-apply the constant offset we peeled off earlier 5930 TrueValue += Offset; 5931 FalseValue += Offset; 5932 } 5933 5934 bool isRecognized() { return Condition != nullptr; } 5935 }; 5936 5937 SelectPattern StartPattern(*this, BitWidth, Start); 5938 if (!StartPattern.isRecognized()) 5939 return ConstantRange::getFull(BitWidth); 5940 5941 SelectPattern StepPattern(*this, BitWidth, Step); 5942 if (!StepPattern.isRecognized()) 5943 return ConstantRange::getFull(BitWidth); 5944 5945 if (StartPattern.Condition != StepPattern.Condition) { 5946 // We don't handle this case today; but we could, by considering four 5947 // possibilities below instead of two. I'm not sure if there are cases where 5948 // that will help over what getRange already does, though. 5949 return ConstantRange::getFull(BitWidth); 5950 } 5951 5952 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 5953 // construct arbitrary general SCEV expressions here. This function is called 5954 // from deep in the call stack, and calling getSCEV (on a sext instruction, 5955 // say) can end up caching a suboptimal value. 5956 5957 // FIXME: without the explicit `this` receiver below, MSVC errors out with 5958 // C2352 and C2512 (otherwise it isn't needed). 5959 5960 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 5961 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 5962 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 5963 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 5964 5965 ConstantRange TrueRange = 5966 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 5967 ConstantRange FalseRange = 5968 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 5969 5970 return TrueRange.unionWith(FalseRange); 5971 } 5972 5973 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 5974 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 5975 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 5976 5977 // Return early if there are no flags to propagate to the SCEV. 5978 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5979 if (BinOp->hasNoUnsignedWrap()) 5980 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 5981 if (BinOp->hasNoSignedWrap()) 5982 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 5983 if (Flags == SCEV::FlagAnyWrap) 5984 return SCEV::FlagAnyWrap; 5985 5986 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 5987 } 5988 5989 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 5990 // Here we check that I is in the header of the innermost loop containing I, 5991 // since we only deal with instructions in the loop header. The actual loop we 5992 // need to check later will come from an add recurrence, but getting that 5993 // requires computing the SCEV of the operands, which can be expensive. This 5994 // check we can do cheaply to rule out some cases early. 5995 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 5996 if (InnermostContainingLoop == nullptr || 5997 InnermostContainingLoop->getHeader() != I->getParent()) 5998 return false; 5999 6000 // Only proceed if we can prove that I does not yield poison. 6001 if (!programUndefinedIfFullPoison(I)) 6002 return false; 6003 6004 // At this point we know that if I is executed, then it does not wrap 6005 // according to at least one of NSW or NUW. If I is not executed, then we do 6006 // not know if the calculation that I represents would wrap. Multiple 6007 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6008 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6009 // derived from other instructions that map to the same SCEV. We cannot make 6010 // that guarantee for cases where I is not executed. So we need to find the 6011 // loop that I is considered in relation to and prove that I is executed for 6012 // every iteration of that loop. That implies that the value that I 6013 // calculates does not wrap anywhere in the loop, so then we can apply the 6014 // flags to the SCEV. 6015 // 6016 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6017 // from different loops, so that we know which loop to prove that I is 6018 // executed in. 6019 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6020 // I could be an extractvalue from a call to an overflow intrinsic. 6021 // TODO: We can do better here in some cases. 6022 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6023 return false; 6024 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6025 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6026 bool AllOtherOpsLoopInvariant = true; 6027 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6028 ++OtherOpIndex) { 6029 if (OtherOpIndex != OpIndex) { 6030 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6031 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6032 AllOtherOpsLoopInvariant = false; 6033 break; 6034 } 6035 } 6036 } 6037 if (AllOtherOpsLoopInvariant && 6038 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6039 return true; 6040 } 6041 } 6042 return false; 6043 } 6044 6045 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6046 // If we know that \c I can never be poison period, then that's enough. 6047 if (isSCEVExprNeverPoison(I)) 6048 return true; 6049 6050 // For an add recurrence specifically, we assume that infinite loops without 6051 // side effects are undefined behavior, and then reason as follows: 6052 // 6053 // If the add recurrence is poison in any iteration, it is poison on all 6054 // future iterations (since incrementing poison yields poison). If the result 6055 // of the add recurrence is fed into the loop latch condition and the loop 6056 // does not contain any throws or exiting blocks other than the latch, we now 6057 // have the ability to "choose" whether the backedge is taken or not (by 6058 // choosing a sufficiently evil value for the poison feeding into the branch) 6059 // for every iteration including and after the one in which \p I first became 6060 // poison. There are two possibilities (let's call the iteration in which \p 6061 // I first became poison as K): 6062 // 6063 // 1. In the set of iterations including and after K, the loop body executes 6064 // no side effects. In this case executing the backege an infinte number 6065 // of times will yield undefined behavior. 6066 // 6067 // 2. In the set of iterations including and after K, the loop body executes 6068 // at least one side effect. In this case, that specific instance of side 6069 // effect is control dependent on poison, which also yields undefined 6070 // behavior. 6071 6072 auto *ExitingBB = L->getExitingBlock(); 6073 auto *LatchBB = L->getLoopLatch(); 6074 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6075 return false; 6076 6077 SmallPtrSet<const Instruction *, 16> Pushed; 6078 SmallVector<const Instruction *, 8> PoisonStack; 6079 6080 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6081 // things that are known to be fully poison under that assumption go on the 6082 // PoisonStack. 6083 Pushed.insert(I); 6084 PoisonStack.push_back(I); 6085 6086 bool LatchControlDependentOnPoison = false; 6087 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6088 const Instruction *Poison = PoisonStack.pop_back_val(); 6089 6090 for (auto *PoisonUser : Poison->users()) { 6091 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) { 6092 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6093 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6094 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6095 assert(BI->isConditional() && "Only possibility!"); 6096 if (BI->getParent() == LatchBB) { 6097 LatchControlDependentOnPoison = true; 6098 break; 6099 } 6100 } 6101 } 6102 } 6103 6104 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6105 } 6106 6107 ScalarEvolution::LoopProperties 6108 ScalarEvolution::getLoopProperties(const Loop *L) { 6109 using LoopProperties = ScalarEvolution::LoopProperties; 6110 6111 auto Itr = LoopPropertiesCache.find(L); 6112 if (Itr == LoopPropertiesCache.end()) { 6113 auto HasSideEffects = [](Instruction *I) { 6114 if (auto *SI = dyn_cast<StoreInst>(I)) 6115 return !SI->isSimple(); 6116 6117 return I->mayHaveSideEffects(); 6118 }; 6119 6120 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6121 /*HasNoSideEffects*/ true}; 6122 6123 for (auto *BB : L->getBlocks()) 6124 for (auto &I : *BB) { 6125 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6126 LP.HasNoAbnormalExits = false; 6127 if (HasSideEffects(&I)) 6128 LP.HasNoSideEffects = false; 6129 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6130 break; // We're already as pessimistic as we can get. 6131 } 6132 6133 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6134 assert(InsertPair.second && "We just checked!"); 6135 Itr = InsertPair.first; 6136 } 6137 6138 return Itr->second; 6139 } 6140 6141 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6142 if (!isSCEVable(V->getType())) 6143 return getUnknown(V); 6144 6145 if (Instruction *I = dyn_cast<Instruction>(V)) { 6146 // Don't attempt to analyze instructions in blocks that aren't 6147 // reachable. Such instructions don't matter, and they aren't required 6148 // to obey basic rules for definitions dominating uses which this 6149 // analysis depends on. 6150 if (!DT.isReachableFromEntry(I->getParent())) 6151 return getUnknown(UndefValue::get(V->getType())); 6152 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6153 return getConstant(CI); 6154 else if (isa<ConstantPointerNull>(V)) 6155 return getZero(V->getType()); 6156 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6157 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6158 else if (!isa<ConstantExpr>(V)) 6159 return getUnknown(V); 6160 6161 Operator *U = cast<Operator>(V); 6162 if (auto BO = MatchBinaryOp(U, DT)) { 6163 switch (BO->Opcode) { 6164 case Instruction::Add: { 6165 // The simple thing to do would be to just call getSCEV on both operands 6166 // and call getAddExpr with the result. However if we're looking at a 6167 // bunch of things all added together, this can be quite inefficient, 6168 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6169 // Instead, gather up all the operands and make a single getAddExpr call. 6170 // LLVM IR canonical form means we need only traverse the left operands. 6171 SmallVector<const SCEV *, 4> AddOps; 6172 do { 6173 if (BO->Op) { 6174 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6175 AddOps.push_back(OpSCEV); 6176 break; 6177 } 6178 6179 // If a NUW or NSW flag can be applied to the SCEV for this 6180 // addition, then compute the SCEV for this addition by itself 6181 // with a separate call to getAddExpr. We need to do that 6182 // instead of pushing the operands of the addition onto AddOps, 6183 // since the flags are only known to apply to this particular 6184 // addition - they may not apply to other additions that can be 6185 // formed with operands from AddOps. 6186 const SCEV *RHS = getSCEV(BO->RHS); 6187 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6188 if (Flags != SCEV::FlagAnyWrap) { 6189 const SCEV *LHS = getSCEV(BO->LHS); 6190 if (BO->Opcode == Instruction::Sub) 6191 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6192 else 6193 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6194 break; 6195 } 6196 } 6197 6198 if (BO->Opcode == Instruction::Sub) 6199 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6200 else 6201 AddOps.push_back(getSCEV(BO->RHS)); 6202 6203 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6204 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6205 NewBO->Opcode != Instruction::Sub)) { 6206 AddOps.push_back(getSCEV(BO->LHS)); 6207 break; 6208 } 6209 BO = NewBO; 6210 } while (true); 6211 6212 return getAddExpr(AddOps); 6213 } 6214 6215 case Instruction::Mul: { 6216 SmallVector<const SCEV *, 4> MulOps; 6217 do { 6218 if (BO->Op) { 6219 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6220 MulOps.push_back(OpSCEV); 6221 break; 6222 } 6223 6224 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6225 if (Flags != SCEV::FlagAnyWrap) { 6226 MulOps.push_back( 6227 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6228 break; 6229 } 6230 } 6231 6232 MulOps.push_back(getSCEV(BO->RHS)); 6233 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6234 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6235 MulOps.push_back(getSCEV(BO->LHS)); 6236 break; 6237 } 6238 BO = NewBO; 6239 } while (true); 6240 6241 return getMulExpr(MulOps); 6242 } 6243 case Instruction::UDiv: 6244 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6245 case Instruction::URem: 6246 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6247 case Instruction::Sub: { 6248 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6249 if (BO->Op) 6250 Flags = getNoWrapFlagsFromUB(BO->Op); 6251 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6252 } 6253 case Instruction::And: 6254 // For an expression like x&255 that merely masks off the high bits, 6255 // use zext(trunc(x)) as the SCEV expression. 6256 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6257 if (CI->isZero()) 6258 return getSCEV(BO->RHS); 6259 if (CI->isMinusOne()) 6260 return getSCEV(BO->LHS); 6261 const APInt &A = CI->getValue(); 6262 6263 // Instcombine's ShrinkDemandedConstant may strip bits out of 6264 // constants, obscuring what would otherwise be a low-bits mask. 6265 // Use computeKnownBits to compute what ShrinkDemandedConstant 6266 // knew about to reconstruct a low-bits mask value. 6267 unsigned LZ = A.countLeadingZeros(); 6268 unsigned TZ = A.countTrailingZeros(); 6269 unsigned BitWidth = A.getBitWidth(); 6270 KnownBits Known(BitWidth); 6271 computeKnownBits(BO->LHS, Known, getDataLayout(), 6272 0, &AC, nullptr, &DT); 6273 6274 APInt EffectiveMask = 6275 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6276 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6277 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6278 const SCEV *LHS = getSCEV(BO->LHS); 6279 const SCEV *ShiftedLHS = nullptr; 6280 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6281 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6282 // For an expression like (x * 8) & 8, simplify the multiply. 6283 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6284 unsigned GCD = std::min(MulZeros, TZ); 6285 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6286 SmallVector<const SCEV*, 4> MulOps; 6287 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6288 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6289 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6290 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6291 } 6292 } 6293 if (!ShiftedLHS) 6294 ShiftedLHS = getUDivExpr(LHS, MulCount); 6295 return getMulExpr( 6296 getZeroExtendExpr( 6297 getTruncateExpr(ShiftedLHS, 6298 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6299 BO->LHS->getType()), 6300 MulCount); 6301 } 6302 } 6303 break; 6304 6305 case Instruction::Or: 6306 // If the RHS of the Or is a constant, we may have something like: 6307 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6308 // optimizations will transparently handle this case. 6309 // 6310 // In order for this transformation to be safe, the LHS must be of the 6311 // form X*(2^n) and the Or constant must be less than 2^n. 6312 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6313 const SCEV *LHS = getSCEV(BO->LHS); 6314 const APInt &CIVal = CI->getValue(); 6315 if (GetMinTrailingZeros(LHS) >= 6316 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6317 // Build a plain add SCEV. 6318 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6319 // If the LHS of the add was an addrec and it has no-wrap flags, 6320 // transfer the no-wrap flags, since an or won't introduce a wrap. 6321 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6322 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6323 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6324 OldAR->getNoWrapFlags()); 6325 } 6326 return S; 6327 } 6328 } 6329 break; 6330 6331 case Instruction::Xor: 6332 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6333 // If the RHS of xor is -1, then this is a not operation. 6334 if (CI->isMinusOne()) 6335 return getNotSCEV(getSCEV(BO->LHS)); 6336 6337 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6338 // This is a variant of the check for xor with -1, and it handles 6339 // the case where instcombine has trimmed non-demanded bits out 6340 // of an xor with -1. 6341 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6342 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6343 if (LBO->getOpcode() == Instruction::And && 6344 LCI->getValue() == CI->getValue()) 6345 if (const SCEVZeroExtendExpr *Z = 6346 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6347 Type *UTy = BO->LHS->getType(); 6348 const SCEV *Z0 = Z->getOperand(); 6349 Type *Z0Ty = Z0->getType(); 6350 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6351 6352 // If C is a low-bits mask, the zero extend is serving to 6353 // mask off the high bits. Complement the operand and 6354 // re-apply the zext. 6355 if (CI->getValue().isMask(Z0TySize)) 6356 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6357 6358 // If C is a single bit, it may be in the sign-bit position 6359 // before the zero-extend. In this case, represent the xor 6360 // using an add, which is equivalent, and re-apply the zext. 6361 APInt Trunc = CI->getValue().trunc(Z0TySize); 6362 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6363 Trunc.isSignMask()) 6364 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6365 UTy); 6366 } 6367 } 6368 break; 6369 6370 case Instruction::Shl: 6371 // Turn shift left of a constant amount into a multiply. 6372 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6373 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6374 6375 // If the shift count is not less than the bitwidth, the result of 6376 // the shift is undefined. Don't try to analyze it, because the 6377 // resolution chosen here may differ from the resolution chosen in 6378 // other parts of the compiler. 6379 if (SA->getValue().uge(BitWidth)) 6380 break; 6381 6382 // It is currently not resolved how to interpret NSW for left 6383 // shift by BitWidth - 1, so we avoid applying flags in that 6384 // case. Remove this check (or this comment) once the situation 6385 // is resolved. See 6386 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6387 // and http://reviews.llvm.org/D8890 . 6388 auto Flags = SCEV::FlagAnyWrap; 6389 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6390 Flags = getNoWrapFlagsFromUB(BO->Op); 6391 6392 Constant *X = ConstantInt::get( 6393 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6394 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6395 } 6396 break; 6397 6398 case Instruction::AShr: { 6399 // AShr X, C, where C is a constant. 6400 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6401 if (!CI) 6402 break; 6403 6404 Type *OuterTy = BO->LHS->getType(); 6405 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6406 // If the shift count is not less than the bitwidth, the result of 6407 // the shift is undefined. Don't try to analyze it, because the 6408 // resolution chosen here may differ from the resolution chosen in 6409 // other parts of the compiler. 6410 if (CI->getValue().uge(BitWidth)) 6411 break; 6412 6413 if (CI->isZero()) 6414 return getSCEV(BO->LHS); // shift by zero --> noop 6415 6416 uint64_t AShrAmt = CI->getZExtValue(); 6417 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6418 6419 Operator *L = dyn_cast<Operator>(BO->LHS); 6420 if (L && L->getOpcode() == Instruction::Shl) { 6421 // X = Shl A, n 6422 // Y = AShr X, m 6423 // Both n and m are constant. 6424 6425 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6426 if (L->getOperand(1) == BO->RHS) 6427 // For a two-shift sext-inreg, i.e. n = m, 6428 // use sext(trunc(x)) as the SCEV expression. 6429 return getSignExtendExpr( 6430 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6431 6432 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6433 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6434 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6435 if (ShlAmt > AShrAmt) { 6436 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6437 // expression. We already checked that ShlAmt < BitWidth, so 6438 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6439 // ShlAmt - AShrAmt < Amt. 6440 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6441 ShlAmt - AShrAmt); 6442 return getSignExtendExpr( 6443 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6444 getConstant(Mul)), OuterTy); 6445 } 6446 } 6447 } 6448 break; 6449 } 6450 } 6451 } 6452 6453 switch (U->getOpcode()) { 6454 case Instruction::Trunc: 6455 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6456 6457 case Instruction::ZExt: 6458 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6459 6460 case Instruction::SExt: 6461 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6462 // The NSW flag of a subtract does not always survive the conversion to 6463 // A + (-1)*B. By pushing sign extension onto its operands we are much 6464 // more likely to preserve NSW and allow later AddRec optimisations. 6465 // 6466 // NOTE: This is effectively duplicating this logic from getSignExtend: 6467 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6468 // but by that point the NSW information has potentially been lost. 6469 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6470 Type *Ty = U->getType(); 6471 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6472 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6473 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6474 } 6475 } 6476 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6477 6478 case Instruction::BitCast: 6479 // BitCasts are no-op casts so we just eliminate the cast. 6480 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6481 return getSCEV(U->getOperand(0)); 6482 break; 6483 6484 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6485 // lead to pointer expressions which cannot safely be expanded to GEPs, 6486 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6487 // simplifying integer expressions. 6488 6489 case Instruction::GetElementPtr: 6490 return createNodeForGEP(cast<GEPOperator>(U)); 6491 6492 case Instruction::PHI: 6493 return createNodeForPHI(cast<PHINode>(U)); 6494 6495 case Instruction::Select: 6496 // U can also be a select constant expr, which let fall through. Since 6497 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6498 // constant expressions cannot have instructions as operands, we'd have 6499 // returned getUnknown for a select constant expressions anyway. 6500 if (isa<Instruction>(U)) 6501 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6502 U->getOperand(1), U->getOperand(2)); 6503 break; 6504 6505 case Instruction::Call: 6506 case Instruction::Invoke: 6507 if (Value *RV = CallSite(U).getReturnedArgOperand()) 6508 return getSCEV(RV); 6509 break; 6510 } 6511 6512 return getUnknown(V); 6513 } 6514 6515 //===----------------------------------------------------------------------===// 6516 // Iteration Count Computation Code 6517 // 6518 6519 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6520 if (!ExitCount) 6521 return 0; 6522 6523 ConstantInt *ExitConst = ExitCount->getValue(); 6524 6525 // Guard against huge trip counts. 6526 if (ExitConst->getValue().getActiveBits() > 32) 6527 return 0; 6528 6529 // In case of integer overflow, this returns 0, which is correct. 6530 return ((unsigned)ExitConst->getZExtValue()) + 1; 6531 } 6532 6533 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6534 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6535 return getSmallConstantTripCount(L, ExitingBB); 6536 6537 // No trip count information for multiple exits. 6538 return 0; 6539 } 6540 6541 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6542 BasicBlock *ExitingBlock) { 6543 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6544 assert(L->isLoopExiting(ExitingBlock) && 6545 "Exiting block must actually branch out of the loop!"); 6546 const SCEVConstant *ExitCount = 6547 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6548 return getConstantTripCount(ExitCount); 6549 } 6550 6551 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6552 const auto *MaxExitCount = 6553 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6554 return getConstantTripCount(MaxExitCount); 6555 } 6556 6557 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6558 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6559 return getSmallConstantTripMultiple(L, ExitingBB); 6560 6561 // No trip multiple information for multiple exits. 6562 return 0; 6563 } 6564 6565 /// Returns the largest constant divisor of the trip count of this loop as a 6566 /// normal unsigned value, if possible. This means that the actual trip count is 6567 /// always a multiple of the returned value (don't forget the trip count could 6568 /// very well be zero as well!). 6569 /// 6570 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6571 /// multiple of a constant (which is also the case if the trip count is simply 6572 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6573 /// if the trip count is very large (>= 2^32). 6574 /// 6575 /// As explained in the comments for getSmallConstantTripCount, this assumes 6576 /// that control exits the loop via ExitingBlock. 6577 unsigned 6578 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6579 BasicBlock *ExitingBlock) { 6580 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6581 assert(L->isLoopExiting(ExitingBlock) && 6582 "Exiting block must actually branch out of the loop!"); 6583 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6584 if (ExitCount == getCouldNotCompute()) 6585 return 1; 6586 6587 // Get the trip count from the BE count by adding 1. 6588 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6589 6590 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6591 if (!TC) 6592 // Attempt to factor more general cases. Returns the greatest power of 6593 // two divisor. If overflow happens, the trip count expression is still 6594 // divisible by the greatest power of 2 divisor returned. 6595 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6596 6597 ConstantInt *Result = TC->getValue(); 6598 6599 // Guard against huge trip counts (this requires checking 6600 // for zero to handle the case where the trip count == -1 and the 6601 // addition wraps). 6602 if (!Result || Result->getValue().getActiveBits() > 32 || 6603 Result->getValue().getActiveBits() == 0) 6604 return 1; 6605 6606 return (unsigned)Result->getZExtValue(); 6607 } 6608 6609 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6610 BasicBlock *ExitingBlock, 6611 ExitCountKind Kind) { 6612 switch (Kind) { 6613 case Exact: 6614 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6615 case ConstantMaximum: 6616 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6617 }; 6618 llvm_unreachable("Invalid ExitCountKind!"); 6619 } 6620 6621 const SCEV * 6622 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6623 SCEVUnionPredicate &Preds) { 6624 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6625 } 6626 6627 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6628 ExitCountKind Kind) { 6629 switch (Kind) { 6630 case Exact: 6631 return getBackedgeTakenInfo(L).getExact(L, this); 6632 case ConstantMaximum: 6633 return getBackedgeTakenInfo(L).getMax(this); 6634 }; 6635 llvm_unreachable("Invalid ExitCountKind!"); 6636 } 6637 6638 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6639 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6640 } 6641 6642 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6643 static void 6644 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6645 BasicBlock *Header = L->getHeader(); 6646 6647 // Push all Loop-header PHIs onto the Worklist stack. 6648 for (PHINode &PN : Header->phis()) 6649 Worklist.push_back(&PN); 6650 } 6651 6652 const ScalarEvolution::BackedgeTakenInfo & 6653 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6654 auto &BTI = getBackedgeTakenInfo(L); 6655 if (BTI.hasFullInfo()) 6656 return BTI; 6657 6658 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6659 6660 if (!Pair.second) 6661 return Pair.first->second; 6662 6663 BackedgeTakenInfo Result = 6664 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6665 6666 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6667 } 6668 6669 const ScalarEvolution::BackedgeTakenInfo & 6670 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6671 // Initially insert an invalid entry for this loop. If the insertion 6672 // succeeds, proceed to actually compute a backedge-taken count and 6673 // update the value. The temporary CouldNotCompute value tells SCEV 6674 // code elsewhere that it shouldn't attempt to request a new 6675 // backedge-taken count, which could result in infinite recursion. 6676 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6677 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6678 if (!Pair.second) 6679 return Pair.first->second; 6680 6681 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6682 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6683 // must be cleared in this scope. 6684 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6685 6686 // In product build, there are no usage of statistic. 6687 (void)NumTripCountsComputed; 6688 (void)NumTripCountsNotComputed; 6689 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6690 const SCEV *BEExact = Result.getExact(L, this); 6691 if (BEExact != getCouldNotCompute()) { 6692 assert(isLoopInvariant(BEExact, L) && 6693 isLoopInvariant(Result.getMax(this), L) && 6694 "Computed backedge-taken count isn't loop invariant for loop!"); 6695 ++NumTripCountsComputed; 6696 } 6697 else if (Result.getMax(this) == getCouldNotCompute() && 6698 isa<PHINode>(L->getHeader()->begin())) { 6699 // Only count loops that have phi nodes as not being computable. 6700 ++NumTripCountsNotComputed; 6701 } 6702 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6703 6704 // Now that we know more about the trip count for this loop, forget any 6705 // existing SCEV values for PHI nodes in this loop since they are only 6706 // conservative estimates made without the benefit of trip count 6707 // information. This is similar to the code in forgetLoop, except that 6708 // it handles SCEVUnknown PHI nodes specially. 6709 if (Result.hasAnyInfo()) { 6710 SmallVector<Instruction *, 16> Worklist; 6711 PushLoopPHIs(L, Worklist); 6712 6713 SmallPtrSet<Instruction *, 8> Discovered; 6714 while (!Worklist.empty()) { 6715 Instruction *I = Worklist.pop_back_val(); 6716 6717 ValueExprMapType::iterator It = 6718 ValueExprMap.find_as(static_cast<Value *>(I)); 6719 if (It != ValueExprMap.end()) { 6720 const SCEV *Old = It->second; 6721 6722 // SCEVUnknown for a PHI either means that it has an unrecognized 6723 // structure, or it's a PHI that's in the progress of being computed 6724 // by createNodeForPHI. In the former case, additional loop trip 6725 // count information isn't going to change anything. In the later 6726 // case, createNodeForPHI will perform the necessary updates on its 6727 // own when it gets to that point. 6728 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6729 eraseValueFromMap(It->first); 6730 forgetMemoizedResults(Old); 6731 } 6732 if (PHINode *PN = dyn_cast<PHINode>(I)) 6733 ConstantEvolutionLoopExitValue.erase(PN); 6734 } 6735 6736 // Since we don't need to invalidate anything for correctness and we're 6737 // only invalidating to make SCEV's results more precise, we get to stop 6738 // early to avoid invalidating too much. This is especially important in 6739 // cases like: 6740 // 6741 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6742 // loop0: 6743 // %pn0 = phi 6744 // ... 6745 // loop1: 6746 // %pn1 = phi 6747 // ... 6748 // 6749 // where both loop0 and loop1's backedge taken count uses the SCEV 6750 // expression for %v. If we don't have the early stop below then in cases 6751 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6752 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6753 // count for loop1, effectively nullifying SCEV's trip count cache. 6754 for (auto *U : I->users()) 6755 if (auto *I = dyn_cast<Instruction>(U)) { 6756 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6757 if (LoopForUser && L->contains(LoopForUser) && 6758 Discovered.insert(I).second) 6759 Worklist.push_back(I); 6760 } 6761 } 6762 } 6763 6764 // Re-lookup the insert position, since the call to 6765 // computeBackedgeTakenCount above could result in a 6766 // recusive call to getBackedgeTakenInfo (on a different 6767 // loop), which would invalidate the iterator computed 6768 // earlier. 6769 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6770 } 6771 6772 void ScalarEvolution::forgetAllLoops() { 6773 // This method is intended to forget all info about loops. It should 6774 // invalidate caches as if the following happened: 6775 // - The trip counts of all loops have changed arbitrarily 6776 // - Every llvm::Value has been updated in place to produce a different 6777 // result. 6778 BackedgeTakenCounts.clear(); 6779 PredicatedBackedgeTakenCounts.clear(); 6780 LoopPropertiesCache.clear(); 6781 ConstantEvolutionLoopExitValue.clear(); 6782 ValueExprMap.clear(); 6783 ValuesAtScopes.clear(); 6784 LoopDispositions.clear(); 6785 BlockDispositions.clear(); 6786 UnsignedRanges.clear(); 6787 SignedRanges.clear(); 6788 ExprValueMap.clear(); 6789 HasRecMap.clear(); 6790 MinTrailingZerosCache.clear(); 6791 PredicatedSCEVRewrites.clear(); 6792 } 6793 6794 void ScalarEvolution::forgetLoop(const Loop *L) { 6795 // Drop any stored trip count value. 6796 auto RemoveLoopFromBackedgeMap = 6797 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6798 auto BTCPos = Map.find(L); 6799 if (BTCPos != Map.end()) { 6800 BTCPos->second.clear(); 6801 Map.erase(BTCPos); 6802 } 6803 }; 6804 6805 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6806 SmallVector<Instruction *, 32> Worklist; 6807 SmallPtrSet<Instruction *, 16> Visited; 6808 6809 // Iterate over all the loops and sub-loops to drop SCEV information. 6810 while (!LoopWorklist.empty()) { 6811 auto *CurrL = LoopWorklist.pop_back_val(); 6812 6813 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6814 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6815 6816 // Drop information about predicated SCEV rewrites for this loop. 6817 for (auto I = PredicatedSCEVRewrites.begin(); 6818 I != PredicatedSCEVRewrites.end();) { 6819 std::pair<const SCEV *, const Loop *> Entry = I->first; 6820 if (Entry.second == CurrL) 6821 PredicatedSCEVRewrites.erase(I++); 6822 else 6823 ++I; 6824 } 6825 6826 auto LoopUsersItr = LoopUsers.find(CurrL); 6827 if (LoopUsersItr != LoopUsers.end()) { 6828 for (auto *S : LoopUsersItr->second) 6829 forgetMemoizedResults(S); 6830 LoopUsers.erase(LoopUsersItr); 6831 } 6832 6833 // Drop information about expressions based on loop-header PHIs. 6834 PushLoopPHIs(CurrL, Worklist); 6835 6836 while (!Worklist.empty()) { 6837 Instruction *I = Worklist.pop_back_val(); 6838 if (!Visited.insert(I).second) 6839 continue; 6840 6841 ValueExprMapType::iterator It = 6842 ValueExprMap.find_as(static_cast<Value *>(I)); 6843 if (It != ValueExprMap.end()) { 6844 eraseValueFromMap(It->first); 6845 forgetMemoizedResults(It->second); 6846 if (PHINode *PN = dyn_cast<PHINode>(I)) 6847 ConstantEvolutionLoopExitValue.erase(PN); 6848 } 6849 6850 PushDefUseChildren(I, Worklist); 6851 } 6852 6853 LoopPropertiesCache.erase(CurrL); 6854 // Forget all contained loops too, to avoid dangling entries in the 6855 // ValuesAtScopes map. 6856 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6857 } 6858 } 6859 6860 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6861 while (Loop *Parent = L->getParentLoop()) 6862 L = Parent; 6863 forgetLoop(L); 6864 } 6865 6866 void ScalarEvolution::forgetValue(Value *V) { 6867 Instruction *I = dyn_cast<Instruction>(V); 6868 if (!I) return; 6869 6870 // Drop information about expressions based on loop-header PHIs. 6871 SmallVector<Instruction *, 16> Worklist; 6872 Worklist.push_back(I); 6873 6874 SmallPtrSet<Instruction *, 8> Visited; 6875 while (!Worklist.empty()) { 6876 I = Worklist.pop_back_val(); 6877 if (!Visited.insert(I).second) 6878 continue; 6879 6880 ValueExprMapType::iterator It = 6881 ValueExprMap.find_as(static_cast<Value *>(I)); 6882 if (It != ValueExprMap.end()) { 6883 eraseValueFromMap(It->first); 6884 forgetMemoizedResults(It->second); 6885 if (PHINode *PN = dyn_cast<PHINode>(I)) 6886 ConstantEvolutionLoopExitValue.erase(PN); 6887 } 6888 6889 PushDefUseChildren(I, Worklist); 6890 } 6891 } 6892 6893 /// Get the exact loop backedge taken count considering all loop exits. A 6894 /// computable result can only be returned for loops with all exiting blocks 6895 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6896 /// is never skipped. This is a valid assumption as long as the loop exits via 6897 /// that test. For precise results, it is the caller's responsibility to specify 6898 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6899 const SCEV * 6900 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6901 SCEVUnionPredicate *Preds) const { 6902 // If any exits were not computable, the loop is not computable. 6903 if (!isComplete() || ExitNotTaken.empty()) 6904 return SE->getCouldNotCompute(); 6905 6906 const BasicBlock *Latch = L->getLoopLatch(); 6907 // All exiting blocks we have collected must dominate the only backedge. 6908 if (!Latch) 6909 return SE->getCouldNotCompute(); 6910 6911 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6912 // count is simply a minimum out of all these calculated exit counts. 6913 SmallVector<const SCEV *, 2> Ops; 6914 for (auto &ENT : ExitNotTaken) { 6915 const SCEV *BECount = ENT.ExactNotTaken; 6916 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6917 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6918 "We should only have known counts for exiting blocks that dominate " 6919 "latch!"); 6920 6921 Ops.push_back(BECount); 6922 6923 if (Preds && !ENT.hasAlwaysTruePredicate()) 6924 Preds->add(ENT.Predicate.get()); 6925 6926 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6927 "Predicate should be always true!"); 6928 } 6929 6930 return SE->getUMinFromMismatchedTypes(Ops); 6931 } 6932 6933 /// Get the exact not taken count for this loop exit. 6934 const SCEV * 6935 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 6936 ScalarEvolution *SE) const { 6937 for (auto &ENT : ExitNotTaken) 6938 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6939 return ENT.ExactNotTaken; 6940 6941 return SE->getCouldNotCompute(); 6942 } 6943 6944 const SCEV * 6945 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock, 6946 ScalarEvolution *SE) const { 6947 for (auto &ENT : ExitNotTaken) 6948 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 6949 return ENT.MaxNotTaken; 6950 6951 return SE->getCouldNotCompute(); 6952 } 6953 6954 /// getMax - Get the max backedge taken count for the loop. 6955 const SCEV * 6956 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 6957 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6958 return !ENT.hasAlwaysTruePredicate(); 6959 }; 6960 6961 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 6962 return SE->getCouldNotCompute(); 6963 6964 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 6965 "No point in having a non-constant max backedge taken count!"); 6966 return getMax(); 6967 } 6968 6969 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 6970 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 6971 return !ENT.hasAlwaysTruePredicate(); 6972 }; 6973 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 6974 } 6975 6976 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 6977 ScalarEvolution *SE) const { 6978 if (getMax() && getMax() != SE->getCouldNotCompute() && 6979 SE->hasOperand(getMax(), S)) 6980 return true; 6981 6982 for (auto &ENT : ExitNotTaken) 6983 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 6984 SE->hasOperand(ENT.ExactNotTaken, S)) 6985 return true; 6986 6987 return false; 6988 } 6989 6990 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 6991 : ExactNotTaken(E), MaxNotTaken(E) { 6992 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 6993 isa<SCEVConstant>(MaxNotTaken)) && 6994 "No point in having a non-constant max backedge taken count!"); 6995 } 6996 6997 ScalarEvolution::ExitLimit::ExitLimit( 6998 const SCEV *E, const SCEV *M, bool MaxOrZero, 6999 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7000 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7001 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7002 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7003 "Exact is not allowed to be less precise than Max"); 7004 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7005 isa<SCEVConstant>(MaxNotTaken)) && 7006 "No point in having a non-constant max backedge taken count!"); 7007 for (auto *PredSet : PredSetList) 7008 for (auto *P : *PredSet) 7009 addPredicate(P); 7010 } 7011 7012 ScalarEvolution::ExitLimit::ExitLimit( 7013 const SCEV *E, const SCEV *M, bool MaxOrZero, 7014 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7015 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7016 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7017 isa<SCEVConstant>(MaxNotTaken)) && 7018 "No point in having a non-constant max backedge taken count!"); 7019 } 7020 7021 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7022 bool MaxOrZero) 7023 : ExitLimit(E, M, MaxOrZero, None) { 7024 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7025 isa<SCEVConstant>(MaxNotTaken)) && 7026 "No point in having a non-constant max backedge taken count!"); 7027 } 7028 7029 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7030 /// computable exit into a persistent ExitNotTakenInfo array. 7031 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7032 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7033 ExitCounts, 7034 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7035 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7036 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7037 7038 ExitNotTaken.reserve(ExitCounts.size()); 7039 std::transform( 7040 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7041 [&](const EdgeExitInfo &EEI) { 7042 BasicBlock *ExitBB = EEI.first; 7043 const ExitLimit &EL = EEI.second; 7044 if (EL.Predicates.empty()) 7045 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7046 nullptr); 7047 7048 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7049 for (auto *Pred : EL.Predicates) 7050 Predicate->add(Pred); 7051 7052 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7053 std::move(Predicate)); 7054 }); 7055 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7056 "No point in having a non-constant max backedge taken count!"); 7057 } 7058 7059 /// Invalidate this result and free the ExitNotTakenInfo array. 7060 void ScalarEvolution::BackedgeTakenInfo::clear() { 7061 ExitNotTaken.clear(); 7062 } 7063 7064 /// Compute the number of times the backedge of the specified loop will execute. 7065 ScalarEvolution::BackedgeTakenInfo 7066 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7067 bool AllowPredicates) { 7068 SmallVector<BasicBlock *, 8> ExitingBlocks; 7069 L->getExitingBlocks(ExitingBlocks); 7070 7071 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7072 7073 SmallVector<EdgeExitInfo, 4> ExitCounts; 7074 bool CouldComputeBECount = true; 7075 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7076 const SCEV *MustExitMaxBECount = nullptr; 7077 const SCEV *MayExitMaxBECount = nullptr; 7078 bool MustExitMaxOrZero = false; 7079 7080 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7081 // and compute maxBECount. 7082 // Do a union of all the predicates here. 7083 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7084 BasicBlock *ExitBB = ExitingBlocks[i]; 7085 7086 // We canonicalize untaken exits to br (constant), ignore them so that 7087 // proving an exit untaken doesn't negatively impact our ability to reason 7088 // about the loop as whole. 7089 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7090 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7091 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7092 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7093 continue; 7094 } 7095 7096 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7097 7098 assert((AllowPredicates || EL.Predicates.empty()) && 7099 "Predicated exit limit when predicates are not allowed!"); 7100 7101 // 1. For each exit that can be computed, add an entry to ExitCounts. 7102 // CouldComputeBECount is true only if all exits can be computed. 7103 if (EL.ExactNotTaken == getCouldNotCompute()) 7104 // We couldn't compute an exact value for this exit, so 7105 // we won't be able to compute an exact value for the loop. 7106 CouldComputeBECount = false; 7107 else 7108 ExitCounts.emplace_back(ExitBB, EL); 7109 7110 // 2. Derive the loop's MaxBECount from each exit's max number of 7111 // non-exiting iterations. Partition the loop exits into two kinds: 7112 // LoopMustExits and LoopMayExits. 7113 // 7114 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7115 // is a LoopMayExit. If any computable LoopMustExit is found, then 7116 // MaxBECount is the minimum EL.MaxNotTaken of computable 7117 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7118 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7119 // computable EL.MaxNotTaken. 7120 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7121 DT.dominates(ExitBB, Latch)) { 7122 if (!MustExitMaxBECount) { 7123 MustExitMaxBECount = EL.MaxNotTaken; 7124 MustExitMaxOrZero = EL.MaxOrZero; 7125 } else { 7126 MustExitMaxBECount = 7127 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7128 } 7129 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7130 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7131 MayExitMaxBECount = EL.MaxNotTaken; 7132 else { 7133 MayExitMaxBECount = 7134 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7135 } 7136 } 7137 } 7138 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7139 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7140 // The loop backedge will be taken the maximum or zero times if there's 7141 // a single exit that must be taken the maximum or zero times. 7142 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7143 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7144 MaxBECount, MaxOrZero); 7145 } 7146 7147 ScalarEvolution::ExitLimit 7148 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7149 bool AllowPredicates) { 7150 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7151 // If our exiting block does not dominate the latch, then its connection with 7152 // loop's exit limit may be far from trivial. 7153 const BasicBlock *Latch = L->getLoopLatch(); 7154 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7155 return getCouldNotCompute(); 7156 7157 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7158 Instruction *Term = ExitingBlock->getTerminator(); 7159 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7160 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7161 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7162 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7163 "It should have one successor in loop and one exit block!"); 7164 // Proceed to the next level to examine the exit condition expression. 7165 return computeExitLimitFromCond( 7166 L, BI->getCondition(), ExitIfTrue, 7167 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7168 } 7169 7170 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7171 // For switch, make sure that there is a single exit from the loop. 7172 BasicBlock *Exit = nullptr; 7173 for (auto *SBB : successors(ExitingBlock)) 7174 if (!L->contains(SBB)) { 7175 if (Exit) // Multiple exit successors. 7176 return getCouldNotCompute(); 7177 Exit = SBB; 7178 } 7179 assert(Exit && "Exiting block must have at least one exit"); 7180 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7181 /*ControlsExit=*/IsOnlyExit); 7182 } 7183 7184 return getCouldNotCompute(); 7185 } 7186 7187 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7188 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7189 bool ControlsExit, bool AllowPredicates) { 7190 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7191 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7192 ControlsExit, AllowPredicates); 7193 } 7194 7195 Optional<ScalarEvolution::ExitLimit> 7196 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7197 bool ExitIfTrue, bool ControlsExit, 7198 bool AllowPredicates) { 7199 (void)this->L; 7200 (void)this->ExitIfTrue; 7201 (void)this->AllowPredicates; 7202 7203 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7204 this->AllowPredicates == AllowPredicates && 7205 "Variance in assumed invariant key components!"); 7206 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7207 if (Itr == TripCountMap.end()) 7208 return None; 7209 return Itr->second; 7210 } 7211 7212 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7213 bool ExitIfTrue, 7214 bool ControlsExit, 7215 bool AllowPredicates, 7216 const ExitLimit &EL) { 7217 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7218 this->AllowPredicates == AllowPredicates && 7219 "Variance in assumed invariant key components!"); 7220 7221 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7222 assert(InsertResult.second && "Expected successful insertion!"); 7223 (void)InsertResult; 7224 (void)ExitIfTrue; 7225 } 7226 7227 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7228 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7229 bool ControlsExit, bool AllowPredicates) { 7230 7231 if (auto MaybeEL = 7232 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7233 return *MaybeEL; 7234 7235 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7236 ControlsExit, AllowPredicates); 7237 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7238 return EL; 7239 } 7240 7241 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7242 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7243 bool ControlsExit, bool AllowPredicates) { 7244 // Check if the controlling expression for this loop is an And or Or. 7245 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7246 if (BO->getOpcode() == Instruction::And) { 7247 // Recurse on the operands of the and. 7248 bool EitherMayExit = !ExitIfTrue; 7249 ExitLimit EL0 = computeExitLimitFromCondCached( 7250 Cache, L, BO->getOperand(0), ExitIfTrue, 7251 ControlsExit && !EitherMayExit, AllowPredicates); 7252 ExitLimit EL1 = computeExitLimitFromCondCached( 7253 Cache, L, BO->getOperand(1), ExitIfTrue, 7254 ControlsExit && !EitherMayExit, AllowPredicates); 7255 // Be robust against unsimplified IR for the form "and i1 X, true" 7256 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7257 return CI->isOne() ? EL0 : EL1; 7258 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7259 return CI->isOne() ? EL1 : EL0; 7260 const SCEV *BECount = getCouldNotCompute(); 7261 const SCEV *MaxBECount = getCouldNotCompute(); 7262 if (EitherMayExit) { 7263 // Both conditions must be true for the loop to continue executing. 7264 // Choose the less conservative count. 7265 if (EL0.ExactNotTaken == getCouldNotCompute() || 7266 EL1.ExactNotTaken == getCouldNotCompute()) 7267 BECount = getCouldNotCompute(); 7268 else 7269 BECount = 7270 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7271 if (EL0.MaxNotTaken == getCouldNotCompute()) 7272 MaxBECount = EL1.MaxNotTaken; 7273 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7274 MaxBECount = EL0.MaxNotTaken; 7275 else 7276 MaxBECount = 7277 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7278 } else { 7279 // Both conditions must be true at the same time for the loop to exit. 7280 // For now, be conservative. 7281 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7282 MaxBECount = EL0.MaxNotTaken; 7283 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7284 BECount = EL0.ExactNotTaken; 7285 } 7286 7287 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7288 // to be more aggressive when computing BECount than when computing 7289 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7290 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7291 // to not. 7292 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7293 !isa<SCEVCouldNotCompute>(BECount)) 7294 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7295 7296 return ExitLimit(BECount, MaxBECount, false, 7297 {&EL0.Predicates, &EL1.Predicates}); 7298 } 7299 if (BO->getOpcode() == Instruction::Or) { 7300 // Recurse on the operands of the or. 7301 bool EitherMayExit = ExitIfTrue; 7302 ExitLimit EL0 = computeExitLimitFromCondCached( 7303 Cache, L, BO->getOperand(0), ExitIfTrue, 7304 ControlsExit && !EitherMayExit, AllowPredicates); 7305 ExitLimit EL1 = computeExitLimitFromCondCached( 7306 Cache, L, BO->getOperand(1), ExitIfTrue, 7307 ControlsExit && !EitherMayExit, AllowPredicates); 7308 // Be robust against unsimplified IR for the form "or i1 X, true" 7309 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7310 return CI->isZero() ? EL0 : EL1; 7311 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7312 return CI->isZero() ? EL1 : EL0; 7313 const SCEV *BECount = getCouldNotCompute(); 7314 const SCEV *MaxBECount = getCouldNotCompute(); 7315 if (EitherMayExit) { 7316 // Both conditions must be false for the loop to continue executing. 7317 // Choose the less conservative count. 7318 if (EL0.ExactNotTaken == getCouldNotCompute() || 7319 EL1.ExactNotTaken == getCouldNotCompute()) 7320 BECount = getCouldNotCompute(); 7321 else 7322 BECount = 7323 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7324 if (EL0.MaxNotTaken == getCouldNotCompute()) 7325 MaxBECount = EL1.MaxNotTaken; 7326 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7327 MaxBECount = EL0.MaxNotTaken; 7328 else 7329 MaxBECount = 7330 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7331 } else { 7332 // Both conditions must be false at the same time for the loop to exit. 7333 // For now, be conservative. 7334 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7335 MaxBECount = EL0.MaxNotTaken; 7336 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7337 BECount = EL0.ExactNotTaken; 7338 } 7339 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7340 // to be more aggressive when computing BECount than when computing 7341 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7342 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7343 // to not. 7344 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7345 !isa<SCEVCouldNotCompute>(BECount)) 7346 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7347 7348 return ExitLimit(BECount, MaxBECount, false, 7349 {&EL0.Predicates, &EL1.Predicates}); 7350 } 7351 } 7352 7353 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7354 // Proceed to the next level to examine the icmp. 7355 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7356 ExitLimit EL = 7357 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7358 if (EL.hasFullInfo() || !AllowPredicates) 7359 return EL; 7360 7361 // Try again, but use SCEV predicates this time. 7362 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7363 /*AllowPredicates=*/true); 7364 } 7365 7366 // Check for a constant condition. These are normally stripped out by 7367 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7368 // preserve the CFG and is temporarily leaving constant conditions 7369 // in place. 7370 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7371 if (ExitIfTrue == !CI->getZExtValue()) 7372 // The backedge is always taken. 7373 return getCouldNotCompute(); 7374 else 7375 // The backedge is never taken. 7376 return getZero(CI->getType()); 7377 } 7378 7379 // If it's not an integer or pointer comparison then compute it the hard way. 7380 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7381 } 7382 7383 ScalarEvolution::ExitLimit 7384 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7385 ICmpInst *ExitCond, 7386 bool ExitIfTrue, 7387 bool ControlsExit, 7388 bool AllowPredicates) { 7389 // If the condition was exit on true, convert the condition to exit on false 7390 ICmpInst::Predicate Pred; 7391 if (!ExitIfTrue) 7392 Pred = ExitCond->getPredicate(); 7393 else 7394 Pred = ExitCond->getInversePredicate(); 7395 const ICmpInst::Predicate OriginalPred = Pred; 7396 7397 // Handle common loops like: for (X = "string"; *X; ++X) 7398 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7399 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7400 ExitLimit ItCnt = 7401 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7402 if (ItCnt.hasAnyInfo()) 7403 return ItCnt; 7404 } 7405 7406 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7407 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7408 7409 // Try to evaluate any dependencies out of the loop. 7410 LHS = getSCEVAtScope(LHS, L); 7411 RHS = getSCEVAtScope(RHS, L); 7412 7413 // At this point, we would like to compute how many iterations of the 7414 // loop the predicate will return true for these inputs. 7415 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7416 // If there is a loop-invariant, force it into the RHS. 7417 std::swap(LHS, RHS); 7418 Pred = ICmpInst::getSwappedPredicate(Pred); 7419 } 7420 7421 // Simplify the operands before analyzing them. 7422 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7423 7424 // If we have a comparison of a chrec against a constant, try to use value 7425 // ranges to answer this query. 7426 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7427 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7428 if (AddRec->getLoop() == L) { 7429 // Form the constant range. 7430 ConstantRange CompRange = 7431 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7432 7433 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7434 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7435 } 7436 7437 switch (Pred) { 7438 case ICmpInst::ICMP_NE: { // while (X != Y) 7439 // Convert to: while (X-Y != 0) 7440 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7441 AllowPredicates); 7442 if (EL.hasAnyInfo()) return EL; 7443 break; 7444 } 7445 case ICmpInst::ICMP_EQ: { // while (X == Y) 7446 // Convert to: while (X-Y == 0) 7447 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7448 if (EL.hasAnyInfo()) return EL; 7449 break; 7450 } 7451 case ICmpInst::ICMP_SLT: 7452 case ICmpInst::ICMP_ULT: { // while (X < Y) 7453 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7454 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7455 AllowPredicates); 7456 if (EL.hasAnyInfo()) return EL; 7457 break; 7458 } 7459 case ICmpInst::ICMP_SGT: 7460 case ICmpInst::ICMP_UGT: { // while (X > Y) 7461 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7462 ExitLimit EL = 7463 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7464 AllowPredicates); 7465 if (EL.hasAnyInfo()) return EL; 7466 break; 7467 } 7468 default: 7469 break; 7470 } 7471 7472 auto *ExhaustiveCount = 7473 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7474 7475 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7476 return ExhaustiveCount; 7477 7478 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7479 ExitCond->getOperand(1), L, OriginalPred); 7480 } 7481 7482 ScalarEvolution::ExitLimit 7483 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7484 SwitchInst *Switch, 7485 BasicBlock *ExitingBlock, 7486 bool ControlsExit) { 7487 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7488 7489 // Give up if the exit is the default dest of a switch. 7490 if (Switch->getDefaultDest() == ExitingBlock) 7491 return getCouldNotCompute(); 7492 7493 assert(L->contains(Switch->getDefaultDest()) && 7494 "Default case must not exit the loop!"); 7495 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7496 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7497 7498 // while (X != Y) --> while (X-Y != 0) 7499 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7500 if (EL.hasAnyInfo()) 7501 return EL; 7502 7503 return getCouldNotCompute(); 7504 } 7505 7506 static ConstantInt * 7507 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7508 ScalarEvolution &SE) { 7509 const SCEV *InVal = SE.getConstant(C); 7510 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7511 assert(isa<SCEVConstant>(Val) && 7512 "Evaluation of SCEV at constant didn't fold correctly?"); 7513 return cast<SCEVConstant>(Val)->getValue(); 7514 } 7515 7516 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7517 /// compute the backedge execution count. 7518 ScalarEvolution::ExitLimit 7519 ScalarEvolution::computeLoadConstantCompareExitLimit( 7520 LoadInst *LI, 7521 Constant *RHS, 7522 const Loop *L, 7523 ICmpInst::Predicate predicate) { 7524 if (LI->isVolatile()) return getCouldNotCompute(); 7525 7526 // Check to see if the loaded pointer is a getelementptr of a global. 7527 // TODO: Use SCEV instead of manually grubbing with GEPs. 7528 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7529 if (!GEP) return getCouldNotCompute(); 7530 7531 // Make sure that it is really a constant global we are gepping, with an 7532 // initializer, and make sure the first IDX is really 0. 7533 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7534 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7535 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7536 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7537 return getCouldNotCompute(); 7538 7539 // Okay, we allow one non-constant index into the GEP instruction. 7540 Value *VarIdx = nullptr; 7541 std::vector<Constant*> Indexes; 7542 unsigned VarIdxNum = 0; 7543 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7544 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7545 Indexes.push_back(CI); 7546 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7547 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7548 VarIdx = GEP->getOperand(i); 7549 VarIdxNum = i-2; 7550 Indexes.push_back(nullptr); 7551 } 7552 7553 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7554 if (!VarIdx) 7555 return getCouldNotCompute(); 7556 7557 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7558 // Check to see if X is a loop variant variable value now. 7559 const SCEV *Idx = getSCEV(VarIdx); 7560 Idx = getSCEVAtScope(Idx, L); 7561 7562 // We can only recognize very limited forms of loop index expressions, in 7563 // particular, only affine AddRec's like {C1,+,C2}. 7564 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7565 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7566 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7567 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7568 return getCouldNotCompute(); 7569 7570 unsigned MaxSteps = MaxBruteForceIterations; 7571 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7572 ConstantInt *ItCst = ConstantInt::get( 7573 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7574 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7575 7576 // Form the GEP offset. 7577 Indexes[VarIdxNum] = Val; 7578 7579 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7580 Indexes); 7581 if (!Result) break; // Cannot compute! 7582 7583 // Evaluate the condition for this iteration. 7584 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7585 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7586 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7587 ++NumArrayLenItCounts; 7588 return getConstant(ItCst); // Found terminating iteration! 7589 } 7590 } 7591 return getCouldNotCompute(); 7592 } 7593 7594 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7595 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7596 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7597 if (!RHS) 7598 return getCouldNotCompute(); 7599 7600 const BasicBlock *Latch = L->getLoopLatch(); 7601 if (!Latch) 7602 return getCouldNotCompute(); 7603 7604 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7605 if (!Predecessor) 7606 return getCouldNotCompute(); 7607 7608 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7609 // Return LHS in OutLHS and shift_opt in OutOpCode. 7610 auto MatchPositiveShift = 7611 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7612 7613 using namespace PatternMatch; 7614 7615 ConstantInt *ShiftAmt; 7616 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7617 OutOpCode = Instruction::LShr; 7618 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7619 OutOpCode = Instruction::AShr; 7620 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7621 OutOpCode = Instruction::Shl; 7622 else 7623 return false; 7624 7625 return ShiftAmt->getValue().isStrictlyPositive(); 7626 }; 7627 7628 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7629 // 7630 // loop: 7631 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7632 // %iv.shifted = lshr i32 %iv, <positive constant> 7633 // 7634 // Return true on a successful match. Return the corresponding PHI node (%iv 7635 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7636 auto MatchShiftRecurrence = 7637 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7638 Optional<Instruction::BinaryOps> PostShiftOpCode; 7639 7640 { 7641 Instruction::BinaryOps OpC; 7642 Value *V; 7643 7644 // If we encounter a shift instruction, "peel off" the shift operation, 7645 // and remember that we did so. Later when we inspect %iv's backedge 7646 // value, we will make sure that the backedge value uses the same 7647 // operation. 7648 // 7649 // Note: the peeled shift operation does not have to be the same 7650 // instruction as the one feeding into the PHI's backedge value. We only 7651 // really care about it being the same *kind* of shift instruction -- 7652 // that's all that is required for our later inferences to hold. 7653 if (MatchPositiveShift(LHS, V, OpC)) { 7654 PostShiftOpCode = OpC; 7655 LHS = V; 7656 } 7657 } 7658 7659 PNOut = dyn_cast<PHINode>(LHS); 7660 if (!PNOut || PNOut->getParent() != L->getHeader()) 7661 return false; 7662 7663 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7664 Value *OpLHS; 7665 7666 return 7667 // The backedge value for the PHI node must be a shift by a positive 7668 // amount 7669 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7670 7671 // of the PHI node itself 7672 OpLHS == PNOut && 7673 7674 // and the kind of shift should be match the kind of shift we peeled 7675 // off, if any. 7676 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7677 }; 7678 7679 PHINode *PN; 7680 Instruction::BinaryOps OpCode; 7681 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7682 return getCouldNotCompute(); 7683 7684 const DataLayout &DL = getDataLayout(); 7685 7686 // The key rationale for this optimization is that for some kinds of shift 7687 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7688 // within a finite number of iterations. If the condition guarding the 7689 // backedge (in the sense that the backedge is taken if the condition is true) 7690 // is false for the value the shift recurrence stabilizes to, then we know 7691 // that the backedge is taken only a finite number of times. 7692 7693 ConstantInt *StableValue = nullptr; 7694 switch (OpCode) { 7695 default: 7696 llvm_unreachable("Impossible case!"); 7697 7698 case Instruction::AShr: { 7699 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7700 // bitwidth(K) iterations. 7701 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7702 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7703 Predecessor->getTerminator(), &DT); 7704 auto *Ty = cast<IntegerType>(RHS->getType()); 7705 if (Known.isNonNegative()) 7706 StableValue = ConstantInt::get(Ty, 0); 7707 else if (Known.isNegative()) 7708 StableValue = ConstantInt::get(Ty, -1, true); 7709 else 7710 return getCouldNotCompute(); 7711 7712 break; 7713 } 7714 case Instruction::LShr: 7715 case Instruction::Shl: 7716 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7717 // stabilize to 0 in at most bitwidth(K) iterations. 7718 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7719 break; 7720 } 7721 7722 auto *Result = 7723 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7724 assert(Result->getType()->isIntegerTy(1) && 7725 "Otherwise cannot be an operand to a branch instruction"); 7726 7727 if (Result->isZeroValue()) { 7728 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7729 const SCEV *UpperBound = 7730 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7731 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7732 } 7733 7734 return getCouldNotCompute(); 7735 } 7736 7737 /// Return true if we can constant fold an instruction of the specified type, 7738 /// assuming that all operands were constants. 7739 static bool CanConstantFold(const Instruction *I) { 7740 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7741 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7742 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7743 return true; 7744 7745 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7746 if (const Function *F = CI->getCalledFunction()) 7747 return canConstantFoldCallTo(CI, F); 7748 return false; 7749 } 7750 7751 /// Determine whether this instruction can constant evolve within this loop 7752 /// assuming its operands can all constant evolve. 7753 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7754 // An instruction outside of the loop can't be derived from a loop PHI. 7755 if (!L->contains(I)) return false; 7756 7757 if (isa<PHINode>(I)) { 7758 // We don't currently keep track of the control flow needed to evaluate 7759 // PHIs, so we cannot handle PHIs inside of loops. 7760 return L->getHeader() == I->getParent(); 7761 } 7762 7763 // If we won't be able to constant fold this expression even if the operands 7764 // are constants, bail early. 7765 return CanConstantFold(I); 7766 } 7767 7768 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7769 /// recursing through each instruction operand until reaching a loop header phi. 7770 static PHINode * 7771 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7772 DenseMap<Instruction *, PHINode *> &PHIMap, 7773 unsigned Depth) { 7774 if (Depth > MaxConstantEvolvingDepth) 7775 return nullptr; 7776 7777 // Otherwise, we can evaluate this instruction if all of its operands are 7778 // constant or derived from a PHI node themselves. 7779 PHINode *PHI = nullptr; 7780 for (Value *Op : UseInst->operands()) { 7781 if (isa<Constant>(Op)) continue; 7782 7783 Instruction *OpInst = dyn_cast<Instruction>(Op); 7784 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7785 7786 PHINode *P = dyn_cast<PHINode>(OpInst); 7787 if (!P) 7788 // If this operand is already visited, reuse the prior result. 7789 // We may have P != PHI if this is the deepest point at which the 7790 // inconsistent paths meet. 7791 P = PHIMap.lookup(OpInst); 7792 if (!P) { 7793 // Recurse and memoize the results, whether a phi is found or not. 7794 // This recursive call invalidates pointers into PHIMap. 7795 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7796 PHIMap[OpInst] = P; 7797 } 7798 if (!P) 7799 return nullptr; // Not evolving from PHI 7800 if (PHI && PHI != P) 7801 return nullptr; // Evolving from multiple different PHIs. 7802 PHI = P; 7803 } 7804 // This is a expression evolving from a constant PHI! 7805 return PHI; 7806 } 7807 7808 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7809 /// in the loop that V is derived from. We allow arbitrary operations along the 7810 /// way, but the operands of an operation must either be constants or a value 7811 /// derived from a constant PHI. If this expression does not fit with these 7812 /// constraints, return null. 7813 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7814 Instruction *I = dyn_cast<Instruction>(V); 7815 if (!I || !canConstantEvolve(I, L)) return nullptr; 7816 7817 if (PHINode *PN = dyn_cast<PHINode>(I)) 7818 return PN; 7819 7820 // Record non-constant instructions contained by the loop. 7821 DenseMap<Instruction *, PHINode *> PHIMap; 7822 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7823 } 7824 7825 /// EvaluateExpression - Given an expression that passes the 7826 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7827 /// in the loop has the value PHIVal. If we can't fold this expression for some 7828 /// reason, return null. 7829 static Constant *EvaluateExpression(Value *V, const Loop *L, 7830 DenseMap<Instruction *, Constant *> &Vals, 7831 const DataLayout &DL, 7832 const TargetLibraryInfo *TLI) { 7833 // Convenient constant check, but redundant for recursive calls. 7834 if (Constant *C = dyn_cast<Constant>(V)) return C; 7835 Instruction *I = dyn_cast<Instruction>(V); 7836 if (!I) return nullptr; 7837 7838 if (Constant *C = Vals.lookup(I)) return C; 7839 7840 // An instruction inside the loop depends on a value outside the loop that we 7841 // weren't given a mapping for, or a value such as a call inside the loop. 7842 if (!canConstantEvolve(I, L)) return nullptr; 7843 7844 // An unmapped PHI can be due to a branch or another loop inside this loop, 7845 // or due to this not being the initial iteration through a loop where we 7846 // couldn't compute the evolution of this particular PHI last time. 7847 if (isa<PHINode>(I)) return nullptr; 7848 7849 std::vector<Constant*> Operands(I->getNumOperands()); 7850 7851 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7852 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7853 if (!Operand) { 7854 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7855 if (!Operands[i]) return nullptr; 7856 continue; 7857 } 7858 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7859 Vals[Operand] = C; 7860 if (!C) return nullptr; 7861 Operands[i] = C; 7862 } 7863 7864 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7865 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7866 Operands[1], DL, TLI); 7867 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7868 if (!LI->isVolatile()) 7869 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7870 } 7871 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7872 } 7873 7874 7875 // If every incoming value to PN except the one for BB is a specific Constant, 7876 // return that, else return nullptr. 7877 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7878 Constant *IncomingVal = nullptr; 7879 7880 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7881 if (PN->getIncomingBlock(i) == BB) 7882 continue; 7883 7884 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7885 if (!CurrentVal) 7886 return nullptr; 7887 7888 if (IncomingVal != CurrentVal) { 7889 if (IncomingVal) 7890 return nullptr; 7891 IncomingVal = CurrentVal; 7892 } 7893 } 7894 7895 return IncomingVal; 7896 } 7897 7898 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7899 /// in the header of its containing loop, we know the loop executes a 7900 /// constant number of times, and the PHI node is just a recurrence 7901 /// involving constants, fold it. 7902 Constant * 7903 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7904 const APInt &BEs, 7905 const Loop *L) { 7906 auto I = ConstantEvolutionLoopExitValue.find(PN); 7907 if (I != ConstantEvolutionLoopExitValue.end()) 7908 return I->second; 7909 7910 if (BEs.ugt(MaxBruteForceIterations)) 7911 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7912 7913 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7914 7915 DenseMap<Instruction *, Constant *> CurrentIterVals; 7916 BasicBlock *Header = L->getHeader(); 7917 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7918 7919 BasicBlock *Latch = L->getLoopLatch(); 7920 if (!Latch) 7921 return nullptr; 7922 7923 for (PHINode &PHI : Header->phis()) { 7924 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7925 CurrentIterVals[&PHI] = StartCST; 7926 } 7927 if (!CurrentIterVals.count(PN)) 7928 return RetVal = nullptr; 7929 7930 Value *BEValue = PN->getIncomingValueForBlock(Latch); 7931 7932 // Execute the loop symbolically to determine the exit value. 7933 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 7934 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 7935 7936 unsigned NumIterations = BEs.getZExtValue(); // must be in range 7937 unsigned IterationNum = 0; 7938 const DataLayout &DL = getDataLayout(); 7939 for (; ; ++IterationNum) { 7940 if (IterationNum == NumIterations) 7941 return RetVal = CurrentIterVals[PN]; // Got exit value! 7942 7943 // Compute the value of the PHIs for the next iteration. 7944 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 7945 DenseMap<Instruction *, Constant *> NextIterVals; 7946 Constant *NextPHI = 7947 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7948 if (!NextPHI) 7949 return nullptr; // Couldn't evaluate! 7950 NextIterVals[PN] = NextPHI; 7951 7952 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 7953 7954 // Also evaluate the other PHI nodes. However, we don't get to stop if we 7955 // cease to be able to evaluate one of them or if they stop evolving, 7956 // because that doesn't necessarily prevent us from computing PN. 7957 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 7958 for (const auto &I : CurrentIterVals) { 7959 PHINode *PHI = dyn_cast<PHINode>(I.first); 7960 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 7961 PHIsToCompute.emplace_back(PHI, I.second); 7962 } 7963 // We use two distinct loops because EvaluateExpression may invalidate any 7964 // iterators into CurrentIterVals. 7965 for (const auto &I : PHIsToCompute) { 7966 PHINode *PHI = I.first; 7967 Constant *&NextPHI = NextIterVals[PHI]; 7968 if (!NextPHI) { // Not already computed. 7969 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 7970 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 7971 } 7972 if (NextPHI != I.second) 7973 StoppedEvolving = false; 7974 } 7975 7976 // If all entries in CurrentIterVals == NextIterVals then we can stop 7977 // iterating, the loop can't continue to change. 7978 if (StoppedEvolving) 7979 return RetVal = CurrentIterVals[PN]; 7980 7981 CurrentIterVals.swap(NextIterVals); 7982 } 7983 } 7984 7985 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 7986 Value *Cond, 7987 bool ExitWhen) { 7988 PHINode *PN = getConstantEvolvingPHI(Cond, L); 7989 if (!PN) return getCouldNotCompute(); 7990 7991 // If the loop is canonicalized, the PHI will have exactly two entries. 7992 // That's the only form we support here. 7993 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 7994 7995 DenseMap<Instruction *, Constant *> CurrentIterVals; 7996 BasicBlock *Header = L->getHeader(); 7997 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7998 7999 BasicBlock *Latch = L->getLoopLatch(); 8000 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8001 8002 for (PHINode &PHI : Header->phis()) { 8003 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8004 CurrentIterVals[&PHI] = StartCST; 8005 } 8006 if (!CurrentIterVals.count(PN)) 8007 return getCouldNotCompute(); 8008 8009 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8010 // the loop symbolically to determine when the condition gets a value of 8011 // "ExitWhen". 8012 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8013 const DataLayout &DL = getDataLayout(); 8014 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8015 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8016 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8017 8018 // Couldn't symbolically evaluate. 8019 if (!CondVal) return getCouldNotCompute(); 8020 8021 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8022 ++NumBruteForceTripCountsComputed; 8023 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8024 } 8025 8026 // Update all the PHI nodes for the next iteration. 8027 DenseMap<Instruction *, Constant *> NextIterVals; 8028 8029 // Create a list of which PHIs we need to compute. We want to do this before 8030 // calling EvaluateExpression on them because that may invalidate iterators 8031 // into CurrentIterVals. 8032 SmallVector<PHINode *, 8> PHIsToCompute; 8033 for (const auto &I : CurrentIterVals) { 8034 PHINode *PHI = dyn_cast<PHINode>(I.first); 8035 if (!PHI || PHI->getParent() != Header) continue; 8036 PHIsToCompute.push_back(PHI); 8037 } 8038 for (PHINode *PHI : PHIsToCompute) { 8039 Constant *&NextPHI = NextIterVals[PHI]; 8040 if (NextPHI) continue; // Already computed! 8041 8042 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8043 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8044 } 8045 CurrentIterVals.swap(NextIterVals); 8046 } 8047 8048 // Too many iterations were needed to evaluate. 8049 return getCouldNotCompute(); 8050 } 8051 8052 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8053 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8054 ValuesAtScopes[V]; 8055 // Check to see if we've folded this expression at this loop before. 8056 for (auto &LS : Values) 8057 if (LS.first == L) 8058 return LS.second ? LS.second : V; 8059 8060 Values.emplace_back(L, nullptr); 8061 8062 // Otherwise compute it. 8063 const SCEV *C = computeSCEVAtScope(V, L); 8064 for (auto &LS : reverse(ValuesAtScopes[V])) 8065 if (LS.first == L) { 8066 LS.second = C; 8067 break; 8068 } 8069 return C; 8070 } 8071 8072 /// This builds up a Constant using the ConstantExpr interface. That way, we 8073 /// will return Constants for objects which aren't represented by a 8074 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8075 /// Returns NULL if the SCEV isn't representable as a Constant. 8076 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8077 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8078 case scCouldNotCompute: 8079 case scAddRecExpr: 8080 break; 8081 case scConstant: 8082 return cast<SCEVConstant>(V)->getValue(); 8083 case scUnknown: 8084 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8085 case scSignExtend: { 8086 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8087 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8088 return ConstantExpr::getSExt(CastOp, SS->getType()); 8089 break; 8090 } 8091 case scZeroExtend: { 8092 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8093 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8094 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8095 break; 8096 } 8097 case scTruncate: { 8098 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8099 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8100 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8101 break; 8102 } 8103 case scAddExpr: { 8104 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8105 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8106 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8107 unsigned AS = PTy->getAddressSpace(); 8108 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8109 C = ConstantExpr::getBitCast(C, DestPtrTy); 8110 } 8111 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8112 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8113 if (!C2) return nullptr; 8114 8115 // First pointer! 8116 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8117 unsigned AS = C2->getType()->getPointerAddressSpace(); 8118 std::swap(C, C2); 8119 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8120 // The offsets have been converted to bytes. We can add bytes to an 8121 // i8* by GEP with the byte count in the first index. 8122 C = ConstantExpr::getBitCast(C, DestPtrTy); 8123 } 8124 8125 // Don't bother trying to sum two pointers. We probably can't 8126 // statically compute a load that results from it anyway. 8127 if (C2->getType()->isPointerTy()) 8128 return nullptr; 8129 8130 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8131 if (PTy->getElementType()->isStructTy()) 8132 C2 = ConstantExpr::getIntegerCast( 8133 C2, Type::getInt32Ty(C->getContext()), true); 8134 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8135 } else 8136 C = ConstantExpr::getAdd(C, C2); 8137 } 8138 return C; 8139 } 8140 break; 8141 } 8142 case scMulExpr: { 8143 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8144 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8145 // Don't bother with pointers at all. 8146 if (C->getType()->isPointerTy()) return nullptr; 8147 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8148 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8149 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8150 C = ConstantExpr::getMul(C, C2); 8151 } 8152 return C; 8153 } 8154 break; 8155 } 8156 case scUDivExpr: { 8157 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8158 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8159 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8160 if (LHS->getType() == RHS->getType()) 8161 return ConstantExpr::getUDiv(LHS, RHS); 8162 break; 8163 } 8164 case scSMaxExpr: 8165 case scUMaxExpr: 8166 case scSMinExpr: 8167 case scUMinExpr: 8168 break; // TODO: smax, umax, smin, umax. 8169 } 8170 return nullptr; 8171 } 8172 8173 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8174 if (isa<SCEVConstant>(V)) return V; 8175 8176 // If this instruction is evolved from a constant-evolving PHI, compute the 8177 // exit value from the loop without using SCEVs. 8178 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8179 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8180 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8181 const Loop *LI = this->LI[I->getParent()]; 8182 // Looking for loop exit value. 8183 if (LI && LI->getParentLoop() == L && 8184 PN->getParent() == LI->getHeader()) { 8185 // Okay, there is no closed form solution for the PHI node. Check 8186 // to see if the loop that contains it has a known backedge-taken 8187 // count. If so, we may be able to force computation of the exit 8188 // value. 8189 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8190 // This trivial case can show up in some degenerate cases where 8191 // the incoming IR has not yet been fully simplified. 8192 if (BackedgeTakenCount->isZero()) { 8193 Value *InitValue = nullptr; 8194 bool MultipleInitValues = false; 8195 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8196 if (!LI->contains(PN->getIncomingBlock(i))) { 8197 if (!InitValue) 8198 InitValue = PN->getIncomingValue(i); 8199 else if (InitValue != PN->getIncomingValue(i)) { 8200 MultipleInitValues = true; 8201 break; 8202 } 8203 } 8204 } 8205 if (!MultipleInitValues && InitValue) 8206 return getSCEV(InitValue); 8207 } 8208 // Do we have a loop invariant value flowing around the backedge 8209 // for a loop which must execute the backedge? 8210 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8211 isKnownPositive(BackedgeTakenCount) && 8212 PN->getNumIncomingValues() == 2) { 8213 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8214 const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred)); 8215 if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent())) 8216 return OnBackedge; 8217 } 8218 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8219 // Okay, we know how many times the containing loop executes. If 8220 // this is a constant evolving PHI node, get the final value at 8221 // the specified iteration number. 8222 Constant *RV = 8223 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8224 if (RV) return getSCEV(RV); 8225 } 8226 } 8227 8228 // If there is a single-input Phi, evaluate it at our scope. If we can 8229 // prove that this replacement does not break LCSSA form, use new value. 8230 if (PN->getNumOperands() == 1) { 8231 const SCEV *Input = getSCEV(PN->getOperand(0)); 8232 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8233 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8234 // for the simplest case just support constants. 8235 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8236 } 8237 } 8238 8239 // Okay, this is an expression that we cannot symbolically evaluate 8240 // into a SCEV. Check to see if it's possible to symbolically evaluate 8241 // the arguments into constants, and if so, try to constant propagate the 8242 // result. This is particularly useful for computing loop exit values. 8243 if (CanConstantFold(I)) { 8244 SmallVector<Constant *, 4> Operands; 8245 bool MadeImprovement = false; 8246 for (Value *Op : I->operands()) { 8247 if (Constant *C = dyn_cast<Constant>(Op)) { 8248 Operands.push_back(C); 8249 continue; 8250 } 8251 8252 // If any of the operands is non-constant and if they are 8253 // non-integer and non-pointer, don't even try to analyze them 8254 // with scev techniques. 8255 if (!isSCEVable(Op->getType())) 8256 return V; 8257 8258 const SCEV *OrigV = getSCEV(Op); 8259 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8260 MadeImprovement |= OrigV != OpV; 8261 8262 Constant *C = BuildConstantFromSCEV(OpV); 8263 if (!C) return V; 8264 if (C->getType() != Op->getType()) 8265 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8266 Op->getType(), 8267 false), 8268 C, Op->getType()); 8269 Operands.push_back(C); 8270 } 8271 8272 // Check to see if getSCEVAtScope actually made an improvement. 8273 if (MadeImprovement) { 8274 Constant *C = nullptr; 8275 const DataLayout &DL = getDataLayout(); 8276 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8277 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8278 Operands[1], DL, &TLI); 8279 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8280 if (!LI->isVolatile()) 8281 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8282 } else 8283 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8284 if (!C) return V; 8285 return getSCEV(C); 8286 } 8287 } 8288 } 8289 8290 // This is some other type of SCEVUnknown, just return it. 8291 return V; 8292 } 8293 8294 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8295 // Avoid performing the look-up in the common case where the specified 8296 // expression has no loop-variant portions. 8297 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8298 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8299 if (OpAtScope != Comm->getOperand(i)) { 8300 // Okay, at least one of these operands is loop variant but might be 8301 // foldable. Build a new instance of the folded commutative expression. 8302 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8303 Comm->op_begin()+i); 8304 NewOps.push_back(OpAtScope); 8305 8306 for (++i; i != e; ++i) { 8307 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8308 NewOps.push_back(OpAtScope); 8309 } 8310 if (isa<SCEVAddExpr>(Comm)) 8311 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8312 if (isa<SCEVMulExpr>(Comm)) 8313 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8314 if (isa<SCEVMinMaxExpr>(Comm)) 8315 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8316 llvm_unreachable("Unknown commutative SCEV type!"); 8317 } 8318 } 8319 // If we got here, all operands are loop invariant. 8320 return Comm; 8321 } 8322 8323 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8324 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8325 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8326 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8327 return Div; // must be loop invariant 8328 return getUDivExpr(LHS, RHS); 8329 } 8330 8331 // If this is a loop recurrence for a loop that does not contain L, then we 8332 // are dealing with the final value computed by the loop. 8333 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8334 // First, attempt to evaluate each operand. 8335 // Avoid performing the look-up in the common case where the specified 8336 // expression has no loop-variant portions. 8337 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8338 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8339 if (OpAtScope == AddRec->getOperand(i)) 8340 continue; 8341 8342 // Okay, at least one of these operands is loop variant but might be 8343 // foldable. Build a new instance of the folded commutative expression. 8344 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8345 AddRec->op_begin()+i); 8346 NewOps.push_back(OpAtScope); 8347 for (++i; i != e; ++i) 8348 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8349 8350 const SCEV *FoldedRec = 8351 getAddRecExpr(NewOps, AddRec->getLoop(), 8352 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8353 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8354 // The addrec may be folded to a nonrecurrence, for example, if the 8355 // induction variable is multiplied by zero after constant folding. Go 8356 // ahead and return the folded value. 8357 if (!AddRec) 8358 return FoldedRec; 8359 break; 8360 } 8361 8362 // If the scope is outside the addrec's loop, evaluate it by using the 8363 // loop exit value of the addrec. 8364 if (!AddRec->getLoop()->contains(L)) { 8365 // To evaluate this recurrence, we need to know how many times the AddRec 8366 // loop iterates. Compute this now. 8367 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8368 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8369 8370 // Then, evaluate the AddRec. 8371 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8372 } 8373 8374 return AddRec; 8375 } 8376 8377 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8378 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8379 if (Op == Cast->getOperand()) 8380 return Cast; // must be loop invariant 8381 return getZeroExtendExpr(Op, Cast->getType()); 8382 } 8383 8384 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8385 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8386 if (Op == Cast->getOperand()) 8387 return Cast; // must be loop invariant 8388 return getSignExtendExpr(Op, Cast->getType()); 8389 } 8390 8391 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8392 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8393 if (Op == Cast->getOperand()) 8394 return Cast; // must be loop invariant 8395 return getTruncateExpr(Op, Cast->getType()); 8396 } 8397 8398 llvm_unreachable("Unknown SCEV type!"); 8399 } 8400 8401 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8402 return getSCEVAtScope(getSCEV(V), L); 8403 } 8404 8405 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8406 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8407 return stripInjectiveFunctions(ZExt->getOperand()); 8408 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8409 return stripInjectiveFunctions(SExt->getOperand()); 8410 return S; 8411 } 8412 8413 /// Finds the minimum unsigned root of the following equation: 8414 /// 8415 /// A * X = B (mod N) 8416 /// 8417 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8418 /// A and B isn't important. 8419 /// 8420 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8421 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8422 ScalarEvolution &SE) { 8423 uint32_t BW = A.getBitWidth(); 8424 assert(BW == SE.getTypeSizeInBits(B->getType())); 8425 assert(A != 0 && "A must be non-zero."); 8426 8427 // 1. D = gcd(A, N) 8428 // 8429 // The gcd of A and N may have only one prime factor: 2. The number of 8430 // trailing zeros in A is its multiplicity 8431 uint32_t Mult2 = A.countTrailingZeros(); 8432 // D = 2^Mult2 8433 8434 // 2. Check if B is divisible by D. 8435 // 8436 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8437 // is not less than multiplicity of this prime factor for D. 8438 if (SE.GetMinTrailingZeros(B) < Mult2) 8439 return SE.getCouldNotCompute(); 8440 8441 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8442 // modulo (N / D). 8443 // 8444 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8445 // (N / D) in general. The inverse itself always fits into BW bits, though, 8446 // so we immediately truncate it. 8447 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8448 APInt Mod(BW + 1, 0); 8449 Mod.setBit(BW - Mult2); // Mod = N / D 8450 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8451 8452 // 4. Compute the minimum unsigned root of the equation: 8453 // I * (B / D) mod (N / D) 8454 // To simplify the computation, we factor out the divide by D: 8455 // (I * B mod N) / D 8456 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8457 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8458 } 8459 8460 /// For a given quadratic addrec, generate coefficients of the corresponding 8461 /// quadratic equation, multiplied by a common value to ensure that they are 8462 /// integers. 8463 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8464 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8465 /// were multiplied by, and BitWidth is the bit width of the original addrec 8466 /// coefficients. 8467 /// This function returns None if the addrec coefficients are not compile- 8468 /// time constants. 8469 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8470 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8471 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8472 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8473 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8474 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8475 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8476 << *AddRec << '\n'); 8477 8478 // We currently can only solve this if the coefficients are constants. 8479 if (!LC || !MC || !NC) { 8480 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8481 return None; 8482 } 8483 8484 APInt L = LC->getAPInt(); 8485 APInt M = MC->getAPInt(); 8486 APInt N = NC->getAPInt(); 8487 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8488 8489 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8490 unsigned NewWidth = BitWidth + 1; 8491 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8492 << BitWidth << '\n'); 8493 // The sign-extension (as opposed to a zero-extension) here matches the 8494 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8495 N = N.sext(NewWidth); 8496 M = M.sext(NewWidth); 8497 L = L.sext(NewWidth); 8498 8499 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8500 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8501 // L+M, L+2M+N, L+3M+3N, ... 8502 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8503 // 8504 // The equation Acc = 0 is then 8505 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8506 // In a quadratic form it becomes: 8507 // N n^2 + (2M-N) n + 2L = 0. 8508 8509 APInt A = N; 8510 APInt B = 2 * M - A; 8511 APInt C = 2 * L; 8512 APInt T = APInt(NewWidth, 2); 8513 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8514 << "x + " << C << ", coeff bw: " << NewWidth 8515 << ", multiplied by " << T << '\n'); 8516 return std::make_tuple(A, B, C, T, BitWidth); 8517 } 8518 8519 /// Helper function to compare optional APInts: 8520 /// (a) if X and Y both exist, return min(X, Y), 8521 /// (b) if neither X nor Y exist, return None, 8522 /// (c) if exactly one of X and Y exists, return that value. 8523 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8524 if (X.hasValue() && Y.hasValue()) { 8525 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8526 APInt XW = X->sextOrSelf(W); 8527 APInt YW = Y->sextOrSelf(W); 8528 return XW.slt(YW) ? *X : *Y; 8529 } 8530 if (!X.hasValue() && !Y.hasValue()) 8531 return None; 8532 return X.hasValue() ? *X : *Y; 8533 } 8534 8535 /// Helper function to truncate an optional APInt to a given BitWidth. 8536 /// When solving addrec-related equations, it is preferable to return a value 8537 /// that has the same bit width as the original addrec's coefficients. If the 8538 /// solution fits in the original bit width, truncate it (except for i1). 8539 /// Returning a value of a different bit width may inhibit some optimizations. 8540 /// 8541 /// In general, a solution to a quadratic equation generated from an addrec 8542 /// may require BW+1 bits, where BW is the bit width of the addrec's 8543 /// coefficients. The reason is that the coefficients of the quadratic 8544 /// equation are BW+1 bits wide (to avoid truncation when converting from 8545 /// the addrec to the equation). 8546 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8547 if (!X.hasValue()) 8548 return None; 8549 unsigned W = X->getBitWidth(); 8550 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8551 return X->trunc(BitWidth); 8552 return X; 8553 } 8554 8555 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8556 /// iterations. The values L, M, N are assumed to be signed, and they 8557 /// should all have the same bit widths. 8558 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8559 /// where BW is the bit width of the addrec's coefficients. 8560 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8561 /// returned as such, otherwise the bit width of the returned value may 8562 /// be greater than BW. 8563 /// 8564 /// This function returns None if 8565 /// (a) the addrec coefficients are not constant, or 8566 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8567 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8568 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8569 static Optional<APInt> 8570 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8571 APInt A, B, C, M; 8572 unsigned BitWidth; 8573 auto T = GetQuadraticEquation(AddRec); 8574 if (!T.hasValue()) 8575 return None; 8576 8577 std::tie(A, B, C, M, BitWidth) = *T; 8578 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8579 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8580 if (!X.hasValue()) 8581 return None; 8582 8583 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8584 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8585 if (!V->isZero()) 8586 return None; 8587 8588 return TruncIfPossible(X, BitWidth); 8589 } 8590 8591 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8592 /// iterations. The values M, N are assumed to be signed, and they 8593 /// should all have the same bit widths. 8594 /// Find the least n such that c(n) does not belong to the given range, 8595 /// while c(n-1) does. 8596 /// 8597 /// This function returns None if 8598 /// (a) the addrec coefficients are not constant, or 8599 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8600 /// bounds of the range. 8601 static Optional<APInt> 8602 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8603 const ConstantRange &Range, ScalarEvolution &SE) { 8604 assert(AddRec->getOperand(0)->isZero() && 8605 "Starting value of addrec should be 0"); 8606 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8607 << Range << ", addrec " << *AddRec << '\n'); 8608 // This case is handled in getNumIterationsInRange. Here we can assume that 8609 // we start in the range. 8610 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8611 "Addrec's initial value should be in range"); 8612 8613 APInt A, B, C, M; 8614 unsigned BitWidth; 8615 auto T = GetQuadraticEquation(AddRec); 8616 if (!T.hasValue()) 8617 return None; 8618 8619 // Be careful about the return value: there can be two reasons for not 8620 // returning an actual number. First, if no solutions to the equations 8621 // were found, and second, if the solutions don't leave the given range. 8622 // The first case means that the actual solution is "unknown", the second 8623 // means that it's known, but not valid. If the solution is unknown, we 8624 // cannot make any conclusions. 8625 // Return a pair: the optional solution and a flag indicating if the 8626 // solution was found. 8627 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8628 // Solve for signed overflow and unsigned overflow, pick the lower 8629 // solution. 8630 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8631 << Bound << " (before multiplying by " << M << ")\n"); 8632 Bound *= M; // The quadratic equation multiplier. 8633 8634 Optional<APInt> SO = None; 8635 if (BitWidth > 1) { 8636 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8637 "signed overflow\n"); 8638 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8639 } 8640 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8641 "unsigned overflow\n"); 8642 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8643 BitWidth+1); 8644 8645 auto LeavesRange = [&] (const APInt &X) { 8646 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8647 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8648 if (Range.contains(V0->getValue())) 8649 return false; 8650 // X should be at least 1, so X-1 is non-negative. 8651 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8652 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8653 if (Range.contains(V1->getValue())) 8654 return true; 8655 return false; 8656 }; 8657 8658 // If SolveQuadraticEquationWrap returns None, it means that there can 8659 // be a solution, but the function failed to find it. We cannot treat it 8660 // as "no solution". 8661 if (!SO.hasValue() || !UO.hasValue()) 8662 return { None, false }; 8663 8664 // Check the smaller value first to see if it leaves the range. 8665 // At this point, both SO and UO must have values. 8666 Optional<APInt> Min = MinOptional(SO, UO); 8667 if (LeavesRange(*Min)) 8668 return { Min, true }; 8669 Optional<APInt> Max = Min == SO ? UO : SO; 8670 if (LeavesRange(*Max)) 8671 return { Max, true }; 8672 8673 // Solutions were found, but were eliminated, hence the "true". 8674 return { None, true }; 8675 }; 8676 8677 std::tie(A, B, C, M, BitWidth) = *T; 8678 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8679 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8680 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8681 auto SL = SolveForBoundary(Lower); 8682 auto SU = SolveForBoundary(Upper); 8683 // If any of the solutions was unknown, no meaninigful conclusions can 8684 // be made. 8685 if (!SL.second || !SU.second) 8686 return None; 8687 8688 // Claim: The correct solution is not some value between Min and Max. 8689 // 8690 // Justification: Assuming that Min and Max are different values, one of 8691 // them is when the first signed overflow happens, the other is when the 8692 // first unsigned overflow happens. Crossing the range boundary is only 8693 // possible via an overflow (treating 0 as a special case of it, modeling 8694 // an overflow as crossing k*2^W for some k). 8695 // 8696 // The interesting case here is when Min was eliminated as an invalid 8697 // solution, but Max was not. The argument is that if there was another 8698 // overflow between Min and Max, it would also have been eliminated if 8699 // it was considered. 8700 // 8701 // For a given boundary, it is possible to have two overflows of the same 8702 // type (signed/unsigned) without having the other type in between: this 8703 // can happen when the vertex of the parabola is between the iterations 8704 // corresponding to the overflows. This is only possible when the two 8705 // overflows cross k*2^W for the same k. In such case, if the second one 8706 // left the range (and was the first one to do so), the first overflow 8707 // would have to enter the range, which would mean that either we had left 8708 // the range before or that we started outside of it. Both of these cases 8709 // are contradictions. 8710 // 8711 // Claim: In the case where SolveForBoundary returns None, the correct 8712 // solution is not some value between the Max for this boundary and the 8713 // Min of the other boundary. 8714 // 8715 // Justification: Assume that we had such Max_A and Min_B corresponding 8716 // to range boundaries A and B and such that Max_A < Min_B. If there was 8717 // a solution between Max_A and Min_B, it would have to be caused by an 8718 // overflow corresponding to either A or B. It cannot correspond to B, 8719 // since Min_B is the first occurrence of such an overflow. If it 8720 // corresponded to A, it would have to be either a signed or an unsigned 8721 // overflow that is larger than both eliminated overflows for A. But 8722 // between the eliminated overflows and this overflow, the values would 8723 // cover the entire value space, thus crossing the other boundary, which 8724 // is a contradiction. 8725 8726 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8727 } 8728 8729 ScalarEvolution::ExitLimit 8730 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8731 bool AllowPredicates) { 8732 8733 // This is only used for loops with a "x != y" exit test. The exit condition 8734 // is now expressed as a single expression, V = x-y. So the exit test is 8735 // effectively V != 0. We know and take advantage of the fact that this 8736 // expression only being used in a comparison by zero context. 8737 8738 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8739 // If the value is a constant 8740 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8741 // If the value is already zero, the branch will execute zero times. 8742 if (C->getValue()->isZero()) return C; 8743 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8744 } 8745 8746 const SCEVAddRecExpr *AddRec = 8747 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8748 8749 if (!AddRec && AllowPredicates) 8750 // Try to make this an AddRec using runtime tests, in the first X 8751 // iterations of this loop, where X is the SCEV expression found by the 8752 // algorithm below. 8753 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8754 8755 if (!AddRec || AddRec->getLoop() != L) 8756 return getCouldNotCompute(); 8757 8758 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8759 // the quadratic equation to solve it. 8760 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8761 // We can only use this value if the chrec ends up with an exact zero 8762 // value at this index. When solving for "X*X != 5", for example, we 8763 // should not accept a root of 2. 8764 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8765 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8766 return ExitLimit(R, R, false, Predicates); 8767 } 8768 return getCouldNotCompute(); 8769 } 8770 8771 // Otherwise we can only handle this if it is affine. 8772 if (!AddRec->isAffine()) 8773 return getCouldNotCompute(); 8774 8775 // If this is an affine expression, the execution count of this branch is 8776 // the minimum unsigned root of the following equation: 8777 // 8778 // Start + Step*N = 0 (mod 2^BW) 8779 // 8780 // equivalent to: 8781 // 8782 // Step*N = -Start (mod 2^BW) 8783 // 8784 // where BW is the common bit width of Start and Step. 8785 8786 // Get the initial value for the loop. 8787 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8788 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8789 8790 // For now we handle only constant steps. 8791 // 8792 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8793 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8794 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8795 // We have not yet seen any such cases. 8796 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8797 if (!StepC || StepC->getValue()->isZero()) 8798 return getCouldNotCompute(); 8799 8800 // For positive steps (counting up until unsigned overflow): 8801 // N = -Start/Step (as unsigned) 8802 // For negative steps (counting down to zero): 8803 // N = Start/-Step 8804 // First compute the unsigned distance from zero in the direction of Step. 8805 bool CountDown = StepC->getAPInt().isNegative(); 8806 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8807 8808 // Handle unitary steps, which cannot wraparound. 8809 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8810 // N = Distance (as unsigned) 8811 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8812 APInt MaxBECount = getUnsignedRangeMax(Distance); 8813 8814 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8815 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8816 // case, and see if we can improve the bound. 8817 // 8818 // Explicitly handling this here is necessary because getUnsignedRange 8819 // isn't context-sensitive; it doesn't know that we only care about the 8820 // range inside the loop. 8821 const SCEV *Zero = getZero(Distance->getType()); 8822 const SCEV *One = getOne(Distance->getType()); 8823 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8824 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8825 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8826 // as "unsigned_max(Distance + 1) - 1". 8827 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8828 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8829 } 8830 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8831 } 8832 8833 // If the condition controls loop exit (the loop exits only if the expression 8834 // is true) and the addition is no-wrap we can use unsigned divide to 8835 // compute the backedge count. In this case, the step may not divide the 8836 // distance, but we don't care because if the condition is "missed" the loop 8837 // will have undefined behavior due to wrapping. 8838 if (ControlsExit && AddRec->hasNoSelfWrap() && 8839 loopHasNoAbnormalExits(AddRec->getLoop())) { 8840 const SCEV *Exact = 8841 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8842 const SCEV *Max = 8843 Exact == getCouldNotCompute() 8844 ? Exact 8845 : getConstant(getUnsignedRangeMax(Exact)); 8846 return ExitLimit(Exact, Max, false, Predicates); 8847 } 8848 8849 // Solve the general equation. 8850 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8851 getNegativeSCEV(Start), *this); 8852 const SCEV *M = E == getCouldNotCompute() 8853 ? E 8854 : getConstant(getUnsignedRangeMax(E)); 8855 return ExitLimit(E, M, false, Predicates); 8856 } 8857 8858 ScalarEvolution::ExitLimit 8859 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8860 // Loops that look like: while (X == 0) are very strange indeed. We don't 8861 // handle them yet except for the trivial case. This could be expanded in the 8862 // future as needed. 8863 8864 // If the value is a constant, check to see if it is known to be non-zero 8865 // already. If so, the backedge will execute zero times. 8866 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8867 if (!C->getValue()->isZero()) 8868 return getZero(C->getType()); 8869 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8870 } 8871 8872 // We could implement others, but I really doubt anyone writes loops like 8873 // this, and if they did, they would already be constant folded. 8874 return getCouldNotCompute(); 8875 } 8876 8877 std::pair<BasicBlock *, BasicBlock *> 8878 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8879 // If the block has a unique predecessor, then there is no path from the 8880 // predecessor to the block that does not go through the direct edge 8881 // from the predecessor to the block. 8882 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8883 return {Pred, BB}; 8884 8885 // A loop's header is defined to be a block that dominates the loop. 8886 // If the header has a unique predecessor outside the loop, it must be 8887 // a block that has exactly one successor that can reach the loop. 8888 if (Loop *L = LI.getLoopFor(BB)) 8889 return {L->getLoopPredecessor(), L->getHeader()}; 8890 8891 return {nullptr, nullptr}; 8892 } 8893 8894 /// SCEV structural equivalence is usually sufficient for testing whether two 8895 /// expressions are equal, however for the purposes of looking for a condition 8896 /// guarding a loop, it can be useful to be a little more general, since a 8897 /// front-end may have replicated the controlling expression. 8898 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8899 // Quick check to see if they are the same SCEV. 8900 if (A == B) return true; 8901 8902 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8903 // Not all instructions that are "identical" compute the same value. For 8904 // instance, two distinct alloca instructions allocating the same type are 8905 // identical and do not read memory; but compute distinct values. 8906 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8907 }; 8908 8909 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8910 // two different instructions with the same value. Check for this case. 8911 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8912 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8913 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8914 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8915 if (ComputesEqualValues(AI, BI)) 8916 return true; 8917 8918 // Otherwise assume they may have a different value. 8919 return false; 8920 } 8921 8922 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8923 const SCEV *&LHS, const SCEV *&RHS, 8924 unsigned Depth) { 8925 bool Changed = false; 8926 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 8927 // '0 != 0'. 8928 auto TrivialCase = [&](bool TriviallyTrue) { 8929 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 8930 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 8931 return true; 8932 }; 8933 // If we hit the max recursion limit bail out. 8934 if (Depth >= 3) 8935 return false; 8936 8937 // Canonicalize a constant to the right side. 8938 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 8939 // Check for both operands constant. 8940 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 8941 if (ConstantExpr::getICmp(Pred, 8942 LHSC->getValue(), 8943 RHSC->getValue())->isNullValue()) 8944 return TrivialCase(false); 8945 else 8946 return TrivialCase(true); 8947 } 8948 // Otherwise swap the operands to put the constant on the right. 8949 std::swap(LHS, RHS); 8950 Pred = ICmpInst::getSwappedPredicate(Pred); 8951 Changed = true; 8952 } 8953 8954 // If we're comparing an addrec with a value which is loop-invariant in the 8955 // addrec's loop, put the addrec on the left. Also make a dominance check, 8956 // as both operands could be addrecs loop-invariant in each other's loop. 8957 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 8958 const Loop *L = AR->getLoop(); 8959 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 8960 std::swap(LHS, RHS); 8961 Pred = ICmpInst::getSwappedPredicate(Pred); 8962 Changed = true; 8963 } 8964 } 8965 8966 // If there's a constant operand, canonicalize comparisons with boundary 8967 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 8968 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 8969 const APInt &RA = RC->getAPInt(); 8970 8971 bool SimplifiedByConstantRange = false; 8972 8973 if (!ICmpInst::isEquality(Pred)) { 8974 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 8975 if (ExactCR.isFullSet()) 8976 return TrivialCase(true); 8977 else if (ExactCR.isEmptySet()) 8978 return TrivialCase(false); 8979 8980 APInt NewRHS; 8981 CmpInst::Predicate NewPred; 8982 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 8983 ICmpInst::isEquality(NewPred)) { 8984 // We were able to convert an inequality to an equality. 8985 Pred = NewPred; 8986 RHS = getConstant(NewRHS); 8987 Changed = SimplifiedByConstantRange = true; 8988 } 8989 } 8990 8991 if (!SimplifiedByConstantRange) { 8992 switch (Pred) { 8993 default: 8994 break; 8995 case ICmpInst::ICMP_EQ: 8996 case ICmpInst::ICMP_NE: 8997 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 8998 if (!RA) 8999 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9000 if (const SCEVMulExpr *ME = 9001 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9002 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9003 ME->getOperand(0)->isAllOnesValue()) { 9004 RHS = AE->getOperand(1); 9005 LHS = ME->getOperand(1); 9006 Changed = true; 9007 } 9008 break; 9009 9010 9011 // The "Should have been caught earlier!" messages refer to the fact 9012 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9013 // should have fired on the corresponding cases, and canonicalized the 9014 // check to trivial case. 9015 9016 case ICmpInst::ICMP_UGE: 9017 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9018 Pred = ICmpInst::ICMP_UGT; 9019 RHS = getConstant(RA - 1); 9020 Changed = true; 9021 break; 9022 case ICmpInst::ICMP_ULE: 9023 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9024 Pred = ICmpInst::ICMP_ULT; 9025 RHS = getConstant(RA + 1); 9026 Changed = true; 9027 break; 9028 case ICmpInst::ICMP_SGE: 9029 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9030 Pred = ICmpInst::ICMP_SGT; 9031 RHS = getConstant(RA - 1); 9032 Changed = true; 9033 break; 9034 case ICmpInst::ICMP_SLE: 9035 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9036 Pred = ICmpInst::ICMP_SLT; 9037 RHS = getConstant(RA + 1); 9038 Changed = true; 9039 break; 9040 } 9041 } 9042 } 9043 9044 // Check for obvious equality. 9045 if (HasSameValue(LHS, RHS)) { 9046 if (ICmpInst::isTrueWhenEqual(Pred)) 9047 return TrivialCase(true); 9048 if (ICmpInst::isFalseWhenEqual(Pred)) 9049 return TrivialCase(false); 9050 } 9051 9052 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9053 // adding or subtracting 1 from one of the operands. 9054 switch (Pred) { 9055 case ICmpInst::ICMP_SLE: 9056 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9057 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9058 SCEV::FlagNSW); 9059 Pred = ICmpInst::ICMP_SLT; 9060 Changed = true; 9061 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9062 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9063 SCEV::FlagNSW); 9064 Pred = ICmpInst::ICMP_SLT; 9065 Changed = true; 9066 } 9067 break; 9068 case ICmpInst::ICMP_SGE: 9069 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9070 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9071 SCEV::FlagNSW); 9072 Pred = ICmpInst::ICMP_SGT; 9073 Changed = true; 9074 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9075 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9076 SCEV::FlagNSW); 9077 Pred = ICmpInst::ICMP_SGT; 9078 Changed = true; 9079 } 9080 break; 9081 case ICmpInst::ICMP_ULE: 9082 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9083 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9084 SCEV::FlagNUW); 9085 Pred = ICmpInst::ICMP_ULT; 9086 Changed = true; 9087 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9088 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9089 Pred = ICmpInst::ICMP_ULT; 9090 Changed = true; 9091 } 9092 break; 9093 case ICmpInst::ICMP_UGE: 9094 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9095 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9096 Pred = ICmpInst::ICMP_UGT; 9097 Changed = true; 9098 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9099 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9100 SCEV::FlagNUW); 9101 Pred = ICmpInst::ICMP_UGT; 9102 Changed = true; 9103 } 9104 break; 9105 default: 9106 break; 9107 } 9108 9109 // TODO: More simplifications are possible here. 9110 9111 // Recursively simplify until we either hit a recursion limit or nothing 9112 // changes. 9113 if (Changed) 9114 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9115 9116 return Changed; 9117 } 9118 9119 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9120 return getSignedRangeMax(S).isNegative(); 9121 } 9122 9123 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9124 return getSignedRangeMin(S).isStrictlyPositive(); 9125 } 9126 9127 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9128 return !getSignedRangeMin(S).isNegative(); 9129 } 9130 9131 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9132 return !getSignedRangeMax(S).isStrictlyPositive(); 9133 } 9134 9135 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9136 return isKnownNegative(S) || isKnownPositive(S); 9137 } 9138 9139 std::pair<const SCEV *, const SCEV *> 9140 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9141 // Compute SCEV on entry of loop L. 9142 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9143 if (Start == getCouldNotCompute()) 9144 return { Start, Start }; 9145 // Compute post increment SCEV for loop L. 9146 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9147 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9148 return { Start, PostInc }; 9149 } 9150 9151 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9152 const SCEV *LHS, const SCEV *RHS) { 9153 // First collect all loops. 9154 SmallPtrSet<const Loop *, 8> LoopsUsed; 9155 getUsedLoops(LHS, LoopsUsed); 9156 getUsedLoops(RHS, LoopsUsed); 9157 9158 if (LoopsUsed.empty()) 9159 return false; 9160 9161 // Domination relationship must be a linear order on collected loops. 9162 #ifndef NDEBUG 9163 for (auto *L1 : LoopsUsed) 9164 for (auto *L2 : LoopsUsed) 9165 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9166 DT.dominates(L2->getHeader(), L1->getHeader())) && 9167 "Domination relationship is not a linear order"); 9168 #endif 9169 9170 const Loop *MDL = 9171 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9172 [&](const Loop *L1, const Loop *L2) { 9173 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9174 }); 9175 9176 // Get init and post increment value for LHS. 9177 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9178 // if LHS contains unknown non-invariant SCEV then bail out. 9179 if (SplitLHS.first == getCouldNotCompute()) 9180 return false; 9181 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9182 // Get init and post increment value for RHS. 9183 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9184 // if RHS contains unknown non-invariant SCEV then bail out. 9185 if (SplitRHS.first == getCouldNotCompute()) 9186 return false; 9187 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9188 // It is possible that init SCEV contains an invariant load but it does 9189 // not dominate MDL and is not available at MDL loop entry, so we should 9190 // check it here. 9191 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9192 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9193 return false; 9194 9195 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) && 9196 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9197 SplitRHS.second); 9198 } 9199 9200 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9201 const SCEV *LHS, const SCEV *RHS) { 9202 // Canonicalize the inputs first. 9203 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9204 9205 if (isKnownViaInduction(Pred, LHS, RHS)) 9206 return true; 9207 9208 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9209 return true; 9210 9211 // Otherwise see what can be done with some simple reasoning. 9212 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9213 } 9214 9215 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9216 const SCEVAddRecExpr *LHS, 9217 const SCEV *RHS) { 9218 const Loop *L = LHS->getLoop(); 9219 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9220 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9221 } 9222 9223 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9224 ICmpInst::Predicate Pred, 9225 bool &Increasing) { 9226 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9227 9228 #ifndef NDEBUG 9229 // Verify an invariant: inverting the predicate should turn a monotonically 9230 // increasing change to a monotonically decreasing one, and vice versa. 9231 bool IncreasingSwapped; 9232 bool ResultSwapped = isMonotonicPredicateImpl( 9233 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9234 9235 assert(Result == ResultSwapped && "should be able to analyze both!"); 9236 if (ResultSwapped) 9237 assert(Increasing == !IncreasingSwapped && 9238 "monotonicity should flip as we flip the predicate"); 9239 #endif 9240 9241 return Result; 9242 } 9243 9244 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9245 ICmpInst::Predicate Pred, 9246 bool &Increasing) { 9247 9248 // A zero step value for LHS means the induction variable is essentially a 9249 // loop invariant value. We don't really depend on the predicate actually 9250 // flipping from false to true (for increasing predicates, and the other way 9251 // around for decreasing predicates), all we care about is that *if* the 9252 // predicate changes then it only changes from false to true. 9253 // 9254 // A zero step value in itself is not very useful, but there may be places 9255 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9256 // as general as possible. 9257 9258 switch (Pred) { 9259 default: 9260 return false; // Conservative answer 9261 9262 case ICmpInst::ICMP_UGT: 9263 case ICmpInst::ICMP_UGE: 9264 case ICmpInst::ICMP_ULT: 9265 case ICmpInst::ICMP_ULE: 9266 if (!LHS->hasNoUnsignedWrap()) 9267 return false; 9268 9269 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9270 return true; 9271 9272 case ICmpInst::ICMP_SGT: 9273 case ICmpInst::ICMP_SGE: 9274 case ICmpInst::ICMP_SLT: 9275 case ICmpInst::ICMP_SLE: { 9276 if (!LHS->hasNoSignedWrap()) 9277 return false; 9278 9279 const SCEV *Step = LHS->getStepRecurrence(*this); 9280 9281 if (isKnownNonNegative(Step)) { 9282 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9283 return true; 9284 } 9285 9286 if (isKnownNonPositive(Step)) { 9287 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9288 return true; 9289 } 9290 9291 return false; 9292 } 9293 9294 } 9295 9296 llvm_unreachable("switch has default clause!"); 9297 } 9298 9299 bool ScalarEvolution::isLoopInvariantPredicate( 9300 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9301 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9302 const SCEV *&InvariantRHS) { 9303 9304 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9305 if (!isLoopInvariant(RHS, L)) { 9306 if (!isLoopInvariant(LHS, L)) 9307 return false; 9308 9309 std::swap(LHS, RHS); 9310 Pred = ICmpInst::getSwappedPredicate(Pred); 9311 } 9312 9313 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9314 if (!ArLHS || ArLHS->getLoop() != L) 9315 return false; 9316 9317 bool Increasing; 9318 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9319 return false; 9320 9321 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9322 // true as the loop iterates, and the backedge is control dependent on 9323 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9324 // 9325 // * if the predicate was false in the first iteration then the predicate 9326 // is never evaluated again, since the loop exits without taking the 9327 // backedge. 9328 // * if the predicate was true in the first iteration then it will 9329 // continue to be true for all future iterations since it is 9330 // monotonically increasing. 9331 // 9332 // For both the above possibilities, we can replace the loop varying 9333 // predicate with its value on the first iteration of the loop (which is 9334 // loop invariant). 9335 // 9336 // A similar reasoning applies for a monotonically decreasing predicate, by 9337 // replacing true with false and false with true in the above two bullets. 9338 9339 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9340 9341 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9342 return false; 9343 9344 InvariantPred = Pred; 9345 InvariantLHS = ArLHS->getStart(); 9346 InvariantRHS = RHS; 9347 return true; 9348 } 9349 9350 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9351 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9352 if (HasSameValue(LHS, RHS)) 9353 return ICmpInst::isTrueWhenEqual(Pred); 9354 9355 // This code is split out from isKnownPredicate because it is called from 9356 // within isLoopEntryGuardedByCond. 9357 9358 auto CheckRanges = 9359 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9360 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9361 .contains(RangeLHS); 9362 }; 9363 9364 // The check at the top of the function catches the case where the values are 9365 // known to be equal. 9366 if (Pred == CmpInst::ICMP_EQ) 9367 return false; 9368 9369 if (Pred == CmpInst::ICMP_NE) 9370 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9371 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9372 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9373 9374 if (CmpInst::isSigned(Pred)) 9375 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9376 9377 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9378 } 9379 9380 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9381 const SCEV *LHS, 9382 const SCEV *RHS) { 9383 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9384 // Return Y via OutY. 9385 auto MatchBinaryAddToConst = 9386 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9387 SCEV::NoWrapFlags ExpectedFlags) { 9388 const SCEV *NonConstOp, *ConstOp; 9389 SCEV::NoWrapFlags FlagsPresent; 9390 9391 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9392 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9393 return false; 9394 9395 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9396 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9397 }; 9398 9399 APInt C; 9400 9401 switch (Pred) { 9402 default: 9403 break; 9404 9405 case ICmpInst::ICMP_SGE: 9406 std::swap(LHS, RHS); 9407 LLVM_FALLTHROUGH; 9408 case ICmpInst::ICMP_SLE: 9409 // X s<= (X + C)<nsw> if C >= 0 9410 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9411 return true; 9412 9413 // (X + C)<nsw> s<= X if C <= 0 9414 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9415 !C.isStrictlyPositive()) 9416 return true; 9417 break; 9418 9419 case ICmpInst::ICMP_SGT: 9420 std::swap(LHS, RHS); 9421 LLVM_FALLTHROUGH; 9422 case ICmpInst::ICMP_SLT: 9423 // X s< (X + C)<nsw> if C > 0 9424 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9425 C.isStrictlyPositive()) 9426 return true; 9427 9428 // (X + C)<nsw> s< X if C < 0 9429 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9430 return true; 9431 break; 9432 } 9433 9434 return false; 9435 } 9436 9437 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9438 const SCEV *LHS, 9439 const SCEV *RHS) { 9440 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9441 return false; 9442 9443 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9444 // the stack can result in exponential time complexity. 9445 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9446 9447 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9448 // 9449 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9450 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9451 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9452 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9453 // use isKnownPredicate later if needed. 9454 return isKnownNonNegative(RHS) && 9455 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9456 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9457 } 9458 9459 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9460 ICmpInst::Predicate Pred, 9461 const SCEV *LHS, const SCEV *RHS) { 9462 // No need to even try if we know the module has no guards. 9463 if (!HasGuards) 9464 return false; 9465 9466 return any_of(*BB, [&](Instruction &I) { 9467 using namespace llvm::PatternMatch; 9468 9469 Value *Condition; 9470 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9471 m_Value(Condition))) && 9472 isImpliedCond(Pred, LHS, RHS, Condition, false); 9473 }); 9474 } 9475 9476 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9477 /// protected by a conditional between LHS and RHS. This is used to 9478 /// to eliminate casts. 9479 bool 9480 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9481 ICmpInst::Predicate Pred, 9482 const SCEV *LHS, const SCEV *RHS) { 9483 // Interpret a null as meaning no loop, where there is obviously no guard 9484 // (interprocedural conditions notwithstanding). 9485 if (!L) return true; 9486 9487 if (VerifyIR) 9488 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9489 "This cannot be done on broken IR!"); 9490 9491 9492 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9493 return true; 9494 9495 BasicBlock *Latch = L->getLoopLatch(); 9496 if (!Latch) 9497 return false; 9498 9499 BranchInst *LoopContinuePredicate = 9500 dyn_cast<BranchInst>(Latch->getTerminator()); 9501 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9502 isImpliedCond(Pred, LHS, RHS, 9503 LoopContinuePredicate->getCondition(), 9504 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9505 return true; 9506 9507 // We don't want more than one activation of the following loops on the stack 9508 // -- that can lead to O(n!) time complexity. 9509 if (WalkingBEDominatingConds) 9510 return false; 9511 9512 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9513 9514 // See if we can exploit a trip count to prove the predicate. 9515 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9516 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9517 if (LatchBECount != getCouldNotCompute()) { 9518 // We know that Latch branches back to the loop header exactly 9519 // LatchBECount times. This means the backdege condition at Latch is 9520 // equivalent to "{0,+,1} u< LatchBECount". 9521 Type *Ty = LatchBECount->getType(); 9522 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9523 const SCEV *LoopCounter = 9524 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9525 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9526 LatchBECount)) 9527 return true; 9528 } 9529 9530 // Check conditions due to any @llvm.assume intrinsics. 9531 for (auto &AssumeVH : AC.assumptions()) { 9532 if (!AssumeVH) 9533 continue; 9534 auto *CI = cast<CallInst>(AssumeVH); 9535 if (!DT.dominates(CI, Latch->getTerminator())) 9536 continue; 9537 9538 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9539 return true; 9540 } 9541 9542 // If the loop is not reachable from the entry block, we risk running into an 9543 // infinite loop as we walk up into the dom tree. These loops do not matter 9544 // anyway, so we just return a conservative answer when we see them. 9545 if (!DT.isReachableFromEntry(L->getHeader())) 9546 return false; 9547 9548 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9549 return true; 9550 9551 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9552 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9553 assert(DTN && "should reach the loop header before reaching the root!"); 9554 9555 BasicBlock *BB = DTN->getBlock(); 9556 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9557 return true; 9558 9559 BasicBlock *PBB = BB->getSinglePredecessor(); 9560 if (!PBB) 9561 continue; 9562 9563 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9564 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9565 continue; 9566 9567 Value *Condition = ContinuePredicate->getCondition(); 9568 9569 // If we have an edge `E` within the loop body that dominates the only 9570 // latch, the condition guarding `E` also guards the backedge. This 9571 // reasoning works only for loops with a single latch. 9572 9573 BasicBlockEdge DominatingEdge(PBB, BB); 9574 if (DominatingEdge.isSingleEdge()) { 9575 // We're constructively (and conservatively) enumerating edges within the 9576 // loop body that dominate the latch. The dominator tree better agree 9577 // with us on this: 9578 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9579 9580 if (isImpliedCond(Pred, LHS, RHS, Condition, 9581 BB != ContinuePredicate->getSuccessor(0))) 9582 return true; 9583 } 9584 } 9585 9586 return false; 9587 } 9588 9589 bool 9590 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9591 ICmpInst::Predicate Pred, 9592 const SCEV *LHS, const SCEV *RHS) { 9593 // Interpret a null as meaning no loop, where there is obviously no guard 9594 // (interprocedural conditions notwithstanding). 9595 if (!L) return false; 9596 9597 if (VerifyIR) 9598 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9599 "This cannot be done on broken IR!"); 9600 9601 // Both LHS and RHS must be available at loop entry. 9602 assert(isAvailableAtLoopEntry(LHS, L) && 9603 "LHS is not available at Loop Entry"); 9604 assert(isAvailableAtLoopEntry(RHS, L) && 9605 "RHS is not available at Loop Entry"); 9606 9607 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9608 return true; 9609 9610 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9611 // the facts (a >= b && a != b) separately. A typical situation is when the 9612 // non-strict comparison is known from ranges and non-equality is known from 9613 // dominating predicates. If we are proving strict comparison, we always try 9614 // to prove non-equality and non-strict comparison separately. 9615 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9616 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9617 bool ProvedNonStrictComparison = false; 9618 bool ProvedNonEquality = false; 9619 9620 if (ProvingStrictComparison) { 9621 ProvedNonStrictComparison = 9622 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9623 ProvedNonEquality = 9624 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9625 if (ProvedNonStrictComparison && ProvedNonEquality) 9626 return true; 9627 } 9628 9629 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9630 auto ProveViaGuard = [&](BasicBlock *Block) { 9631 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9632 return true; 9633 if (ProvingStrictComparison) { 9634 if (!ProvedNonStrictComparison) 9635 ProvedNonStrictComparison = 9636 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9637 if (!ProvedNonEquality) 9638 ProvedNonEquality = 9639 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9640 if (ProvedNonStrictComparison && ProvedNonEquality) 9641 return true; 9642 } 9643 return false; 9644 }; 9645 9646 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9647 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9648 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9649 return true; 9650 if (ProvingStrictComparison) { 9651 if (!ProvedNonStrictComparison) 9652 ProvedNonStrictComparison = 9653 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9654 if (!ProvedNonEquality) 9655 ProvedNonEquality = 9656 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9657 if (ProvedNonStrictComparison && ProvedNonEquality) 9658 return true; 9659 } 9660 return false; 9661 }; 9662 9663 // Starting at the loop predecessor, climb up the predecessor chain, as long 9664 // as there are predecessors that can be found that have unique successors 9665 // leading to the original header. 9666 for (std::pair<BasicBlock *, BasicBlock *> 9667 Pair(L->getLoopPredecessor(), L->getHeader()); 9668 Pair.first; 9669 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9670 9671 if (ProveViaGuard(Pair.first)) 9672 return true; 9673 9674 BranchInst *LoopEntryPredicate = 9675 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9676 if (!LoopEntryPredicate || 9677 LoopEntryPredicate->isUnconditional()) 9678 continue; 9679 9680 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9681 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9682 return true; 9683 } 9684 9685 // Check conditions due to any @llvm.assume intrinsics. 9686 for (auto &AssumeVH : AC.assumptions()) { 9687 if (!AssumeVH) 9688 continue; 9689 auto *CI = cast<CallInst>(AssumeVH); 9690 if (!DT.dominates(CI, L->getHeader())) 9691 continue; 9692 9693 if (ProveViaCond(CI->getArgOperand(0), false)) 9694 return true; 9695 } 9696 9697 return false; 9698 } 9699 9700 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9701 const SCEV *LHS, const SCEV *RHS, 9702 Value *FoundCondValue, 9703 bool Inverse) { 9704 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9705 return false; 9706 9707 auto ClearOnExit = 9708 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9709 9710 // Recursively handle And and Or conditions. 9711 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9712 if (BO->getOpcode() == Instruction::And) { 9713 if (!Inverse) 9714 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9715 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9716 } else if (BO->getOpcode() == Instruction::Or) { 9717 if (Inverse) 9718 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9719 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9720 } 9721 } 9722 9723 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9724 if (!ICI) return false; 9725 9726 // Now that we found a conditional branch that dominates the loop or controls 9727 // the loop latch. Check to see if it is the comparison we are looking for. 9728 ICmpInst::Predicate FoundPred; 9729 if (Inverse) 9730 FoundPred = ICI->getInversePredicate(); 9731 else 9732 FoundPred = ICI->getPredicate(); 9733 9734 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9735 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9736 9737 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9738 } 9739 9740 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9741 const SCEV *RHS, 9742 ICmpInst::Predicate FoundPred, 9743 const SCEV *FoundLHS, 9744 const SCEV *FoundRHS) { 9745 // Balance the types. 9746 if (getTypeSizeInBits(LHS->getType()) < 9747 getTypeSizeInBits(FoundLHS->getType())) { 9748 if (CmpInst::isSigned(Pred)) { 9749 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9750 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9751 } else { 9752 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9753 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9754 } 9755 } else if (getTypeSizeInBits(LHS->getType()) > 9756 getTypeSizeInBits(FoundLHS->getType())) { 9757 if (CmpInst::isSigned(FoundPred)) { 9758 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9759 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9760 } else { 9761 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9762 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9763 } 9764 } 9765 9766 // Canonicalize the query to match the way instcombine will have 9767 // canonicalized the comparison. 9768 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9769 if (LHS == RHS) 9770 return CmpInst::isTrueWhenEqual(Pred); 9771 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9772 if (FoundLHS == FoundRHS) 9773 return CmpInst::isFalseWhenEqual(FoundPred); 9774 9775 // Check to see if we can make the LHS or RHS match. 9776 if (LHS == FoundRHS || RHS == FoundLHS) { 9777 if (isa<SCEVConstant>(RHS)) { 9778 std::swap(FoundLHS, FoundRHS); 9779 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9780 } else { 9781 std::swap(LHS, RHS); 9782 Pred = ICmpInst::getSwappedPredicate(Pred); 9783 } 9784 } 9785 9786 // Check whether the found predicate is the same as the desired predicate. 9787 if (FoundPred == Pred) 9788 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9789 9790 // Check whether swapping the found predicate makes it the same as the 9791 // desired predicate. 9792 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9793 if (isa<SCEVConstant>(RHS)) 9794 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9795 else 9796 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9797 RHS, LHS, FoundLHS, FoundRHS); 9798 } 9799 9800 // Unsigned comparison is the same as signed comparison when both the operands 9801 // are non-negative. 9802 if (CmpInst::isUnsigned(FoundPred) && 9803 CmpInst::getSignedPredicate(FoundPred) == Pred && 9804 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9805 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9806 9807 // Check if we can make progress by sharpening ranges. 9808 if (FoundPred == ICmpInst::ICMP_NE && 9809 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9810 9811 const SCEVConstant *C = nullptr; 9812 const SCEV *V = nullptr; 9813 9814 if (isa<SCEVConstant>(FoundLHS)) { 9815 C = cast<SCEVConstant>(FoundLHS); 9816 V = FoundRHS; 9817 } else { 9818 C = cast<SCEVConstant>(FoundRHS); 9819 V = FoundLHS; 9820 } 9821 9822 // The guarding predicate tells us that C != V. If the known range 9823 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9824 // range we consider has to correspond to same signedness as the 9825 // predicate we're interested in folding. 9826 9827 APInt Min = ICmpInst::isSigned(Pred) ? 9828 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9829 9830 if (Min == C->getAPInt()) { 9831 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9832 // This is true even if (Min + 1) wraps around -- in case of 9833 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9834 9835 APInt SharperMin = Min + 1; 9836 9837 switch (Pred) { 9838 case ICmpInst::ICMP_SGE: 9839 case ICmpInst::ICMP_UGE: 9840 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9841 // RHS, we're done. 9842 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9843 getConstant(SharperMin))) 9844 return true; 9845 LLVM_FALLTHROUGH; 9846 9847 case ICmpInst::ICMP_SGT: 9848 case ICmpInst::ICMP_UGT: 9849 // We know from the range information that (V `Pred` Min || 9850 // V == Min). We know from the guarding condition that !(V 9851 // == Min). This gives us 9852 // 9853 // V `Pred` Min || V == Min && !(V == Min) 9854 // => V `Pred` Min 9855 // 9856 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9857 9858 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9859 return true; 9860 LLVM_FALLTHROUGH; 9861 9862 default: 9863 // No change 9864 break; 9865 } 9866 } 9867 } 9868 9869 // Check whether the actual condition is beyond sufficient. 9870 if (FoundPred == ICmpInst::ICMP_EQ) 9871 if (ICmpInst::isTrueWhenEqual(Pred)) 9872 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9873 return true; 9874 if (Pred == ICmpInst::ICMP_NE) 9875 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9876 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9877 return true; 9878 9879 // Otherwise assume the worst. 9880 return false; 9881 } 9882 9883 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9884 const SCEV *&L, const SCEV *&R, 9885 SCEV::NoWrapFlags &Flags) { 9886 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9887 if (!AE || AE->getNumOperands() != 2) 9888 return false; 9889 9890 L = AE->getOperand(0); 9891 R = AE->getOperand(1); 9892 Flags = AE->getNoWrapFlags(); 9893 return true; 9894 } 9895 9896 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9897 const SCEV *Less) { 9898 // We avoid subtracting expressions here because this function is usually 9899 // fairly deep in the call stack (i.e. is called many times). 9900 9901 // X - X = 0. 9902 if (More == Less) 9903 return APInt(getTypeSizeInBits(More->getType()), 0); 9904 9905 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9906 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9907 const auto *MAR = cast<SCEVAddRecExpr>(More); 9908 9909 if (LAR->getLoop() != MAR->getLoop()) 9910 return None; 9911 9912 // We look at affine expressions only; not for correctness but to keep 9913 // getStepRecurrence cheap. 9914 if (!LAR->isAffine() || !MAR->isAffine()) 9915 return None; 9916 9917 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9918 return None; 9919 9920 Less = LAR->getStart(); 9921 More = MAR->getStart(); 9922 9923 // fall through 9924 } 9925 9926 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 9927 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 9928 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 9929 return M - L; 9930 } 9931 9932 SCEV::NoWrapFlags Flags; 9933 const SCEV *LLess = nullptr, *RLess = nullptr; 9934 const SCEV *LMore = nullptr, *RMore = nullptr; 9935 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 9936 // Compare (X + C1) vs X. 9937 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 9938 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 9939 if (RLess == More) 9940 return -(C1->getAPInt()); 9941 9942 // Compare X vs (X + C2). 9943 if (splitBinaryAdd(More, LMore, RMore, Flags)) 9944 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 9945 if (RMore == Less) 9946 return C2->getAPInt(); 9947 9948 // Compare (X + C1) vs (X + C2). 9949 if (C1 && C2 && RLess == RMore) 9950 return C2->getAPInt() - C1->getAPInt(); 9951 9952 return None; 9953 } 9954 9955 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 9956 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 9957 const SCEV *FoundLHS, const SCEV *FoundRHS) { 9958 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 9959 return false; 9960 9961 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9962 if (!AddRecLHS) 9963 return false; 9964 9965 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 9966 if (!AddRecFoundLHS) 9967 return false; 9968 9969 // We'd like to let SCEV reason about control dependencies, so we constrain 9970 // both the inequalities to be about add recurrences on the same loop. This 9971 // way we can use isLoopEntryGuardedByCond later. 9972 9973 const Loop *L = AddRecFoundLHS->getLoop(); 9974 if (L != AddRecLHS->getLoop()) 9975 return false; 9976 9977 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 9978 // 9979 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 9980 // ... (2) 9981 // 9982 // Informal proof for (2), assuming (1) [*]: 9983 // 9984 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 9985 // 9986 // Then 9987 // 9988 // FoundLHS s< FoundRHS s< INT_MIN - C 9989 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 9990 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 9991 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 9992 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 9993 // <=> FoundLHS + C s< FoundRHS + C 9994 // 9995 // [*]: (1) can be proved by ruling out overflow. 9996 // 9997 // [**]: This can be proved by analyzing all the four possibilities: 9998 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 9999 // (A s>= 0, B s>= 0). 10000 // 10001 // Note: 10002 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10003 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10004 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10005 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10006 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10007 // C)". 10008 10009 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10010 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10011 if (!LDiff || !RDiff || *LDiff != *RDiff) 10012 return false; 10013 10014 if (LDiff->isMinValue()) 10015 return true; 10016 10017 APInt FoundRHSLimit; 10018 10019 if (Pred == CmpInst::ICMP_ULT) { 10020 FoundRHSLimit = -(*RDiff); 10021 } else { 10022 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10023 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10024 } 10025 10026 // Try to prove (1) or (2), as needed. 10027 return isAvailableAtLoopEntry(FoundRHS, L) && 10028 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10029 getConstant(FoundRHSLimit)); 10030 } 10031 10032 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10033 const SCEV *LHS, const SCEV *RHS, 10034 const SCEV *FoundLHS, 10035 const SCEV *FoundRHS, unsigned Depth) { 10036 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10037 10038 auto ClearOnExit = make_scope_exit([&]() { 10039 if (LPhi) { 10040 bool Erased = PendingMerges.erase(LPhi); 10041 assert(Erased && "Failed to erase LPhi!"); 10042 (void)Erased; 10043 } 10044 if (RPhi) { 10045 bool Erased = PendingMerges.erase(RPhi); 10046 assert(Erased && "Failed to erase RPhi!"); 10047 (void)Erased; 10048 } 10049 }); 10050 10051 // Find respective Phis and check that they are not being pending. 10052 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10053 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10054 if (!PendingMerges.insert(Phi).second) 10055 return false; 10056 LPhi = Phi; 10057 } 10058 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10059 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10060 // If we detect a loop of Phi nodes being processed by this method, for 10061 // example: 10062 // 10063 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10064 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10065 // 10066 // we don't want to deal with a case that complex, so return conservative 10067 // answer false. 10068 if (!PendingMerges.insert(Phi).second) 10069 return false; 10070 RPhi = Phi; 10071 } 10072 10073 // If none of LHS, RHS is a Phi, nothing to do here. 10074 if (!LPhi && !RPhi) 10075 return false; 10076 10077 // If there is a SCEVUnknown Phi we are interested in, make it left. 10078 if (!LPhi) { 10079 std::swap(LHS, RHS); 10080 std::swap(FoundLHS, FoundRHS); 10081 std::swap(LPhi, RPhi); 10082 Pred = ICmpInst::getSwappedPredicate(Pred); 10083 } 10084 10085 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10086 const BasicBlock *LBB = LPhi->getParent(); 10087 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10088 10089 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10090 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10091 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10092 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10093 }; 10094 10095 if (RPhi && RPhi->getParent() == LBB) { 10096 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10097 // If we compare two Phis from the same block, and for each entry block 10098 // the predicate is true for incoming values from this block, then the 10099 // predicate is also true for the Phis. 10100 for (const BasicBlock *IncBB : predecessors(LBB)) { 10101 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10102 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10103 if (!ProvedEasily(L, R)) 10104 return false; 10105 } 10106 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10107 // Case two: RHS is also a Phi from the same basic block, and it is an 10108 // AddRec. It means that there is a loop which has both AddRec and Unknown 10109 // PHIs, for it we can compare incoming values of AddRec from above the loop 10110 // and latch with their respective incoming values of LPhi. 10111 // TODO: Generalize to handle loops with many inputs in a header. 10112 if (LPhi->getNumIncomingValues() != 2) return false; 10113 10114 auto *RLoop = RAR->getLoop(); 10115 auto *Predecessor = RLoop->getLoopPredecessor(); 10116 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10117 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10118 if (!ProvedEasily(L1, RAR->getStart())) 10119 return false; 10120 auto *Latch = RLoop->getLoopLatch(); 10121 assert(Latch && "Loop with AddRec with no latch?"); 10122 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10123 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10124 return false; 10125 } else { 10126 // In all other cases go over inputs of LHS and compare each of them to RHS, 10127 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10128 // At this point RHS is either a non-Phi, or it is a Phi from some block 10129 // different from LBB. 10130 for (const BasicBlock *IncBB : predecessors(LBB)) { 10131 // Check that RHS is available in this block. 10132 if (!dominates(RHS, IncBB)) 10133 return false; 10134 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10135 if (!ProvedEasily(L, RHS)) 10136 return false; 10137 } 10138 } 10139 return true; 10140 } 10141 10142 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10143 const SCEV *LHS, const SCEV *RHS, 10144 const SCEV *FoundLHS, 10145 const SCEV *FoundRHS) { 10146 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10147 return true; 10148 10149 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10150 return true; 10151 10152 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10153 FoundLHS, FoundRHS) || 10154 // ~x < ~y --> x > y 10155 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10156 getNotSCEV(FoundRHS), 10157 getNotSCEV(FoundLHS)); 10158 } 10159 10160 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10161 template <typename MinMaxExprType> 10162 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10163 const SCEV *Candidate) { 10164 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10165 if (!MinMaxExpr) 10166 return false; 10167 10168 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10169 } 10170 10171 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10172 ICmpInst::Predicate Pred, 10173 const SCEV *LHS, const SCEV *RHS) { 10174 // If both sides are affine addrecs for the same loop, with equal 10175 // steps, and we know the recurrences don't wrap, then we only 10176 // need to check the predicate on the starting values. 10177 10178 if (!ICmpInst::isRelational(Pred)) 10179 return false; 10180 10181 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10182 if (!LAR) 10183 return false; 10184 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10185 if (!RAR) 10186 return false; 10187 if (LAR->getLoop() != RAR->getLoop()) 10188 return false; 10189 if (!LAR->isAffine() || !RAR->isAffine()) 10190 return false; 10191 10192 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10193 return false; 10194 10195 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10196 SCEV::FlagNSW : SCEV::FlagNUW; 10197 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10198 return false; 10199 10200 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10201 } 10202 10203 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10204 /// expression? 10205 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10206 ICmpInst::Predicate Pred, 10207 const SCEV *LHS, const SCEV *RHS) { 10208 switch (Pred) { 10209 default: 10210 return false; 10211 10212 case ICmpInst::ICMP_SGE: 10213 std::swap(LHS, RHS); 10214 LLVM_FALLTHROUGH; 10215 case ICmpInst::ICMP_SLE: 10216 return 10217 // min(A, ...) <= A 10218 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10219 // A <= max(A, ...) 10220 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10221 10222 case ICmpInst::ICMP_UGE: 10223 std::swap(LHS, RHS); 10224 LLVM_FALLTHROUGH; 10225 case ICmpInst::ICMP_ULE: 10226 return 10227 // min(A, ...) <= A 10228 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10229 // A <= max(A, ...) 10230 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10231 } 10232 10233 llvm_unreachable("covered switch fell through?!"); 10234 } 10235 10236 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10237 const SCEV *LHS, const SCEV *RHS, 10238 const SCEV *FoundLHS, 10239 const SCEV *FoundRHS, 10240 unsigned Depth) { 10241 assert(getTypeSizeInBits(LHS->getType()) == 10242 getTypeSizeInBits(RHS->getType()) && 10243 "LHS and RHS have different sizes?"); 10244 assert(getTypeSizeInBits(FoundLHS->getType()) == 10245 getTypeSizeInBits(FoundRHS->getType()) && 10246 "FoundLHS and FoundRHS have different sizes?"); 10247 // We want to avoid hurting the compile time with analysis of too big trees. 10248 if (Depth > MaxSCEVOperationsImplicationDepth) 10249 return false; 10250 // We only want to work with ICMP_SGT comparison so far. 10251 // TODO: Extend to ICMP_UGT? 10252 if (Pred == ICmpInst::ICMP_SLT) { 10253 Pred = ICmpInst::ICMP_SGT; 10254 std::swap(LHS, RHS); 10255 std::swap(FoundLHS, FoundRHS); 10256 } 10257 if (Pred != ICmpInst::ICMP_SGT) 10258 return false; 10259 10260 auto GetOpFromSExt = [&](const SCEV *S) { 10261 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10262 return Ext->getOperand(); 10263 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10264 // the constant in some cases. 10265 return S; 10266 }; 10267 10268 // Acquire values from extensions. 10269 auto *OrigLHS = LHS; 10270 auto *OrigFoundLHS = FoundLHS; 10271 LHS = GetOpFromSExt(LHS); 10272 FoundLHS = GetOpFromSExt(FoundLHS); 10273 10274 // Is the SGT predicate can be proved trivially or using the found context. 10275 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10276 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10277 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10278 FoundRHS, Depth + 1); 10279 }; 10280 10281 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10282 // We want to avoid creation of any new non-constant SCEV. Since we are 10283 // going to compare the operands to RHS, we should be certain that we don't 10284 // need any size extensions for this. So let's decline all cases when the 10285 // sizes of types of LHS and RHS do not match. 10286 // TODO: Maybe try to get RHS from sext to catch more cases? 10287 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10288 return false; 10289 10290 // Should not overflow. 10291 if (!LHSAddExpr->hasNoSignedWrap()) 10292 return false; 10293 10294 auto *LL = LHSAddExpr->getOperand(0); 10295 auto *LR = LHSAddExpr->getOperand(1); 10296 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10297 10298 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10299 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10300 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10301 }; 10302 // Try to prove the following rule: 10303 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10304 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10305 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10306 return true; 10307 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10308 Value *LL, *LR; 10309 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10310 10311 using namespace llvm::PatternMatch; 10312 10313 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10314 // Rules for division. 10315 // We are going to perform some comparisons with Denominator and its 10316 // derivative expressions. In general case, creating a SCEV for it may 10317 // lead to a complex analysis of the entire graph, and in particular it 10318 // can request trip count recalculation for the same loop. This would 10319 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10320 // this, we only want to create SCEVs that are constants in this section. 10321 // So we bail if Denominator is not a constant. 10322 if (!isa<ConstantInt>(LR)) 10323 return false; 10324 10325 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10326 10327 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10328 // then a SCEV for the numerator already exists and matches with FoundLHS. 10329 auto *Numerator = getExistingSCEV(LL); 10330 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10331 return false; 10332 10333 // Make sure that the numerator matches with FoundLHS and the denominator 10334 // is positive. 10335 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10336 return false; 10337 10338 auto *DTy = Denominator->getType(); 10339 auto *FRHSTy = FoundRHS->getType(); 10340 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10341 // One of types is a pointer and another one is not. We cannot extend 10342 // them properly to a wider type, so let us just reject this case. 10343 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10344 // to avoid this check. 10345 return false; 10346 10347 // Given that: 10348 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10349 auto *WTy = getWiderType(DTy, FRHSTy); 10350 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10351 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10352 10353 // Try to prove the following rule: 10354 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10355 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10356 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10357 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10358 if (isKnownNonPositive(RHS) && 10359 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10360 return true; 10361 10362 // Try to prove the following rule: 10363 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10364 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10365 // If we divide it by Denominator > 2, then: 10366 // 1. If FoundLHS is negative, then the result is 0. 10367 // 2. If FoundLHS is non-negative, then the result is non-negative. 10368 // Anyways, the result is non-negative. 10369 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10370 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10371 if (isKnownNegative(RHS) && 10372 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10373 return true; 10374 } 10375 } 10376 10377 // If our expression contained SCEVUnknown Phis, and we split it down and now 10378 // need to prove something for them, try to prove the predicate for every 10379 // possible incoming values of those Phis. 10380 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10381 return true; 10382 10383 return false; 10384 } 10385 10386 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10387 const SCEV *LHS, const SCEV *RHS) { 10388 // zext x u<= sext x, sext x s<= zext x 10389 switch (Pred) { 10390 case ICmpInst::ICMP_SGE: 10391 std::swap(LHS, RHS); 10392 LLVM_FALLTHROUGH; 10393 case ICmpInst::ICMP_SLE: { 10394 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10395 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10396 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10397 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10398 return true; 10399 break; 10400 } 10401 case ICmpInst::ICMP_UGE: 10402 std::swap(LHS, RHS); 10403 LLVM_FALLTHROUGH; 10404 case ICmpInst::ICMP_ULE: { 10405 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10406 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10407 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10408 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10409 return true; 10410 break; 10411 } 10412 default: 10413 break; 10414 }; 10415 return false; 10416 } 10417 10418 bool 10419 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10420 const SCEV *LHS, const SCEV *RHS) { 10421 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10422 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10423 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10424 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10425 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10426 } 10427 10428 bool 10429 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10430 const SCEV *LHS, const SCEV *RHS, 10431 const SCEV *FoundLHS, 10432 const SCEV *FoundRHS) { 10433 switch (Pred) { 10434 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10435 case ICmpInst::ICMP_EQ: 10436 case ICmpInst::ICMP_NE: 10437 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10438 return true; 10439 break; 10440 case ICmpInst::ICMP_SLT: 10441 case ICmpInst::ICMP_SLE: 10442 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10443 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10444 return true; 10445 break; 10446 case ICmpInst::ICMP_SGT: 10447 case ICmpInst::ICMP_SGE: 10448 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10449 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10450 return true; 10451 break; 10452 case ICmpInst::ICMP_ULT: 10453 case ICmpInst::ICMP_ULE: 10454 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10455 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10456 return true; 10457 break; 10458 case ICmpInst::ICMP_UGT: 10459 case ICmpInst::ICMP_UGE: 10460 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10461 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10462 return true; 10463 break; 10464 } 10465 10466 // Maybe it can be proved via operations? 10467 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10468 return true; 10469 10470 return false; 10471 } 10472 10473 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10474 const SCEV *LHS, 10475 const SCEV *RHS, 10476 const SCEV *FoundLHS, 10477 const SCEV *FoundRHS) { 10478 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10479 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10480 // reduce the compile time impact of this optimization. 10481 return false; 10482 10483 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10484 if (!Addend) 10485 return false; 10486 10487 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10488 10489 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10490 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10491 ConstantRange FoundLHSRange = 10492 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10493 10494 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10495 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10496 10497 // We can also compute the range of values for `LHS` that satisfy the 10498 // consequent, "`LHS` `Pred` `RHS`": 10499 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10500 ConstantRange SatisfyingLHSRange = 10501 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10502 10503 // The antecedent implies the consequent if every value of `LHS` that 10504 // satisfies the antecedent also satisfies the consequent. 10505 return SatisfyingLHSRange.contains(LHSRange); 10506 } 10507 10508 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10509 bool IsSigned, bool NoWrap) { 10510 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10511 10512 if (NoWrap) return false; 10513 10514 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10515 const SCEV *One = getOne(Stride->getType()); 10516 10517 if (IsSigned) { 10518 APInt MaxRHS = getSignedRangeMax(RHS); 10519 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10520 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10521 10522 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10523 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10524 } 10525 10526 APInt MaxRHS = getUnsignedRangeMax(RHS); 10527 APInt MaxValue = APInt::getMaxValue(BitWidth); 10528 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10529 10530 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10531 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10532 } 10533 10534 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10535 bool IsSigned, bool NoWrap) { 10536 if (NoWrap) return false; 10537 10538 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10539 const SCEV *One = getOne(Stride->getType()); 10540 10541 if (IsSigned) { 10542 APInt MinRHS = getSignedRangeMin(RHS); 10543 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10544 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10545 10546 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10547 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10548 } 10549 10550 APInt MinRHS = getUnsignedRangeMin(RHS); 10551 APInt MinValue = APInt::getMinValue(BitWidth); 10552 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10553 10554 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10555 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10556 } 10557 10558 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10559 bool Equality) { 10560 const SCEV *One = getOne(Step->getType()); 10561 Delta = Equality ? getAddExpr(Delta, Step) 10562 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10563 return getUDivExpr(Delta, Step); 10564 } 10565 10566 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10567 const SCEV *Stride, 10568 const SCEV *End, 10569 unsigned BitWidth, 10570 bool IsSigned) { 10571 10572 assert(!isKnownNonPositive(Stride) && 10573 "Stride is expected strictly positive!"); 10574 // Calculate the maximum backedge count based on the range of values 10575 // permitted by Start, End, and Stride. 10576 const SCEV *MaxBECount; 10577 APInt MinStart = 10578 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10579 10580 APInt StrideForMaxBECount = 10581 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10582 10583 // We already know that the stride is positive, so we paper over conservatism 10584 // in our range computation by forcing StrideForMaxBECount to be at least one. 10585 // In theory this is unnecessary, but we expect MaxBECount to be a 10586 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10587 // is nothing to constant fold it to). 10588 APInt One(BitWidth, 1, IsSigned); 10589 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10590 10591 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10592 : APInt::getMaxValue(BitWidth); 10593 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10594 10595 // Although End can be a MAX expression we estimate MaxEnd considering only 10596 // the case End = RHS of the loop termination condition. This is safe because 10597 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10598 // taken count. 10599 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10600 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10601 10602 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10603 getConstant(StrideForMaxBECount) /* Step */, 10604 false /* Equality */); 10605 10606 return MaxBECount; 10607 } 10608 10609 ScalarEvolution::ExitLimit 10610 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10611 const Loop *L, bool IsSigned, 10612 bool ControlsExit, bool AllowPredicates) { 10613 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10614 10615 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10616 bool PredicatedIV = false; 10617 10618 if (!IV && AllowPredicates) { 10619 // Try to make this an AddRec using runtime tests, in the first X 10620 // iterations of this loop, where X is the SCEV expression found by the 10621 // algorithm below. 10622 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10623 PredicatedIV = true; 10624 } 10625 10626 // Avoid weird loops 10627 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10628 return getCouldNotCompute(); 10629 10630 bool NoWrap = ControlsExit && 10631 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10632 10633 const SCEV *Stride = IV->getStepRecurrence(*this); 10634 10635 bool PositiveStride = isKnownPositive(Stride); 10636 10637 // Avoid negative or zero stride values. 10638 if (!PositiveStride) { 10639 // We can compute the correct backedge taken count for loops with unknown 10640 // strides if we can prove that the loop is not an infinite loop with side 10641 // effects. Here's the loop structure we are trying to handle - 10642 // 10643 // i = start 10644 // do { 10645 // A[i] = i; 10646 // i += s; 10647 // } while (i < end); 10648 // 10649 // The backedge taken count for such loops is evaluated as - 10650 // (max(end, start + stride) - start - 1) /u stride 10651 // 10652 // The additional preconditions that we need to check to prove correctness 10653 // of the above formula is as follows - 10654 // 10655 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10656 // NoWrap flag). 10657 // b) loop is single exit with no side effects. 10658 // 10659 // 10660 // Precondition a) implies that if the stride is negative, this is a single 10661 // trip loop. The backedge taken count formula reduces to zero in this case. 10662 // 10663 // Precondition b) implies that the unknown stride cannot be zero otherwise 10664 // we have UB. 10665 // 10666 // The positive stride case is the same as isKnownPositive(Stride) returning 10667 // true (original behavior of the function). 10668 // 10669 // We want to make sure that the stride is truly unknown as there are edge 10670 // cases where ScalarEvolution propagates no wrap flags to the 10671 // post-increment/decrement IV even though the increment/decrement operation 10672 // itself is wrapping. The computed backedge taken count may be wrong in 10673 // such cases. This is prevented by checking that the stride is not known to 10674 // be either positive or non-positive. For example, no wrap flags are 10675 // propagated to the post-increment IV of this loop with a trip count of 2 - 10676 // 10677 // unsigned char i; 10678 // for(i=127; i<128; i+=129) 10679 // A[i] = i; 10680 // 10681 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10682 !loopHasNoSideEffects(L)) 10683 return getCouldNotCompute(); 10684 } else if (!Stride->isOne() && 10685 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10686 // Avoid proven overflow cases: this will ensure that the backedge taken 10687 // count will not generate any unsigned overflow. Relaxed no-overflow 10688 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10689 // undefined behaviors like the case of C language. 10690 return getCouldNotCompute(); 10691 10692 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10693 : ICmpInst::ICMP_ULT; 10694 const SCEV *Start = IV->getStart(); 10695 const SCEV *End = RHS; 10696 // When the RHS is not invariant, we do not know the end bound of the loop and 10697 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10698 // calculate the MaxBECount, given the start, stride and max value for the end 10699 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10700 // checked above). 10701 if (!isLoopInvariant(RHS, L)) { 10702 const SCEV *MaxBECount = computeMaxBECountForLT( 10703 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10704 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10705 false /*MaxOrZero*/, Predicates); 10706 } 10707 // If the backedge is taken at least once, then it will be taken 10708 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10709 // is the LHS value of the less-than comparison the first time it is evaluated 10710 // and End is the RHS. 10711 const SCEV *BECountIfBackedgeTaken = 10712 computeBECount(getMinusSCEV(End, Start), Stride, false); 10713 // If the loop entry is guarded by the result of the backedge test of the 10714 // first loop iteration, then we know the backedge will be taken at least 10715 // once and so the backedge taken count is as above. If not then we use the 10716 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10717 // as if the backedge is taken at least once max(End,Start) is End and so the 10718 // result is as above, and if not max(End,Start) is Start so we get a backedge 10719 // count of zero. 10720 const SCEV *BECount; 10721 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10722 BECount = BECountIfBackedgeTaken; 10723 else { 10724 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10725 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10726 } 10727 10728 const SCEV *MaxBECount; 10729 bool MaxOrZero = false; 10730 if (isa<SCEVConstant>(BECount)) 10731 MaxBECount = BECount; 10732 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10733 // If we know exactly how many times the backedge will be taken if it's 10734 // taken at least once, then the backedge count will either be that or 10735 // zero. 10736 MaxBECount = BECountIfBackedgeTaken; 10737 MaxOrZero = true; 10738 } else { 10739 MaxBECount = computeMaxBECountForLT( 10740 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10741 } 10742 10743 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10744 !isa<SCEVCouldNotCompute>(BECount)) 10745 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10746 10747 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10748 } 10749 10750 ScalarEvolution::ExitLimit 10751 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10752 const Loop *L, bool IsSigned, 10753 bool ControlsExit, bool AllowPredicates) { 10754 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10755 // We handle only IV > Invariant 10756 if (!isLoopInvariant(RHS, L)) 10757 return getCouldNotCompute(); 10758 10759 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10760 if (!IV && AllowPredicates) 10761 // Try to make this an AddRec using runtime tests, in the first X 10762 // iterations of this loop, where X is the SCEV expression found by the 10763 // algorithm below. 10764 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10765 10766 // Avoid weird loops 10767 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10768 return getCouldNotCompute(); 10769 10770 bool NoWrap = ControlsExit && 10771 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10772 10773 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10774 10775 // Avoid negative or zero stride values 10776 if (!isKnownPositive(Stride)) 10777 return getCouldNotCompute(); 10778 10779 // Avoid proven overflow cases: this will ensure that the backedge taken count 10780 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10781 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10782 // behaviors like the case of C language. 10783 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10784 return getCouldNotCompute(); 10785 10786 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10787 : ICmpInst::ICMP_UGT; 10788 10789 const SCEV *Start = IV->getStart(); 10790 const SCEV *End = RHS; 10791 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10792 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10793 10794 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10795 10796 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10797 : getUnsignedRangeMax(Start); 10798 10799 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10800 : getUnsignedRangeMin(Stride); 10801 10802 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10803 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10804 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10805 10806 // Although End can be a MIN expression we estimate MinEnd considering only 10807 // the case End = RHS. This is safe because in the other case (Start - End) 10808 // is zero, leading to a zero maximum backedge taken count. 10809 APInt MinEnd = 10810 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10811 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10812 10813 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10814 ? BECount 10815 : computeBECount(getConstant(MaxStart - MinEnd), 10816 getConstant(MinStride), false); 10817 10818 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10819 MaxBECount = BECount; 10820 10821 return ExitLimit(BECount, MaxBECount, false, Predicates); 10822 } 10823 10824 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10825 ScalarEvolution &SE) const { 10826 if (Range.isFullSet()) // Infinite loop. 10827 return SE.getCouldNotCompute(); 10828 10829 // If the start is a non-zero constant, shift the range to simplify things. 10830 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10831 if (!SC->getValue()->isZero()) { 10832 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10833 Operands[0] = SE.getZero(SC->getType()); 10834 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10835 getNoWrapFlags(FlagNW)); 10836 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10837 return ShiftedAddRec->getNumIterationsInRange( 10838 Range.subtract(SC->getAPInt()), SE); 10839 // This is strange and shouldn't happen. 10840 return SE.getCouldNotCompute(); 10841 } 10842 10843 // The only time we can solve this is when we have all constant indices. 10844 // Otherwise, we cannot determine the overflow conditions. 10845 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10846 return SE.getCouldNotCompute(); 10847 10848 // Okay at this point we know that all elements of the chrec are constants and 10849 // that the start element is zero. 10850 10851 // First check to see if the range contains zero. If not, the first 10852 // iteration exits. 10853 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10854 if (!Range.contains(APInt(BitWidth, 0))) 10855 return SE.getZero(getType()); 10856 10857 if (isAffine()) { 10858 // If this is an affine expression then we have this situation: 10859 // Solve {0,+,A} in Range === Ax in Range 10860 10861 // We know that zero is in the range. If A is positive then we know that 10862 // the upper value of the range must be the first possible exit value. 10863 // If A is negative then the lower of the range is the last possible loop 10864 // value. Also note that we already checked for a full range. 10865 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10866 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10867 10868 // The exit value should be (End+A)/A. 10869 APInt ExitVal = (End + A).udiv(A); 10870 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10871 10872 // Evaluate at the exit value. If we really did fall out of the valid 10873 // range, then we computed our trip count, otherwise wrap around or other 10874 // things must have happened. 10875 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10876 if (Range.contains(Val->getValue())) 10877 return SE.getCouldNotCompute(); // Something strange happened 10878 10879 // Ensure that the previous value is in the range. This is a sanity check. 10880 assert(Range.contains( 10881 EvaluateConstantChrecAtConstant(this, 10882 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10883 "Linear scev computation is off in a bad way!"); 10884 return SE.getConstant(ExitValue); 10885 } 10886 10887 if (isQuadratic()) { 10888 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10889 return SE.getConstant(S.getValue()); 10890 } 10891 10892 return SE.getCouldNotCompute(); 10893 } 10894 10895 const SCEVAddRecExpr * 10896 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10897 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10898 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10899 // but in this case we cannot guarantee that the value returned will be an 10900 // AddRec because SCEV does not have a fixed point where it stops 10901 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10902 // may happen if we reach arithmetic depth limit while simplifying. So we 10903 // construct the returned value explicitly. 10904 SmallVector<const SCEV *, 3> Ops; 10905 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10906 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10907 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10908 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10909 // We know that the last operand is not a constant zero (otherwise it would 10910 // have been popped out earlier). This guarantees us that if the result has 10911 // the same last operand, then it will also not be popped out, meaning that 10912 // the returned value will be an AddRec. 10913 const SCEV *Last = getOperand(getNumOperands() - 1); 10914 assert(!Last->isZero() && "Recurrency with zero step?"); 10915 Ops.push_back(Last); 10916 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10917 SCEV::FlagAnyWrap)); 10918 } 10919 10920 // Return true when S contains at least an undef value. 10921 static inline bool containsUndefs(const SCEV *S) { 10922 return SCEVExprContains(S, [](const SCEV *S) { 10923 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10924 return isa<UndefValue>(SU->getValue()); 10925 return false; 10926 }); 10927 } 10928 10929 namespace { 10930 10931 // Collect all steps of SCEV expressions. 10932 struct SCEVCollectStrides { 10933 ScalarEvolution &SE; 10934 SmallVectorImpl<const SCEV *> &Strides; 10935 10936 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 10937 : SE(SE), Strides(S) {} 10938 10939 bool follow(const SCEV *S) { 10940 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 10941 Strides.push_back(AR->getStepRecurrence(SE)); 10942 return true; 10943 } 10944 10945 bool isDone() const { return false; } 10946 }; 10947 10948 // Collect all SCEVUnknown and SCEVMulExpr expressions. 10949 struct SCEVCollectTerms { 10950 SmallVectorImpl<const SCEV *> &Terms; 10951 10952 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 10953 10954 bool follow(const SCEV *S) { 10955 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 10956 isa<SCEVSignExtendExpr>(S)) { 10957 if (!containsUndefs(S)) 10958 Terms.push_back(S); 10959 10960 // Stop recursion: once we collected a term, do not walk its operands. 10961 return false; 10962 } 10963 10964 // Keep looking. 10965 return true; 10966 } 10967 10968 bool isDone() const { return false; } 10969 }; 10970 10971 // Check if a SCEV contains an AddRecExpr. 10972 struct SCEVHasAddRec { 10973 bool &ContainsAddRec; 10974 10975 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 10976 ContainsAddRec = false; 10977 } 10978 10979 bool follow(const SCEV *S) { 10980 if (isa<SCEVAddRecExpr>(S)) { 10981 ContainsAddRec = true; 10982 10983 // Stop recursion: once we collected a term, do not walk its operands. 10984 return false; 10985 } 10986 10987 // Keep looking. 10988 return true; 10989 } 10990 10991 bool isDone() const { return false; } 10992 }; 10993 10994 // Find factors that are multiplied with an expression that (possibly as a 10995 // subexpression) contains an AddRecExpr. In the expression: 10996 // 10997 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 10998 // 10999 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11000 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11001 // parameters as they form a product with an induction variable. 11002 // 11003 // This collector expects all array size parameters to be in the same MulExpr. 11004 // It might be necessary to later add support for collecting parameters that are 11005 // spread over different nested MulExpr. 11006 struct SCEVCollectAddRecMultiplies { 11007 SmallVectorImpl<const SCEV *> &Terms; 11008 ScalarEvolution &SE; 11009 11010 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11011 : Terms(T), SE(SE) {} 11012 11013 bool follow(const SCEV *S) { 11014 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11015 bool HasAddRec = false; 11016 SmallVector<const SCEV *, 0> Operands; 11017 for (auto Op : Mul->operands()) { 11018 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11019 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11020 Operands.push_back(Op); 11021 } else if (Unknown) { 11022 HasAddRec = true; 11023 } else { 11024 bool ContainsAddRec = false; 11025 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11026 visitAll(Op, ContiansAddRec); 11027 HasAddRec |= ContainsAddRec; 11028 } 11029 } 11030 if (Operands.size() == 0) 11031 return true; 11032 11033 if (!HasAddRec) 11034 return false; 11035 11036 Terms.push_back(SE.getMulExpr(Operands)); 11037 // Stop recursion: once we collected a term, do not walk its operands. 11038 return false; 11039 } 11040 11041 // Keep looking. 11042 return true; 11043 } 11044 11045 bool isDone() const { return false; } 11046 }; 11047 11048 } // end anonymous namespace 11049 11050 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11051 /// two places: 11052 /// 1) The strides of AddRec expressions. 11053 /// 2) Unknowns that are multiplied with AddRec expressions. 11054 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11055 SmallVectorImpl<const SCEV *> &Terms) { 11056 SmallVector<const SCEV *, 4> Strides; 11057 SCEVCollectStrides StrideCollector(*this, Strides); 11058 visitAll(Expr, StrideCollector); 11059 11060 LLVM_DEBUG({ 11061 dbgs() << "Strides:\n"; 11062 for (const SCEV *S : Strides) 11063 dbgs() << *S << "\n"; 11064 }); 11065 11066 for (const SCEV *S : Strides) { 11067 SCEVCollectTerms TermCollector(Terms); 11068 visitAll(S, TermCollector); 11069 } 11070 11071 LLVM_DEBUG({ 11072 dbgs() << "Terms:\n"; 11073 for (const SCEV *T : Terms) 11074 dbgs() << *T << "\n"; 11075 }); 11076 11077 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11078 visitAll(Expr, MulCollector); 11079 } 11080 11081 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11082 SmallVectorImpl<const SCEV *> &Terms, 11083 SmallVectorImpl<const SCEV *> &Sizes) { 11084 int Last = Terms.size() - 1; 11085 const SCEV *Step = Terms[Last]; 11086 11087 // End of recursion. 11088 if (Last == 0) { 11089 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11090 SmallVector<const SCEV *, 2> Qs; 11091 for (const SCEV *Op : M->operands()) 11092 if (!isa<SCEVConstant>(Op)) 11093 Qs.push_back(Op); 11094 11095 Step = SE.getMulExpr(Qs); 11096 } 11097 11098 Sizes.push_back(Step); 11099 return true; 11100 } 11101 11102 for (const SCEV *&Term : Terms) { 11103 // Normalize the terms before the next call to findArrayDimensionsRec. 11104 const SCEV *Q, *R; 11105 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11106 11107 // Bail out when GCD does not evenly divide one of the terms. 11108 if (!R->isZero()) 11109 return false; 11110 11111 Term = Q; 11112 } 11113 11114 // Remove all SCEVConstants. 11115 Terms.erase( 11116 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11117 Terms.end()); 11118 11119 if (Terms.size() > 0) 11120 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11121 return false; 11122 11123 Sizes.push_back(Step); 11124 return true; 11125 } 11126 11127 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11128 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11129 for (const SCEV *T : Terms) 11130 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11131 return true; 11132 return false; 11133 } 11134 11135 // Return the number of product terms in S. 11136 static inline int numberOfTerms(const SCEV *S) { 11137 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11138 return Expr->getNumOperands(); 11139 return 1; 11140 } 11141 11142 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11143 if (isa<SCEVConstant>(T)) 11144 return nullptr; 11145 11146 if (isa<SCEVUnknown>(T)) 11147 return T; 11148 11149 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11150 SmallVector<const SCEV *, 2> Factors; 11151 for (const SCEV *Op : M->operands()) 11152 if (!isa<SCEVConstant>(Op)) 11153 Factors.push_back(Op); 11154 11155 return SE.getMulExpr(Factors); 11156 } 11157 11158 return T; 11159 } 11160 11161 /// Return the size of an element read or written by Inst. 11162 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11163 Type *Ty; 11164 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11165 Ty = Store->getValueOperand()->getType(); 11166 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11167 Ty = Load->getType(); 11168 else 11169 return nullptr; 11170 11171 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11172 return getSizeOfExpr(ETy, Ty); 11173 } 11174 11175 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11176 SmallVectorImpl<const SCEV *> &Sizes, 11177 const SCEV *ElementSize) { 11178 if (Terms.size() < 1 || !ElementSize) 11179 return; 11180 11181 // Early return when Terms do not contain parameters: we do not delinearize 11182 // non parametric SCEVs. 11183 if (!containsParameters(Terms)) 11184 return; 11185 11186 LLVM_DEBUG({ 11187 dbgs() << "Terms:\n"; 11188 for (const SCEV *T : Terms) 11189 dbgs() << *T << "\n"; 11190 }); 11191 11192 // Remove duplicates. 11193 array_pod_sort(Terms.begin(), Terms.end()); 11194 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11195 11196 // Put larger terms first. 11197 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11198 return numberOfTerms(LHS) > numberOfTerms(RHS); 11199 }); 11200 11201 // Try to divide all terms by the element size. If term is not divisible by 11202 // element size, proceed with the original term. 11203 for (const SCEV *&Term : Terms) { 11204 const SCEV *Q, *R; 11205 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11206 if (!Q->isZero()) 11207 Term = Q; 11208 } 11209 11210 SmallVector<const SCEV *, 4> NewTerms; 11211 11212 // Remove constant factors. 11213 for (const SCEV *T : Terms) 11214 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11215 NewTerms.push_back(NewT); 11216 11217 LLVM_DEBUG({ 11218 dbgs() << "Terms after sorting:\n"; 11219 for (const SCEV *T : NewTerms) 11220 dbgs() << *T << "\n"; 11221 }); 11222 11223 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11224 Sizes.clear(); 11225 return; 11226 } 11227 11228 // The last element to be pushed into Sizes is the size of an element. 11229 Sizes.push_back(ElementSize); 11230 11231 LLVM_DEBUG({ 11232 dbgs() << "Sizes:\n"; 11233 for (const SCEV *S : Sizes) 11234 dbgs() << *S << "\n"; 11235 }); 11236 } 11237 11238 void ScalarEvolution::computeAccessFunctions( 11239 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11240 SmallVectorImpl<const SCEV *> &Sizes) { 11241 // Early exit in case this SCEV is not an affine multivariate function. 11242 if (Sizes.empty()) 11243 return; 11244 11245 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11246 if (!AR->isAffine()) 11247 return; 11248 11249 const SCEV *Res = Expr; 11250 int Last = Sizes.size() - 1; 11251 for (int i = Last; i >= 0; i--) { 11252 const SCEV *Q, *R; 11253 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11254 11255 LLVM_DEBUG({ 11256 dbgs() << "Res: " << *Res << "\n"; 11257 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11258 dbgs() << "Res divided by Sizes[i]:\n"; 11259 dbgs() << "Quotient: " << *Q << "\n"; 11260 dbgs() << "Remainder: " << *R << "\n"; 11261 }); 11262 11263 Res = Q; 11264 11265 // Do not record the last subscript corresponding to the size of elements in 11266 // the array. 11267 if (i == Last) { 11268 11269 // Bail out if the remainder is too complex. 11270 if (isa<SCEVAddRecExpr>(R)) { 11271 Subscripts.clear(); 11272 Sizes.clear(); 11273 return; 11274 } 11275 11276 continue; 11277 } 11278 11279 // Record the access function for the current subscript. 11280 Subscripts.push_back(R); 11281 } 11282 11283 // Also push in last position the remainder of the last division: it will be 11284 // the access function of the innermost dimension. 11285 Subscripts.push_back(Res); 11286 11287 std::reverse(Subscripts.begin(), Subscripts.end()); 11288 11289 LLVM_DEBUG({ 11290 dbgs() << "Subscripts:\n"; 11291 for (const SCEV *S : Subscripts) 11292 dbgs() << *S << "\n"; 11293 }); 11294 } 11295 11296 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11297 /// sizes of an array access. Returns the remainder of the delinearization that 11298 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11299 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11300 /// expressions in the stride and base of a SCEV corresponding to the 11301 /// computation of a GCD (greatest common divisor) of base and stride. When 11302 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11303 /// 11304 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11305 /// 11306 /// void foo(long n, long m, long o, double A[n][m][o]) { 11307 /// 11308 /// for (long i = 0; i < n; i++) 11309 /// for (long j = 0; j < m; j++) 11310 /// for (long k = 0; k < o; k++) 11311 /// A[i][j][k] = 1.0; 11312 /// } 11313 /// 11314 /// the delinearization input is the following AddRec SCEV: 11315 /// 11316 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11317 /// 11318 /// From this SCEV, we are able to say that the base offset of the access is %A 11319 /// because it appears as an offset that does not divide any of the strides in 11320 /// the loops: 11321 /// 11322 /// CHECK: Base offset: %A 11323 /// 11324 /// and then SCEV->delinearize determines the size of some of the dimensions of 11325 /// the array as these are the multiples by which the strides are happening: 11326 /// 11327 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11328 /// 11329 /// Note that the outermost dimension remains of UnknownSize because there are 11330 /// no strides that would help identifying the size of the last dimension: when 11331 /// the array has been statically allocated, one could compute the size of that 11332 /// dimension by dividing the overall size of the array by the size of the known 11333 /// dimensions: %m * %o * 8. 11334 /// 11335 /// Finally delinearize provides the access functions for the array reference 11336 /// that does correspond to A[i][j][k] of the above C testcase: 11337 /// 11338 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11339 /// 11340 /// The testcases are checking the output of a function pass: 11341 /// DelinearizationPass that walks through all loads and stores of a function 11342 /// asking for the SCEV of the memory access with respect to all enclosing 11343 /// loops, calling SCEV->delinearize on that and printing the results. 11344 void ScalarEvolution::delinearize(const SCEV *Expr, 11345 SmallVectorImpl<const SCEV *> &Subscripts, 11346 SmallVectorImpl<const SCEV *> &Sizes, 11347 const SCEV *ElementSize) { 11348 // First step: collect parametric terms. 11349 SmallVector<const SCEV *, 4> Terms; 11350 collectParametricTerms(Expr, Terms); 11351 11352 if (Terms.empty()) 11353 return; 11354 11355 // Second step: find subscript sizes. 11356 findArrayDimensions(Terms, Sizes, ElementSize); 11357 11358 if (Sizes.empty()) 11359 return; 11360 11361 // Third step: compute the access functions for each subscript. 11362 computeAccessFunctions(Expr, Subscripts, Sizes); 11363 11364 if (Subscripts.empty()) 11365 return; 11366 11367 LLVM_DEBUG({ 11368 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11369 dbgs() << "ArrayDecl[UnknownSize]"; 11370 for (const SCEV *S : Sizes) 11371 dbgs() << "[" << *S << "]"; 11372 11373 dbgs() << "\nArrayRef"; 11374 for (const SCEV *S : Subscripts) 11375 dbgs() << "[" << *S << "]"; 11376 dbgs() << "\n"; 11377 }); 11378 } 11379 11380 //===----------------------------------------------------------------------===// 11381 // SCEVCallbackVH Class Implementation 11382 //===----------------------------------------------------------------------===// 11383 11384 void ScalarEvolution::SCEVCallbackVH::deleted() { 11385 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11386 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11387 SE->ConstantEvolutionLoopExitValue.erase(PN); 11388 SE->eraseValueFromMap(getValPtr()); 11389 // this now dangles! 11390 } 11391 11392 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11393 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11394 11395 // Forget all the expressions associated with users of the old value, 11396 // so that future queries will recompute the expressions using the new 11397 // value. 11398 Value *Old = getValPtr(); 11399 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11400 SmallPtrSet<User *, 8> Visited; 11401 while (!Worklist.empty()) { 11402 User *U = Worklist.pop_back_val(); 11403 // Deleting the Old value will cause this to dangle. Postpone 11404 // that until everything else is done. 11405 if (U == Old) 11406 continue; 11407 if (!Visited.insert(U).second) 11408 continue; 11409 if (PHINode *PN = dyn_cast<PHINode>(U)) 11410 SE->ConstantEvolutionLoopExitValue.erase(PN); 11411 SE->eraseValueFromMap(U); 11412 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11413 } 11414 // Delete the Old value. 11415 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11416 SE->ConstantEvolutionLoopExitValue.erase(PN); 11417 SE->eraseValueFromMap(Old); 11418 // this now dangles! 11419 } 11420 11421 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11422 : CallbackVH(V), SE(se) {} 11423 11424 //===----------------------------------------------------------------------===// 11425 // ScalarEvolution Class Implementation 11426 //===----------------------------------------------------------------------===// 11427 11428 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11429 AssumptionCache &AC, DominatorTree &DT, 11430 LoopInfo &LI) 11431 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11432 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11433 LoopDispositions(64), BlockDispositions(64) { 11434 // To use guards for proving predicates, we need to scan every instruction in 11435 // relevant basic blocks, and not just terminators. Doing this is a waste of 11436 // time if the IR does not actually contain any calls to 11437 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11438 // 11439 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11440 // to _add_ guards to the module when there weren't any before, and wants 11441 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11442 // efficient in lieu of being smart in that rather obscure case. 11443 11444 auto *GuardDecl = F.getParent()->getFunction( 11445 Intrinsic::getName(Intrinsic::experimental_guard)); 11446 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11447 } 11448 11449 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11450 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11451 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11452 ValueExprMap(std::move(Arg.ValueExprMap)), 11453 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11454 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11455 PendingMerges(std::move(Arg.PendingMerges)), 11456 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11457 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11458 PredicatedBackedgeTakenCounts( 11459 std::move(Arg.PredicatedBackedgeTakenCounts)), 11460 ConstantEvolutionLoopExitValue( 11461 std::move(Arg.ConstantEvolutionLoopExitValue)), 11462 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11463 LoopDispositions(std::move(Arg.LoopDispositions)), 11464 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11465 BlockDispositions(std::move(Arg.BlockDispositions)), 11466 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11467 SignedRanges(std::move(Arg.SignedRanges)), 11468 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11469 UniquePreds(std::move(Arg.UniquePreds)), 11470 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11471 LoopUsers(std::move(Arg.LoopUsers)), 11472 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11473 FirstUnknown(Arg.FirstUnknown) { 11474 Arg.FirstUnknown = nullptr; 11475 } 11476 11477 ScalarEvolution::~ScalarEvolution() { 11478 // Iterate through all the SCEVUnknown instances and call their 11479 // destructors, so that they release their references to their values. 11480 for (SCEVUnknown *U = FirstUnknown; U;) { 11481 SCEVUnknown *Tmp = U; 11482 U = U->Next; 11483 Tmp->~SCEVUnknown(); 11484 } 11485 FirstUnknown = nullptr; 11486 11487 ExprValueMap.clear(); 11488 ValueExprMap.clear(); 11489 HasRecMap.clear(); 11490 11491 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11492 // that a loop had multiple computable exits. 11493 for (auto &BTCI : BackedgeTakenCounts) 11494 BTCI.second.clear(); 11495 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11496 BTCI.second.clear(); 11497 11498 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11499 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11500 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11501 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11502 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11503 } 11504 11505 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11506 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11507 } 11508 11509 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11510 const Loop *L) { 11511 // Print all inner loops first 11512 for (Loop *I : *L) 11513 PrintLoopInfo(OS, SE, I); 11514 11515 OS << "Loop "; 11516 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11517 OS << ": "; 11518 11519 SmallVector<BasicBlock *, 8> ExitingBlocks; 11520 L->getExitingBlocks(ExitingBlocks); 11521 if (ExitingBlocks.size() != 1) 11522 OS << "<multiple exits> "; 11523 11524 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11525 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11526 else 11527 OS << "Unpredictable backedge-taken count.\n"; 11528 11529 if (ExitingBlocks.size() > 1) 11530 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11531 OS << " exit count for " << ExitingBlock->getName() << ": " 11532 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11533 } 11534 11535 OS << "Loop "; 11536 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11537 OS << ": "; 11538 11539 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11540 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11541 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11542 OS << ", actual taken count either this or zero."; 11543 } else { 11544 OS << "Unpredictable max backedge-taken count. "; 11545 } 11546 11547 OS << "\n" 11548 "Loop "; 11549 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11550 OS << ": "; 11551 11552 SCEVUnionPredicate Pred; 11553 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11554 if (!isa<SCEVCouldNotCompute>(PBT)) { 11555 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11556 OS << " Predicates:\n"; 11557 Pred.print(OS, 4); 11558 } else { 11559 OS << "Unpredictable predicated backedge-taken count. "; 11560 } 11561 OS << "\n"; 11562 11563 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11564 OS << "Loop "; 11565 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11566 OS << ": "; 11567 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11568 } 11569 } 11570 11571 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11572 switch (LD) { 11573 case ScalarEvolution::LoopVariant: 11574 return "Variant"; 11575 case ScalarEvolution::LoopInvariant: 11576 return "Invariant"; 11577 case ScalarEvolution::LoopComputable: 11578 return "Computable"; 11579 } 11580 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11581 } 11582 11583 void ScalarEvolution::print(raw_ostream &OS) const { 11584 // ScalarEvolution's implementation of the print method is to print 11585 // out SCEV values of all instructions that are interesting. Doing 11586 // this potentially causes it to create new SCEV objects though, 11587 // which technically conflicts with the const qualifier. This isn't 11588 // observable from outside the class though, so casting away the 11589 // const isn't dangerous. 11590 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11591 11592 if (ClassifyExpressions) { 11593 OS << "Classifying expressions for: "; 11594 F.printAsOperand(OS, /*PrintType=*/false); 11595 OS << "\n"; 11596 for (Instruction &I : instructions(F)) 11597 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11598 OS << I << '\n'; 11599 OS << " --> "; 11600 const SCEV *SV = SE.getSCEV(&I); 11601 SV->print(OS); 11602 if (!isa<SCEVCouldNotCompute>(SV)) { 11603 OS << " U: "; 11604 SE.getUnsignedRange(SV).print(OS); 11605 OS << " S: "; 11606 SE.getSignedRange(SV).print(OS); 11607 } 11608 11609 const Loop *L = LI.getLoopFor(I.getParent()); 11610 11611 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11612 if (AtUse != SV) { 11613 OS << " --> "; 11614 AtUse->print(OS); 11615 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11616 OS << " U: "; 11617 SE.getUnsignedRange(AtUse).print(OS); 11618 OS << " S: "; 11619 SE.getSignedRange(AtUse).print(OS); 11620 } 11621 } 11622 11623 if (L) { 11624 OS << "\t\t" "Exits: "; 11625 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11626 if (!SE.isLoopInvariant(ExitValue, L)) { 11627 OS << "<<Unknown>>"; 11628 } else { 11629 OS << *ExitValue; 11630 } 11631 11632 bool First = true; 11633 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11634 if (First) { 11635 OS << "\t\t" "LoopDispositions: { "; 11636 First = false; 11637 } else { 11638 OS << ", "; 11639 } 11640 11641 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11642 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11643 } 11644 11645 for (auto *InnerL : depth_first(L)) { 11646 if (InnerL == L) 11647 continue; 11648 if (First) { 11649 OS << "\t\t" "LoopDispositions: { "; 11650 First = false; 11651 } else { 11652 OS << ", "; 11653 } 11654 11655 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11656 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11657 } 11658 11659 OS << " }"; 11660 } 11661 11662 OS << "\n"; 11663 } 11664 } 11665 11666 OS << "Determining loop execution counts for: "; 11667 F.printAsOperand(OS, /*PrintType=*/false); 11668 OS << "\n"; 11669 for (Loop *I : LI) 11670 PrintLoopInfo(OS, &SE, I); 11671 } 11672 11673 ScalarEvolution::LoopDisposition 11674 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11675 auto &Values = LoopDispositions[S]; 11676 for (auto &V : Values) { 11677 if (V.getPointer() == L) 11678 return V.getInt(); 11679 } 11680 Values.emplace_back(L, LoopVariant); 11681 LoopDisposition D = computeLoopDisposition(S, L); 11682 auto &Values2 = LoopDispositions[S]; 11683 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11684 if (V.getPointer() == L) { 11685 V.setInt(D); 11686 break; 11687 } 11688 } 11689 return D; 11690 } 11691 11692 ScalarEvolution::LoopDisposition 11693 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11694 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11695 case scConstant: 11696 return LoopInvariant; 11697 case scTruncate: 11698 case scZeroExtend: 11699 case scSignExtend: 11700 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11701 case scAddRecExpr: { 11702 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11703 11704 // If L is the addrec's loop, it's computable. 11705 if (AR->getLoop() == L) 11706 return LoopComputable; 11707 11708 // Add recurrences are never invariant in the function-body (null loop). 11709 if (!L) 11710 return LoopVariant; 11711 11712 // Everything that is not defined at loop entry is variant. 11713 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11714 return LoopVariant; 11715 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11716 " dominate the contained loop's header?"); 11717 11718 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11719 if (AR->getLoop()->contains(L)) 11720 return LoopInvariant; 11721 11722 // This recurrence is variant w.r.t. L if any of its operands 11723 // are variant. 11724 for (auto *Op : AR->operands()) 11725 if (!isLoopInvariant(Op, L)) 11726 return LoopVariant; 11727 11728 // Otherwise it's loop-invariant. 11729 return LoopInvariant; 11730 } 11731 case scAddExpr: 11732 case scMulExpr: 11733 case scUMaxExpr: 11734 case scSMaxExpr: 11735 case scUMinExpr: 11736 case scSMinExpr: { 11737 bool HasVarying = false; 11738 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11739 LoopDisposition D = getLoopDisposition(Op, L); 11740 if (D == LoopVariant) 11741 return LoopVariant; 11742 if (D == LoopComputable) 11743 HasVarying = true; 11744 } 11745 return HasVarying ? LoopComputable : LoopInvariant; 11746 } 11747 case scUDivExpr: { 11748 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11749 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11750 if (LD == LoopVariant) 11751 return LoopVariant; 11752 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11753 if (RD == LoopVariant) 11754 return LoopVariant; 11755 return (LD == LoopInvariant && RD == LoopInvariant) ? 11756 LoopInvariant : LoopComputable; 11757 } 11758 case scUnknown: 11759 // All non-instruction values are loop invariant. All instructions are loop 11760 // invariant if they are not contained in the specified loop. 11761 // Instructions are never considered invariant in the function body 11762 // (null loop) because they are defined within the "loop". 11763 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11764 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11765 return LoopInvariant; 11766 case scCouldNotCompute: 11767 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11768 } 11769 llvm_unreachable("Unknown SCEV kind!"); 11770 } 11771 11772 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11773 return getLoopDisposition(S, L) == LoopInvariant; 11774 } 11775 11776 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11777 return getLoopDisposition(S, L) == LoopComputable; 11778 } 11779 11780 ScalarEvolution::BlockDisposition 11781 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11782 auto &Values = BlockDispositions[S]; 11783 for (auto &V : Values) { 11784 if (V.getPointer() == BB) 11785 return V.getInt(); 11786 } 11787 Values.emplace_back(BB, DoesNotDominateBlock); 11788 BlockDisposition D = computeBlockDisposition(S, BB); 11789 auto &Values2 = BlockDispositions[S]; 11790 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11791 if (V.getPointer() == BB) { 11792 V.setInt(D); 11793 break; 11794 } 11795 } 11796 return D; 11797 } 11798 11799 ScalarEvolution::BlockDisposition 11800 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11801 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11802 case scConstant: 11803 return ProperlyDominatesBlock; 11804 case scTruncate: 11805 case scZeroExtend: 11806 case scSignExtend: 11807 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11808 case scAddRecExpr: { 11809 // This uses a "dominates" query instead of "properly dominates" query 11810 // to test for proper dominance too, because the instruction which 11811 // produces the addrec's value is a PHI, and a PHI effectively properly 11812 // dominates its entire containing block. 11813 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11814 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11815 return DoesNotDominateBlock; 11816 11817 // Fall through into SCEVNAryExpr handling. 11818 LLVM_FALLTHROUGH; 11819 } 11820 case scAddExpr: 11821 case scMulExpr: 11822 case scUMaxExpr: 11823 case scSMaxExpr: 11824 case scUMinExpr: 11825 case scSMinExpr: { 11826 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11827 bool Proper = true; 11828 for (const SCEV *NAryOp : NAry->operands()) { 11829 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11830 if (D == DoesNotDominateBlock) 11831 return DoesNotDominateBlock; 11832 if (D == DominatesBlock) 11833 Proper = false; 11834 } 11835 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11836 } 11837 case scUDivExpr: { 11838 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11839 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11840 BlockDisposition LD = getBlockDisposition(LHS, BB); 11841 if (LD == DoesNotDominateBlock) 11842 return DoesNotDominateBlock; 11843 BlockDisposition RD = getBlockDisposition(RHS, BB); 11844 if (RD == DoesNotDominateBlock) 11845 return DoesNotDominateBlock; 11846 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11847 ProperlyDominatesBlock : DominatesBlock; 11848 } 11849 case scUnknown: 11850 if (Instruction *I = 11851 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11852 if (I->getParent() == BB) 11853 return DominatesBlock; 11854 if (DT.properlyDominates(I->getParent(), BB)) 11855 return ProperlyDominatesBlock; 11856 return DoesNotDominateBlock; 11857 } 11858 return ProperlyDominatesBlock; 11859 case scCouldNotCompute: 11860 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11861 } 11862 llvm_unreachable("Unknown SCEV kind!"); 11863 } 11864 11865 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11866 return getBlockDisposition(S, BB) >= DominatesBlock; 11867 } 11868 11869 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11870 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11871 } 11872 11873 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11874 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11875 } 11876 11877 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11878 auto IsS = [&](const SCEV *X) { return S == X; }; 11879 auto ContainsS = [&](const SCEV *X) { 11880 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 11881 }; 11882 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 11883 } 11884 11885 void 11886 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 11887 ValuesAtScopes.erase(S); 11888 LoopDispositions.erase(S); 11889 BlockDispositions.erase(S); 11890 UnsignedRanges.erase(S); 11891 SignedRanges.erase(S); 11892 ExprValueMap.erase(S); 11893 HasRecMap.erase(S); 11894 MinTrailingZerosCache.erase(S); 11895 11896 for (auto I = PredicatedSCEVRewrites.begin(); 11897 I != PredicatedSCEVRewrites.end();) { 11898 std::pair<const SCEV *, const Loop *> Entry = I->first; 11899 if (Entry.first == S) 11900 PredicatedSCEVRewrites.erase(I++); 11901 else 11902 ++I; 11903 } 11904 11905 auto RemoveSCEVFromBackedgeMap = 11906 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 11907 for (auto I = Map.begin(), E = Map.end(); I != E;) { 11908 BackedgeTakenInfo &BEInfo = I->second; 11909 if (BEInfo.hasOperand(S, this)) { 11910 BEInfo.clear(); 11911 Map.erase(I++); 11912 } else 11913 ++I; 11914 } 11915 }; 11916 11917 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 11918 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 11919 } 11920 11921 void 11922 ScalarEvolution::getUsedLoops(const SCEV *S, 11923 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 11924 struct FindUsedLoops { 11925 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 11926 : LoopsUsed(LoopsUsed) {} 11927 SmallPtrSetImpl<const Loop *> &LoopsUsed; 11928 bool follow(const SCEV *S) { 11929 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 11930 LoopsUsed.insert(AR->getLoop()); 11931 return true; 11932 } 11933 11934 bool isDone() const { return false; } 11935 }; 11936 11937 FindUsedLoops F(LoopsUsed); 11938 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 11939 } 11940 11941 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 11942 SmallPtrSet<const Loop *, 8> LoopsUsed; 11943 getUsedLoops(S, LoopsUsed); 11944 for (auto *L : LoopsUsed) 11945 LoopUsers[L].push_back(S); 11946 } 11947 11948 void ScalarEvolution::verify() const { 11949 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11950 ScalarEvolution SE2(F, TLI, AC, DT, LI); 11951 11952 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 11953 11954 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 11955 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 11956 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 11957 11958 const SCEV *visitConstant(const SCEVConstant *Constant) { 11959 return SE.getConstant(Constant->getAPInt()); 11960 } 11961 11962 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 11963 return SE.getUnknown(Expr->getValue()); 11964 } 11965 11966 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 11967 return SE.getCouldNotCompute(); 11968 } 11969 }; 11970 11971 SCEVMapper SCM(SE2); 11972 11973 while (!LoopStack.empty()) { 11974 auto *L = LoopStack.pop_back_val(); 11975 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 11976 11977 auto *CurBECount = SCM.visit( 11978 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 11979 auto *NewBECount = SE2.getBackedgeTakenCount(L); 11980 11981 if (CurBECount == SE2.getCouldNotCompute() || 11982 NewBECount == SE2.getCouldNotCompute()) { 11983 // NB! This situation is legal, but is very suspicious -- whatever pass 11984 // change the loop to make a trip count go from could not compute to 11985 // computable or vice-versa *should have* invalidated SCEV. However, we 11986 // choose not to assert here (for now) since we don't want false 11987 // positives. 11988 continue; 11989 } 11990 11991 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 11992 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 11993 // not propagate undef aggressively). This means we can (and do) fail 11994 // verification in cases where a transform makes the trip count of a loop 11995 // go from "undef" to "undef+1" (say). The transform is fine, since in 11996 // both cases the loop iterates "undef" times, but SCEV thinks we 11997 // increased the trip count of the loop by 1 incorrectly. 11998 continue; 11999 } 12000 12001 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12002 SE.getTypeSizeInBits(NewBECount->getType())) 12003 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12004 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12005 SE.getTypeSizeInBits(NewBECount->getType())) 12006 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12007 12008 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12009 12010 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12011 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12012 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12013 dbgs() << "Old: " << *CurBECount << "\n"; 12014 dbgs() << "New: " << *NewBECount << "\n"; 12015 dbgs() << "Delta: " << *Delta << "\n"; 12016 std::abort(); 12017 } 12018 } 12019 } 12020 12021 bool ScalarEvolution::invalidate( 12022 Function &F, const PreservedAnalyses &PA, 12023 FunctionAnalysisManager::Invalidator &Inv) { 12024 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12025 // of its dependencies is invalidated. 12026 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12027 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12028 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12029 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12030 Inv.invalidate<LoopAnalysis>(F, PA); 12031 } 12032 12033 AnalysisKey ScalarEvolutionAnalysis::Key; 12034 12035 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12036 FunctionAnalysisManager &AM) { 12037 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12038 AM.getResult<AssumptionAnalysis>(F), 12039 AM.getResult<DominatorTreeAnalysis>(F), 12040 AM.getResult<LoopAnalysis>(F)); 12041 } 12042 12043 PreservedAnalyses 12044 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12045 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12046 return PreservedAnalyses::all(); 12047 } 12048 12049 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12050 "Scalar Evolution Analysis", false, true) 12051 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12052 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12053 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12054 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12055 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12056 "Scalar Evolution Analysis", false, true) 12057 12058 char ScalarEvolutionWrapperPass::ID = 0; 12059 12060 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12061 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12062 } 12063 12064 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12065 SE.reset(new ScalarEvolution( 12066 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12067 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12068 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12069 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12070 return false; 12071 } 12072 12073 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12074 12075 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12076 SE->print(OS); 12077 } 12078 12079 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12080 if (!VerifySCEV) 12081 return; 12082 12083 SE->verify(); 12084 } 12085 12086 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12087 AU.setPreservesAll(); 12088 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12089 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12090 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12091 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12092 } 12093 12094 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12095 const SCEV *RHS) { 12096 FoldingSetNodeID ID; 12097 assert(LHS->getType() == RHS->getType() && 12098 "Type mismatch between LHS and RHS"); 12099 // Unique this node based on the arguments 12100 ID.AddInteger(SCEVPredicate::P_Equal); 12101 ID.AddPointer(LHS); 12102 ID.AddPointer(RHS); 12103 void *IP = nullptr; 12104 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12105 return S; 12106 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12107 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12108 UniquePreds.InsertNode(Eq, IP); 12109 return Eq; 12110 } 12111 12112 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12113 const SCEVAddRecExpr *AR, 12114 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12115 FoldingSetNodeID ID; 12116 // Unique this node based on the arguments 12117 ID.AddInteger(SCEVPredicate::P_Wrap); 12118 ID.AddPointer(AR); 12119 ID.AddInteger(AddedFlags); 12120 void *IP = nullptr; 12121 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12122 return S; 12123 auto *OF = new (SCEVAllocator) 12124 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12125 UniquePreds.InsertNode(OF, IP); 12126 return OF; 12127 } 12128 12129 namespace { 12130 12131 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12132 public: 12133 12134 /// Rewrites \p S in the context of a loop L and the SCEV predication 12135 /// infrastructure. 12136 /// 12137 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12138 /// equivalences present in \p Pred. 12139 /// 12140 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12141 /// \p NewPreds such that the result will be an AddRecExpr. 12142 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12143 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12144 SCEVUnionPredicate *Pred) { 12145 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12146 return Rewriter.visit(S); 12147 } 12148 12149 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12150 if (Pred) { 12151 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12152 for (auto *Pred : ExprPreds) 12153 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12154 if (IPred->getLHS() == Expr) 12155 return IPred->getRHS(); 12156 } 12157 return convertToAddRecWithPreds(Expr); 12158 } 12159 12160 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12161 const SCEV *Operand = visit(Expr->getOperand()); 12162 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12163 if (AR && AR->getLoop() == L && AR->isAffine()) { 12164 // This couldn't be folded because the operand didn't have the nuw 12165 // flag. Add the nusw flag as an assumption that we could make. 12166 const SCEV *Step = AR->getStepRecurrence(SE); 12167 Type *Ty = Expr->getType(); 12168 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12169 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12170 SE.getSignExtendExpr(Step, Ty), L, 12171 AR->getNoWrapFlags()); 12172 } 12173 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12174 } 12175 12176 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12177 const SCEV *Operand = visit(Expr->getOperand()); 12178 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12179 if (AR && AR->getLoop() == L && AR->isAffine()) { 12180 // This couldn't be folded because the operand didn't have the nsw 12181 // flag. Add the nssw flag as an assumption that we could make. 12182 const SCEV *Step = AR->getStepRecurrence(SE); 12183 Type *Ty = Expr->getType(); 12184 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12185 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12186 SE.getSignExtendExpr(Step, Ty), L, 12187 AR->getNoWrapFlags()); 12188 } 12189 return SE.getSignExtendExpr(Operand, Expr->getType()); 12190 } 12191 12192 private: 12193 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12194 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12195 SCEVUnionPredicate *Pred) 12196 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12197 12198 bool addOverflowAssumption(const SCEVPredicate *P) { 12199 if (!NewPreds) { 12200 // Check if we've already made this assumption. 12201 return Pred && Pred->implies(P); 12202 } 12203 NewPreds->insert(P); 12204 return true; 12205 } 12206 12207 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12208 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12209 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12210 return addOverflowAssumption(A); 12211 } 12212 12213 // If \p Expr represents a PHINode, we try to see if it can be represented 12214 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12215 // to add this predicate as a runtime overflow check, we return the AddRec. 12216 // If \p Expr does not meet these conditions (is not a PHI node, or we 12217 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12218 // return \p Expr. 12219 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12220 if (!isa<PHINode>(Expr->getValue())) 12221 return Expr; 12222 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12223 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12224 if (!PredicatedRewrite) 12225 return Expr; 12226 for (auto *P : PredicatedRewrite->second){ 12227 // Wrap predicates from outer loops are not supported. 12228 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12229 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12230 if (L != AR->getLoop()) 12231 return Expr; 12232 } 12233 if (!addOverflowAssumption(P)) 12234 return Expr; 12235 } 12236 return PredicatedRewrite->first; 12237 } 12238 12239 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12240 SCEVUnionPredicate *Pred; 12241 const Loop *L; 12242 }; 12243 12244 } // end anonymous namespace 12245 12246 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12247 SCEVUnionPredicate &Preds) { 12248 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12249 } 12250 12251 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12252 const SCEV *S, const Loop *L, 12253 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12254 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12255 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12256 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12257 12258 if (!AddRec) 12259 return nullptr; 12260 12261 // Since the transformation was successful, we can now transfer the SCEV 12262 // predicates. 12263 for (auto *P : TransformPreds) 12264 Preds.insert(P); 12265 12266 return AddRec; 12267 } 12268 12269 /// SCEV predicates 12270 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12271 SCEVPredicateKind Kind) 12272 : FastID(ID), Kind(Kind) {} 12273 12274 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12275 const SCEV *LHS, const SCEV *RHS) 12276 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12277 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12278 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12279 } 12280 12281 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12282 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12283 12284 if (!Op) 12285 return false; 12286 12287 return Op->LHS == LHS && Op->RHS == RHS; 12288 } 12289 12290 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12291 12292 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12293 12294 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12295 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12296 } 12297 12298 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12299 const SCEVAddRecExpr *AR, 12300 IncrementWrapFlags Flags) 12301 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12302 12303 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12304 12305 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12306 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12307 12308 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12309 } 12310 12311 bool SCEVWrapPredicate::isAlwaysTrue() const { 12312 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12313 IncrementWrapFlags IFlags = Flags; 12314 12315 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12316 IFlags = clearFlags(IFlags, IncrementNSSW); 12317 12318 return IFlags == IncrementAnyWrap; 12319 } 12320 12321 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12322 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12323 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12324 OS << "<nusw>"; 12325 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12326 OS << "<nssw>"; 12327 OS << "\n"; 12328 } 12329 12330 SCEVWrapPredicate::IncrementWrapFlags 12331 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12332 ScalarEvolution &SE) { 12333 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12334 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12335 12336 // We can safely transfer the NSW flag as NSSW. 12337 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12338 ImpliedFlags = IncrementNSSW; 12339 12340 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12341 // If the increment is positive, the SCEV NUW flag will also imply the 12342 // WrapPredicate NUSW flag. 12343 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12344 if (Step->getValue()->getValue().isNonNegative()) 12345 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12346 } 12347 12348 return ImpliedFlags; 12349 } 12350 12351 /// Union predicates don't get cached so create a dummy set ID for it. 12352 SCEVUnionPredicate::SCEVUnionPredicate() 12353 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12354 12355 bool SCEVUnionPredicate::isAlwaysTrue() const { 12356 return all_of(Preds, 12357 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12358 } 12359 12360 ArrayRef<const SCEVPredicate *> 12361 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12362 auto I = SCEVToPreds.find(Expr); 12363 if (I == SCEVToPreds.end()) 12364 return ArrayRef<const SCEVPredicate *>(); 12365 return I->second; 12366 } 12367 12368 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12369 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12370 return all_of(Set->Preds, 12371 [this](const SCEVPredicate *I) { return this->implies(I); }); 12372 12373 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12374 if (ScevPredsIt == SCEVToPreds.end()) 12375 return false; 12376 auto &SCEVPreds = ScevPredsIt->second; 12377 12378 return any_of(SCEVPreds, 12379 [N](const SCEVPredicate *I) { return I->implies(N); }); 12380 } 12381 12382 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12383 12384 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12385 for (auto Pred : Preds) 12386 Pred->print(OS, Depth); 12387 } 12388 12389 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12390 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12391 for (auto Pred : Set->Preds) 12392 add(Pred); 12393 return; 12394 } 12395 12396 if (implies(N)) 12397 return; 12398 12399 const SCEV *Key = N->getExpr(); 12400 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12401 " associated expression!"); 12402 12403 SCEVToPreds[Key].push_back(N); 12404 Preds.push_back(N); 12405 } 12406 12407 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12408 Loop &L) 12409 : SE(SE), L(L) {} 12410 12411 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12412 const SCEV *Expr = SE.getSCEV(V); 12413 RewriteEntry &Entry = RewriteMap[Expr]; 12414 12415 // If we already have an entry and the version matches, return it. 12416 if (Entry.second && Generation == Entry.first) 12417 return Entry.second; 12418 12419 // We found an entry but it's stale. Rewrite the stale entry 12420 // according to the current predicate. 12421 if (Entry.second) 12422 Expr = Entry.second; 12423 12424 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12425 Entry = {Generation, NewSCEV}; 12426 12427 return NewSCEV; 12428 } 12429 12430 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12431 if (!BackedgeCount) { 12432 SCEVUnionPredicate BackedgePred; 12433 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12434 addPredicate(BackedgePred); 12435 } 12436 return BackedgeCount; 12437 } 12438 12439 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12440 if (Preds.implies(&Pred)) 12441 return; 12442 Preds.add(&Pred); 12443 updateGeneration(); 12444 } 12445 12446 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12447 return Preds; 12448 } 12449 12450 void PredicatedScalarEvolution::updateGeneration() { 12451 // If the generation number wrapped recompute everything. 12452 if (++Generation == 0) { 12453 for (auto &II : RewriteMap) { 12454 const SCEV *Rewritten = II.second.second; 12455 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12456 } 12457 } 12458 } 12459 12460 void PredicatedScalarEvolution::setNoOverflow( 12461 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12462 const SCEV *Expr = getSCEV(V); 12463 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12464 12465 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12466 12467 // Clear the statically implied flags. 12468 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12469 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12470 12471 auto II = FlagsMap.insert({V, Flags}); 12472 if (!II.second) 12473 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12474 } 12475 12476 bool PredicatedScalarEvolution::hasNoOverflow( 12477 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12478 const SCEV *Expr = getSCEV(V); 12479 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12480 12481 Flags = SCEVWrapPredicate::clearFlags( 12482 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12483 12484 auto II = FlagsMap.find(V); 12485 12486 if (II != FlagsMap.end()) 12487 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12488 12489 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12490 } 12491 12492 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12493 const SCEV *Expr = this->getSCEV(V); 12494 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12495 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12496 12497 if (!New) 12498 return nullptr; 12499 12500 for (auto *P : NewPreds) 12501 Preds.add(P); 12502 12503 updateGeneration(); 12504 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12505 return New; 12506 } 12507 12508 PredicatedScalarEvolution::PredicatedScalarEvolution( 12509 const PredicatedScalarEvolution &Init) 12510 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12511 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12512 for (const auto &I : Init.FlagsMap) 12513 FlagsMap.insert(I); 12514 } 12515 12516 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12517 // For each block. 12518 for (auto *BB : L.getBlocks()) 12519 for (auto &I : *BB) { 12520 if (!SE.isSCEVable(I.getType())) 12521 continue; 12522 12523 auto *Expr = SE.getSCEV(&I); 12524 auto II = RewriteMap.find(Expr); 12525 12526 if (II == RewriteMap.end()) 12527 continue; 12528 12529 // Don't print things that are not interesting. 12530 if (II->second.second == Expr) 12531 continue; 12532 12533 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12534 OS.indent(Depth + 2) << *Expr << "\n"; 12535 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12536 } 12537 } 12538 12539 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12540 // arbitrary expressions. 12541 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12542 // 4, A / B becomes X / 8). 12543 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12544 const SCEV *&RHS) { 12545 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12546 if (Add == nullptr || Add->getNumOperands() != 2) 12547 return false; 12548 12549 const SCEV *A = Add->getOperand(1); 12550 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12551 12552 if (Mul == nullptr) 12553 return false; 12554 12555 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12556 // (SomeExpr + (-(SomeExpr / B) * B)). 12557 if (Expr == getURemExpr(A, B)) { 12558 LHS = A; 12559 RHS = B; 12560 return true; 12561 } 12562 return false; 12563 }; 12564 12565 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12566 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12567 return MatchURemWithDivisor(Mul->getOperand(1)) || 12568 MatchURemWithDivisor(Mul->getOperand(2)); 12569 12570 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12571 if (Mul->getNumOperands() == 2) 12572 return MatchURemWithDivisor(Mul->getOperand(1)) || 12573 MatchURemWithDivisor(Mul->getOperand(0)) || 12574 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12575 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12576 return false; 12577 } 12578