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/Constant.h" 90 #include "llvm/IR/ConstantRange.h" 91 #include "llvm/IR/Constants.h" 92 #include "llvm/IR/DataLayout.h" 93 #include "llvm/IR/DerivedTypes.h" 94 #include "llvm/IR/Dominators.h" 95 #include "llvm/IR/Function.h" 96 #include "llvm/IR/GlobalAlias.h" 97 #include "llvm/IR/GlobalValue.h" 98 #include "llvm/IR/GlobalVariable.h" 99 #include "llvm/IR/InstIterator.h" 100 #include "llvm/IR/InstrTypes.h" 101 #include "llvm/IR/Instruction.h" 102 #include "llvm/IR/Instructions.h" 103 #include "llvm/IR/IntrinsicInst.h" 104 #include "llvm/IR/Intrinsics.h" 105 #include "llvm/IR/LLVMContext.h" 106 #include "llvm/IR/Metadata.h" 107 #include "llvm/IR/Operator.h" 108 #include "llvm/IR/PatternMatch.h" 109 #include "llvm/IR/Type.h" 110 #include "llvm/IR/Use.h" 111 #include "llvm/IR/User.h" 112 #include "llvm/IR/Value.h" 113 #include "llvm/IR/Verifier.h" 114 #include "llvm/InitializePasses.h" 115 #include "llvm/Pass.h" 116 #include "llvm/Support/Casting.h" 117 #include "llvm/Support/CommandLine.h" 118 #include "llvm/Support/Compiler.h" 119 #include "llvm/Support/Debug.h" 120 #include "llvm/Support/ErrorHandling.h" 121 #include "llvm/Support/KnownBits.h" 122 #include "llvm/Support/SaveAndRestore.h" 123 #include "llvm/Support/raw_ostream.h" 124 #include <algorithm> 125 #include <cassert> 126 #include <climits> 127 #include <cstddef> 128 #include <cstdint> 129 #include <cstdlib> 130 #include <map> 131 #include <memory> 132 #include <tuple> 133 #include <utility> 134 #include <vector> 135 136 using namespace llvm; 137 138 #define DEBUG_TYPE "scalar-evolution" 139 140 STATISTIC(NumArrayLenItCounts, 141 "Number of trip counts computed with array length"); 142 STATISTIC(NumTripCountsComputed, 143 "Number of loops with predictable loop counts"); 144 STATISTIC(NumTripCountsNotComputed, 145 "Number of loops without predictable loop counts"); 146 STATISTIC(NumBruteForceTripCountsComputed, 147 "Number of loops with trip counts computed by force"); 148 149 static cl::opt<unsigned> 150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 151 cl::ZeroOrMore, 152 cl::desc("Maximum number of iterations SCEV will " 153 "symbolically execute a constant " 154 "derived loop"), 155 cl::init(100)); 156 157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 158 static cl::opt<bool> VerifySCEV( 159 "verify-scev", cl::Hidden, 160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 161 static cl::opt<bool> VerifySCEVStrict( 162 "verify-scev-strict", cl::Hidden, 163 cl::desc("Enable stricter verification with -verify-scev is passed")); 164 static cl::opt<bool> 165 VerifySCEVMap("verify-scev-maps", cl::Hidden, 166 cl::desc("Verify no dangling value in ScalarEvolution's " 167 "ExprValueMap (slow)")); 168 169 static cl::opt<bool> VerifyIR( 170 "scev-verify-ir", cl::Hidden, 171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 172 cl::init(false)); 173 174 static cl::opt<unsigned> MulOpsInlineThreshold( 175 "scev-mulops-inline-threshold", cl::Hidden, 176 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 177 cl::init(32)); 178 179 static cl::opt<unsigned> AddOpsInlineThreshold( 180 "scev-addops-inline-threshold", cl::Hidden, 181 cl::desc("Threshold for inlining addition operands into a SCEV"), 182 cl::init(500)); 183 184 static cl::opt<unsigned> MaxSCEVCompareDepth( 185 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 187 cl::init(32)); 188 189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 192 cl::init(2)); 193 194 static cl::opt<unsigned> MaxValueCompareDepth( 195 "scalar-evolution-max-value-compare-depth", cl::Hidden, 196 cl::desc("Maximum depth of recursive value complexity comparisons"), 197 cl::init(2)); 198 199 static cl::opt<unsigned> 200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 201 cl::desc("Maximum depth of recursive arithmetics"), 202 cl::init(32)); 203 204 static cl::opt<unsigned> MaxConstantEvolvingDepth( 205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 207 208 static cl::opt<unsigned> 209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 211 cl::init(8)); 212 213 static cl::opt<unsigned> 214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 215 cl::desc("Max coefficients in AddRec during evolving"), 216 cl::init(8)); 217 218 static cl::opt<unsigned> 219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 220 cl::desc("Size of the expression which is considered huge"), 221 cl::init(4096)); 222 223 static cl::opt<bool> 224 ClassifyExpressions("scalar-evolution-classify-expressions", 225 cl::Hidden, cl::init(true), 226 cl::desc("When printing analysis, include information on every instruction")); 227 228 229 //===----------------------------------------------------------------------===// 230 // SCEV class definitions 231 //===----------------------------------------------------------------------===// 232 233 //===----------------------------------------------------------------------===// 234 // Implementation of the SCEV class. 235 // 236 237 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 238 LLVM_DUMP_METHOD void SCEV::dump() const { 239 print(dbgs()); 240 dbgs() << '\n'; 241 } 242 #endif 243 244 void SCEV::print(raw_ostream &OS) const { 245 switch (static_cast<SCEVTypes>(getSCEVType())) { 246 case scConstant: 247 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 248 return; 249 case scTruncate: { 250 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 251 const SCEV *Op = Trunc->getOperand(); 252 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 253 << *Trunc->getType() << ")"; 254 return; 255 } 256 case scZeroExtend: { 257 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 258 const SCEV *Op = ZExt->getOperand(); 259 OS << "(zext " << *Op->getType() << " " << *Op << " to " 260 << *ZExt->getType() << ")"; 261 return; 262 } 263 case scSignExtend: { 264 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 265 const SCEV *Op = SExt->getOperand(); 266 OS << "(sext " << *Op->getType() << " " << *Op << " to " 267 << *SExt->getType() << ")"; 268 return; 269 } 270 case scAddRecExpr: { 271 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 272 OS << "{" << *AR->getOperand(0); 273 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 274 OS << ",+," << *AR->getOperand(i); 275 OS << "}<"; 276 if (AR->hasNoUnsignedWrap()) 277 OS << "nuw><"; 278 if (AR->hasNoSignedWrap()) 279 OS << "nsw><"; 280 if (AR->hasNoSelfWrap() && 281 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 282 OS << "nw><"; 283 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 284 OS << ">"; 285 return; 286 } 287 case scAddExpr: 288 case scMulExpr: 289 case scUMaxExpr: 290 case scSMaxExpr: 291 case scUMinExpr: 292 case scSMinExpr: { 293 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 294 const char *OpStr = nullptr; 295 switch (NAry->getSCEVType()) { 296 case scAddExpr: OpStr = " + "; break; 297 case scMulExpr: OpStr = " * "; break; 298 case scUMaxExpr: OpStr = " umax "; break; 299 case scSMaxExpr: OpStr = " smax "; break; 300 case scUMinExpr: 301 OpStr = " umin "; 302 break; 303 case scSMinExpr: 304 OpStr = " smin "; 305 break; 306 } 307 OS << "("; 308 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 309 I != E; ++I) { 310 OS << **I; 311 if (std::next(I) != E) 312 OS << OpStr; 313 } 314 OS << ")"; 315 switch (NAry->getSCEVType()) { 316 case scAddExpr: 317 case scMulExpr: 318 if (NAry->hasNoUnsignedWrap()) 319 OS << "<nuw>"; 320 if (NAry->hasNoSignedWrap()) 321 OS << "<nsw>"; 322 } 323 return; 324 } 325 case scUDivExpr: { 326 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 327 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 328 return; 329 } 330 case scUnknown: { 331 const SCEVUnknown *U = cast<SCEVUnknown>(this); 332 Type *AllocTy; 333 if (U->isSizeOf(AllocTy)) { 334 OS << "sizeof(" << *AllocTy << ")"; 335 return; 336 } 337 if (U->isAlignOf(AllocTy)) { 338 OS << "alignof(" << *AllocTy << ")"; 339 return; 340 } 341 342 Type *CTy; 343 Constant *FieldNo; 344 if (U->isOffsetOf(CTy, FieldNo)) { 345 OS << "offsetof(" << *CTy << ", "; 346 FieldNo->printAsOperand(OS, false); 347 OS << ")"; 348 return; 349 } 350 351 // Otherwise just print it normally. 352 U->getValue()->printAsOperand(OS, false); 353 return; 354 } 355 case scCouldNotCompute: 356 OS << "***COULDNOTCOMPUTE***"; 357 return; 358 } 359 llvm_unreachable("Unknown SCEV kind!"); 360 } 361 362 Type *SCEV::getType() const { 363 switch (static_cast<SCEVTypes>(getSCEVType())) { 364 case scConstant: 365 return cast<SCEVConstant>(this)->getType(); 366 case scTruncate: 367 case scZeroExtend: 368 case scSignExtend: 369 return cast<SCEVCastExpr>(this)->getType(); 370 case scAddRecExpr: 371 case scMulExpr: 372 case scUMaxExpr: 373 case scSMaxExpr: 374 case scUMinExpr: 375 case scSMinExpr: 376 return cast<SCEVNAryExpr>(this)->getType(); 377 case scAddExpr: 378 return cast<SCEVAddExpr>(this)->getType(); 379 case scUDivExpr: 380 return cast<SCEVUDivExpr>(this)->getType(); 381 case scUnknown: 382 return cast<SCEVUnknown>(this)->getType(); 383 case scCouldNotCompute: 384 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 385 } 386 llvm_unreachable("Unknown SCEV kind!"); 387 } 388 389 bool SCEV::isZero() const { 390 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 391 return SC->getValue()->isZero(); 392 return false; 393 } 394 395 bool SCEV::isOne() const { 396 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 397 return SC->getValue()->isOne(); 398 return false; 399 } 400 401 bool SCEV::isAllOnesValue() const { 402 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 403 return SC->getValue()->isMinusOne(); 404 return false; 405 } 406 407 bool SCEV::isNonConstantNegative() const { 408 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 409 if (!Mul) return false; 410 411 // If there is a constant factor, it will be first. 412 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 413 if (!SC) return false; 414 415 // Return true if the value is negative, this matches things like (-42 * V). 416 return SC->getAPInt().isNegative(); 417 } 418 419 SCEVCouldNotCompute::SCEVCouldNotCompute() : 420 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 421 422 bool SCEVCouldNotCompute::classof(const SCEV *S) { 423 return S->getSCEVType() == scCouldNotCompute; 424 } 425 426 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 427 FoldingSetNodeID ID; 428 ID.AddInteger(scConstant); 429 ID.AddPointer(V); 430 void *IP = nullptr; 431 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 432 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 433 UniqueSCEVs.InsertNode(S, IP); 434 return S; 435 } 436 437 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 438 return getConstant(ConstantInt::get(getContext(), Val)); 439 } 440 441 const SCEV * 442 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 443 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 444 return getConstant(ConstantInt::get(ITy, V, isSigned)); 445 } 446 447 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, 448 unsigned SCEVTy, const SCEV *op, Type *ty) 449 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {} 450 451 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, 452 const SCEV *op, Type *ty) 453 : SCEVCastExpr(ID, scTruncate, op, ty) { 454 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 455 "Cannot truncate non-integer value!"); 456 } 457 458 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 459 const SCEV *op, Type *ty) 460 : SCEVCastExpr(ID, scZeroExtend, op, ty) { 461 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 462 "Cannot zero extend non-integer value!"); 463 } 464 465 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 466 const SCEV *op, Type *ty) 467 : SCEVCastExpr(ID, scSignExtend, op, ty) { 468 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 469 "Cannot sign extend non-integer value!"); 470 } 471 472 void SCEVUnknown::deleted() { 473 // Clear this SCEVUnknown from various maps. 474 SE->forgetMemoizedResults(this); 475 476 // Remove this SCEVUnknown from the uniquing map. 477 SE->UniqueSCEVs.RemoveNode(this); 478 479 // Release the value. 480 setValPtr(nullptr); 481 } 482 483 void SCEVUnknown::allUsesReplacedWith(Value *New) { 484 // Remove this SCEVUnknown from the uniquing map. 485 SE->UniqueSCEVs.RemoveNode(this); 486 487 // Update this SCEVUnknown to point to the new value. This is needed 488 // because there may still be outstanding SCEVs which still point to 489 // this SCEVUnknown. 490 setValPtr(New); 491 } 492 493 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 494 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 495 if (VCE->getOpcode() == Instruction::PtrToInt) 496 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 497 if (CE->getOpcode() == Instruction::GetElementPtr && 498 CE->getOperand(0)->isNullValue() && 499 CE->getNumOperands() == 2) 500 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 501 if (CI->isOne()) { 502 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 503 ->getElementType(); 504 return true; 505 } 506 507 return false; 508 } 509 510 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 511 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 512 if (VCE->getOpcode() == Instruction::PtrToInt) 513 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 514 if (CE->getOpcode() == Instruction::GetElementPtr && 515 CE->getOperand(0)->isNullValue()) { 516 Type *Ty = 517 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 518 if (StructType *STy = dyn_cast<StructType>(Ty)) 519 if (!STy->isPacked() && 520 CE->getNumOperands() == 3 && 521 CE->getOperand(1)->isNullValue()) { 522 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 523 if (CI->isOne() && 524 STy->getNumElements() == 2 && 525 STy->getElementType(0)->isIntegerTy(1)) { 526 AllocTy = STy->getElementType(1); 527 return true; 528 } 529 } 530 } 531 532 return false; 533 } 534 535 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 536 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 537 if (VCE->getOpcode() == Instruction::PtrToInt) 538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 539 if (CE->getOpcode() == Instruction::GetElementPtr && 540 CE->getNumOperands() == 3 && 541 CE->getOperand(0)->isNullValue() && 542 CE->getOperand(1)->isNullValue()) { 543 Type *Ty = 544 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 545 // Ignore vector types here so that ScalarEvolutionExpander doesn't 546 // emit getelementptrs that index into vectors. 547 if (Ty->isStructTy() || Ty->isArrayTy()) { 548 CTy = Ty; 549 FieldNo = CE->getOperand(2); 550 return true; 551 } 552 } 553 554 return false; 555 } 556 557 //===----------------------------------------------------------------------===// 558 // SCEV Utilities 559 //===----------------------------------------------------------------------===// 560 561 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 562 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 563 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 564 /// have been previously deemed to be "equally complex" by this routine. It is 565 /// intended to avoid exponential time complexity in cases like: 566 /// 567 /// %a = f(%x, %y) 568 /// %b = f(%a, %a) 569 /// %c = f(%b, %b) 570 /// 571 /// %d = f(%x, %y) 572 /// %e = f(%d, %d) 573 /// %f = f(%e, %e) 574 /// 575 /// CompareValueComplexity(%f, %c) 576 /// 577 /// Since we do not continue running this routine on expression trees once we 578 /// have seen unequal values, there is no need to track them in the cache. 579 static int 580 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 581 const LoopInfo *const LI, Value *LV, Value *RV, 582 unsigned Depth) { 583 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 584 return 0; 585 586 // Order pointer values after integer values. This helps SCEVExpander form 587 // GEPs. 588 bool LIsPointer = LV->getType()->isPointerTy(), 589 RIsPointer = RV->getType()->isPointerTy(); 590 if (LIsPointer != RIsPointer) 591 return (int)LIsPointer - (int)RIsPointer; 592 593 // Compare getValueID values. 594 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 595 if (LID != RID) 596 return (int)LID - (int)RID; 597 598 // Sort arguments by their position. 599 if (const auto *LA = dyn_cast<Argument>(LV)) { 600 const auto *RA = cast<Argument>(RV); 601 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 602 return (int)LArgNo - (int)RArgNo; 603 } 604 605 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 606 const auto *RGV = cast<GlobalValue>(RV); 607 608 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 609 auto LT = GV->getLinkage(); 610 return !(GlobalValue::isPrivateLinkage(LT) || 611 GlobalValue::isInternalLinkage(LT)); 612 }; 613 614 // Use the names to distinguish the two values, but only if the 615 // names are semantically important. 616 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 617 return LGV->getName().compare(RGV->getName()); 618 } 619 620 // For instructions, compare their loop depth, and their operand count. This 621 // is pretty loose. 622 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 623 const auto *RInst = cast<Instruction>(RV); 624 625 // Compare loop depths. 626 const BasicBlock *LParent = LInst->getParent(), 627 *RParent = RInst->getParent(); 628 if (LParent != RParent) { 629 unsigned LDepth = LI->getLoopDepth(LParent), 630 RDepth = LI->getLoopDepth(RParent); 631 if (LDepth != RDepth) 632 return (int)LDepth - (int)RDepth; 633 } 634 635 // Compare the number of operands. 636 unsigned LNumOps = LInst->getNumOperands(), 637 RNumOps = RInst->getNumOperands(); 638 if (LNumOps != RNumOps) 639 return (int)LNumOps - (int)RNumOps; 640 641 for (unsigned Idx : seq(0u, LNumOps)) { 642 int Result = 643 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 644 RInst->getOperand(Idx), Depth + 1); 645 if (Result != 0) 646 return Result; 647 } 648 } 649 650 EqCacheValue.unionSets(LV, RV); 651 return 0; 652 } 653 654 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 655 // than RHS, respectively. A three-way result allows recursive comparisons to be 656 // more efficient. 657 static int CompareSCEVComplexity( 658 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 659 EquivalenceClasses<const Value *> &EqCacheValue, 660 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 661 DominatorTree &DT, unsigned Depth = 0) { 662 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 663 if (LHS == RHS) 664 return 0; 665 666 // Primarily, sort the SCEVs by their getSCEVType(). 667 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 668 if (LType != RType) 669 return (int)LType - (int)RType; 670 671 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 672 return 0; 673 // Aside from the getSCEVType() ordering, the particular ordering 674 // isn't very important except that it's beneficial to be consistent, 675 // so that (a + b) and (b + a) don't end up as different expressions. 676 switch (static_cast<SCEVTypes>(LType)) { 677 case scUnknown: { 678 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 679 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 680 681 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 682 RU->getValue(), Depth + 1); 683 if (X == 0) 684 EqCacheSCEV.unionSets(LHS, RHS); 685 return X; 686 } 687 688 case scConstant: { 689 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 690 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 691 692 // Compare constant values. 693 const APInt &LA = LC->getAPInt(); 694 const APInt &RA = RC->getAPInt(); 695 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 696 if (LBitWidth != RBitWidth) 697 return (int)LBitWidth - (int)RBitWidth; 698 return LA.ult(RA) ? -1 : 1; 699 } 700 701 case scAddRecExpr: { 702 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 703 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 704 705 // There is always a dominance between two recs that are used by one SCEV, 706 // so we can safely sort recs by loop header dominance. We require such 707 // order in getAddExpr. 708 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 709 if (LLoop != RLoop) { 710 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 711 assert(LHead != RHead && "Two loops share the same header?"); 712 if (DT.dominates(LHead, RHead)) 713 return 1; 714 else 715 assert(DT.dominates(RHead, LHead) && 716 "No dominance between recurrences used by one SCEV?"); 717 return -1; 718 } 719 720 // Addrec complexity grows with operand count. 721 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 722 if (LNumOps != RNumOps) 723 return (int)LNumOps - (int)RNumOps; 724 725 // Lexicographically compare. 726 for (unsigned i = 0; i != LNumOps; ++i) { 727 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 728 LA->getOperand(i), RA->getOperand(i), DT, 729 Depth + 1); 730 if (X != 0) 731 return X; 732 } 733 EqCacheSCEV.unionSets(LHS, RHS); 734 return 0; 735 } 736 737 case scAddExpr: 738 case scMulExpr: 739 case scSMaxExpr: 740 case scUMaxExpr: 741 case scSMinExpr: 742 case scUMinExpr: { 743 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 744 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 745 746 // Lexicographically compare n-ary expressions. 747 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 748 if (LNumOps != RNumOps) 749 return (int)LNumOps - (int)RNumOps; 750 751 for (unsigned i = 0; i != LNumOps; ++i) { 752 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 753 LC->getOperand(i), RC->getOperand(i), DT, 754 Depth + 1); 755 if (X != 0) 756 return X; 757 } 758 EqCacheSCEV.unionSets(LHS, RHS); 759 return 0; 760 } 761 762 case scUDivExpr: { 763 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 764 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 765 766 // Lexicographically compare udiv expressions. 767 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 768 RC->getLHS(), DT, Depth + 1); 769 if (X != 0) 770 return X; 771 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 772 RC->getRHS(), DT, Depth + 1); 773 if (X == 0) 774 EqCacheSCEV.unionSets(LHS, RHS); 775 return X; 776 } 777 778 case scTruncate: 779 case scZeroExtend: 780 case scSignExtend: { 781 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 782 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 783 784 // Compare cast expressions by operand. 785 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 786 LC->getOperand(), RC->getOperand(), DT, 787 Depth + 1); 788 if (X == 0) 789 EqCacheSCEV.unionSets(LHS, RHS); 790 return X; 791 } 792 793 case scCouldNotCompute: 794 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 795 } 796 llvm_unreachable("Unknown SCEV kind!"); 797 } 798 799 /// Given a list of SCEV objects, order them by their complexity, and group 800 /// objects of the same complexity together by value. When this routine is 801 /// finished, we know that any duplicates in the vector are consecutive and that 802 /// complexity is monotonically increasing. 803 /// 804 /// Note that we go take special precautions to ensure that we get deterministic 805 /// results from this routine. In other words, we don't want the results of 806 /// this to depend on where the addresses of various SCEV objects happened to 807 /// land in memory. 808 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 809 LoopInfo *LI, DominatorTree &DT) { 810 if (Ops.size() < 2) return; // Noop 811 812 EquivalenceClasses<const SCEV *> EqCacheSCEV; 813 EquivalenceClasses<const Value *> EqCacheValue; 814 if (Ops.size() == 2) { 815 // This is the common case, which also happens to be trivially simple. 816 // Special case it. 817 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 818 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 819 std::swap(LHS, RHS); 820 return; 821 } 822 823 // Do the rough sort by complexity. 824 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 825 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 826 0; 827 }); 828 829 // Now that we are sorted by complexity, group elements of the same 830 // complexity. Note that this is, at worst, N^2, but the vector is likely to 831 // be extremely short in practice. Note that we take this approach because we 832 // do not want to depend on the addresses of the objects we are grouping. 833 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 834 const SCEV *S = Ops[i]; 835 unsigned Complexity = S->getSCEVType(); 836 837 // If there are any objects of the same complexity and same value as this 838 // one, group them. 839 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 840 if (Ops[j] == S) { // Found a duplicate. 841 // Move it to immediately after i'th element. 842 std::swap(Ops[i+1], Ops[j]); 843 ++i; // no need to rescan it. 844 if (i == e-2) return; // Done! 845 } 846 } 847 } 848 } 849 850 // Returns the size of the SCEV S. 851 static inline int sizeOfSCEV(const SCEV *S) { 852 struct FindSCEVSize { 853 int Size = 0; 854 855 FindSCEVSize() = default; 856 857 bool follow(const SCEV *S) { 858 ++Size; 859 // Keep looking at all operands of S. 860 return true; 861 } 862 863 bool isDone() const { 864 return false; 865 } 866 }; 867 868 FindSCEVSize F; 869 SCEVTraversal<FindSCEVSize> ST(F); 870 ST.visitAll(S); 871 return F.Size; 872 } 873 874 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 875 /// least HugeExprThreshold nodes). 876 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 877 return any_of(Ops, [](const SCEV *S) { 878 return S->getExpressionSize() >= HugeExprThreshold; 879 }); 880 } 881 882 namespace { 883 884 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> { 885 public: 886 // Computes the Quotient and Remainder of the division of Numerator by 887 // Denominator. 888 static void divide(ScalarEvolution &SE, const SCEV *Numerator, 889 const SCEV *Denominator, const SCEV **Quotient, 890 const SCEV **Remainder) { 891 assert(Numerator && Denominator && "Uninitialized SCEV"); 892 893 SCEVDivision D(SE, Numerator, Denominator); 894 895 // Check for the trivial case here to avoid having to check for it in the 896 // rest of the code. 897 if (Numerator == Denominator) { 898 *Quotient = D.One; 899 *Remainder = D.Zero; 900 return; 901 } 902 903 if (Numerator->isZero()) { 904 *Quotient = D.Zero; 905 *Remainder = D.Zero; 906 return; 907 } 908 909 // A simple case when N/1. The quotient is N. 910 if (Denominator->isOne()) { 911 *Quotient = Numerator; 912 *Remainder = D.Zero; 913 return; 914 } 915 916 // Split the Denominator when it is a product. 917 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) { 918 const SCEV *Q, *R; 919 *Quotient = Numerator; 920 for (const SCEV *Op : T->operands()) { 921 divide(SE, *Quotient, Op, &Q, &R); 922 *Quotient = Q; 923 924 // Bail out when the Numerator is not divisible by one of the terms of 925 // the Denominator. 926 if (!R->isZero()) { 927 *Quotient = D.Zero; 928 *Remainder = Numerator; 929 return; 930 } 931 } 932 *Remainder = D.Zero; 933 return; 934 } 935 936 D.visit(Numerator); 937 *Quotient = D.Quotient; 938 *Remainder = D.Remainder; 939 } 940 941 // Except in the trivial case described above, we do not know how to divide 942 // Expr by Denominator for the following functions with empty implementation. 943 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {} 944 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {} 945 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {} 946 void visitUDivExpr(const SCEVUDivExpr *Numerator) {} 947 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {} 948 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {} 949 void visitSMinExpr(const SCEVSMinExpr *Numerator) {} 950 void visitUMinExpr(const SCEVUMinExpr *Numerator) {} 951 void visitUnknown(const SCEVUnknown *Numerator) {} 952 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {} 953 954 void visitConstant(const SCEVConstant *Numerator) { 955 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) { 956 APInt NumeratorVal = Numerator->getAPInt(); 957 APInt DenominatorVal = D->getAPInt(); 958 uint32_t NumeratorBW = NumeratorVal.getBitWidth(); 959 uint32_t DenominatorBW = DenominatorVal.getBitWidth(); 960 961 if (NumeratorBW > DenominatorBW) 962 DenominatorVal = DenominatorVal.sext(NumeratorBW); 963 else if (NumeratorBW < DenominatorBW) 964 NumeratorVal = NumeratorVal.sext(DenominatorBW); 965 966 APInt QuotientVal(NumeratorVal.getBitWidth(), 0); 967 APInt RemainderVal(NumeratorVal.getBitWidth(), 0); 968 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal); 969 Quotient = SE.getConstant(QuotientVal); 970 Remainder = SE.getConstant(RemainderVal); 971 return; 972 } 973 } 974 975 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) { 976 const SCEV *StartQ, *StartR, *StepQ, *StepR; 977 if (!Numerator->isAffine()) 978 return cannotDivide(Numerator); 979 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR); 980 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR); 981 // Bail out if the types do not match. 982 Type *Ty = Denominator->getType(); 983 if (Ty != StartQ->getType() || Ty != StartR->getType() || 984 Ty != StepQ->getType() || Ty != StepR->getType()) 985 return cannotDivide(Numerator); 986 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(), 987 Numerator->getNoWrapFlags()); 988 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(), 989 Numerator->getNoWrapFlags()); 990 } 991 992 void visitAddExpr(const SCEVAddExpr *Numerator) { 993 SmallVector<const SCEV *, 2> Qs, Rs; 994 Type *Ty = Denominator->getType(); 995 996 for (const SCEV *Op : Numerator->operands()) { 997 const SCEV *Q, *R; 998 divide(SE, Op, Denominator, &Q, &R); 999 1000 // Bail out if types do not match. 1001 if (Ty != Q->getType() || Ty != R->getType()) 1002 return cannotDivide(Numerator); 1003 1004 Qs.push_back(Q); 1005 Rs.push_back(R); 1006 } 1007 1008 if (Qs.size() == 1) { 1009 Quotient = Qs[0]; 1010 Remainder = Rs[0]; 1011 return; 1012 } 1013 1014 Quotient = SE.getAddExpr(Qs); 1015 Remainder = SE.getAddExpr(Rs); 1016 } 1017 1018 void visitMulExpr(const SCEVMulExpr *Numerator) { 1019 SmallVector<const SCEV *, 2> Qs; 1020 Type *Ty = Denominator->getType(); 1021 1022 bool FoundDenominatorTerm = false; 1023 for (const SCEV *Op : Numerator->operands()) { 1024 // Bail out if types do not match. 1025 if (Ty != Op->getType()) 1026 return cannotDivide(Numerator); 1027 1028 if (FoundDenominatorTerm) { 1029 Qs.push_back(Op); 1030 continue; 1031 } 1032 1033 // Check whether Denominator divides one of the product operands. 1034 const SCEV *Q, *R; 1035 divide(SE, Op, Denominator, &Q, &R); 1036 if (!R->isZero()) { 1037 Qs.push_back(Op); 1038 continue; 1039 } 1040 1041 // Bail out if types do not match. 1042 if (Ty != Q->getType()) 1043 return cannotDivide(Numerator); 1044 1045 FoundDenominatorTerm = true; 1046 Qs.push_back(Q); 1047 } 1048 1049 if (FoundDenominatorTerm) { 1050 Remainder = Zero; 1051 if (Qs.size() == 1) 1052 Quotient = Qs[0]; 1053 else 1054 Quotient = SE.getMulExpr(Qs); 1055 return; 1056 } 1057 1058 if (!isa<SCEVUnknown>(Denominator)) 1059 return cannotDivide(Numerator); 1060 1061 // The Remainder is obtained by replacing Denominator by 0 in Numerator. 1062 ValueToValueMap RewriteMap; 1063 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1064 cast<SCEVConstant>(Zero)->getValue(); 1065 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1066 1067 if (Remainder->isZero()) { 1068 // The Quotient is obtained by replacing Denominator by 1 in Numerator. 1069 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] = 1070 cast<SCEVConstant>(One)->getValue(); 1071 Quotient = 1072 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true); 1073 return; 1074 } 1075 1076 // Quotient is (Numerator - Remainder) divided by Denominator. 1077 const SCEV *Q, *R; 1078 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder); 1079 // This SCEV does not seem to simplify: fail the division here. 1080 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) 1081 return cannotDivide(Numerator); 1082 divide(SE, Diff, Denominator, &Q, &R); 1083 if (R != Zero) 1084 return cannotDivide(Numerator); 1085 Quotient = Q; 1086 } 1087 1088 private: 1089 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, 1090 const SCEV *Denominator) 1091 : SE(S), Denominator(Denominator) { 1092 Zero = SE.getZero(Denominator->getType()); 1093 One = SE.getOne(Denominator->getType()); 1094 1095 // We generally do not know how to divide Expr by Denominator. We 1096 // initialize the division to a "cannot divide" state to simplify the rest 1097 // of the code. 1098 cannotDivide(Numerator); 1099 } 1100 1101 // Convenience function for giving up on the division. We set the quotient to 1102 // be equal to zero and the remainder to be equal to the numerator. 1103 void cannotDivide(const SCEV *Numerator) { 1104 Quotient = Zero; 1105 Remainder = Numerator; 1106 } 1107 1108 ScalarEvolution &SE; 1109 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One; 1110 }; 1111 1112 } // end anonymous namespace 1113 1114 //===----------------------------------------------------------------------===// 1115 // Simple SCEV method implementations 1116 //===----------------------------------------------------------------------===// 1117 1118 /// Compute BC(It, K). The result has width W. Assume, K > 0. 1119 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 1120 ScalarEvolution &SE, 1121 Type *ResultTy) { 1122 // Handle the simplest case efficiently. 1123 if (K == 1) 1124 return SE.getTruncateOrZeroExtend(It, ResultTy); 1125 1126 // We are using the following formula for BC(It, K): 1127 // 1128 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 1129 // 1130 // Suppose, W is the bitwidth of the return value. We must be prepared for 1131 // overflow. Hence, we must assure that the result of our computation is 1132 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 1133 // safe in modular arithmetic. 1134 // 1135 // However, this code doesn't use exactly that formula; the formula it uses 1136 // is something like the following, where T is the number of factors of 2 in 1137 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 1138 // exponentiation: 1139 // 1140 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 1141 // 1142 // This formula is trivially equivalent to the previous formula. However, 1143 // this formula can be implemented much more efficiently. The trick is that 1144 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 1145 // arithmetic. To do exact division in modular arithmetic, all we have 1146 // to do is multiply by the inverse. Therefore, this step can be done at 1147 // width W. 1148 // 1149 // The next issue is how to safely do the division by 2^T. The way this 1150 // is done is by doing the multiplication step at a width of at least W + T 1151 // bits. This way, the bottom W+T bits of the product are accurate. Then, 1152 // when we perform the division by 2^T (which is equivalent to a right shift 1153 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 1154 // truncated out after the division by 2^T. 1155 // 1156 // In comparison to just directly using the first formula, this technique 1157 // is much more efficient; using the first formula requires W * K bits, 1158 // but this formula less than W + K bits. Also, the first formula requires 1159 // a division step, whereas this formula only requires multiplies and shifts. 1160 // 1161 // It doesn't matter whether the subtraction step is done in the calculation 1162 // width or the input iteration count's width; if the subtraction overflows, 1163 // the result must be zero anyway. We prefer here to do it in the width of 1164 // the induction variable because it helps a lot for certain cases; CodeGen 1165 // isn't smart enough to ignore the overflow, which leads to much less 1166 // efficient code if the width of the subtraction is wider than the native 1167 // register width. 1168 // 1169 // (It's possible to not widen at all by pulling out factors of 2 before 1170 // the multiplication; for example, K=2 can be calculated as 1171 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 1172 // extra arithmetic, so it's not an obvious win, and it gets 1173 // much more complicated for K > 3.) 1174 1175 // Protection from insane SCEVs; this bound is conservative, 1176 // but it probably doesn't matter. 1177 if (K > 1000) 1178 return SE.getCouldNotCompute(); 1179 1180 unsigned W = SE.getTypeSizeInBits(ResultTy); 1181 1182 // Calculate K! / 2^T and T; we divide out the factors of two before 1183 // multiplying for calculating K! / 2^T to avoid overflow. 1184 // Other overflow doesn't matter because we only care about the bottom 1185 // W bits of the result. 1186 APInt OddFactorial(W, 1); 1187 unsigned T = 1; 1188 for (unsigned i = 3; i <= K; ++i) { 1189 APInt Mult(W, i); 1190 unsigned TwoFactors = Mult.countTrailingZeros(); 1191 T += TwoFactors; 1192 Mult.lshrInPlace(TwoFactors); 1193 OddFactorial *= Mult; 1194 } 1195 1196 // We need at least W + T bits for the multiplication step 1197 unsigned CalculationBits = W + T; 1198 1199 // Calculate 2^T, at width T+W. 1200 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 1201 1202 // Calculate the multiplicative inverse of K! / 2^T; 1203 // this multiplication factor will perform the exact division by 1204 // K! / 2^T. 1205 APInt Mod = APInt::getSignedMinValue(W+1); 1206 APInt MultiplyFactor = OddFactorial.zext(W+1); 1207 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 1208 MultiplyFactor = MultiplyFactor.trunc(W); 1209 1210 // Calculate the product, at width T+W 1211 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 1212 CalculationBits); 1213 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 1214 for (unsigned i = 1; i != K; ++i) { 1215 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 1216 Dividend = SE.getMulExpr(Dividend, 1217 SE.getTruncateOrZeroExtend(S, CalculationTy)); 1218 } 1219 1220 // Divide by 2^T 1221 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1222 1223 // Truncate the result, and divide by K! / 2^T. 1224 1225 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1226 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1227 } 1228 1229 /// Return the value of this chain of recurrences at the specified iteration 1230 /// number. We can evaluate this recurrence by multiplying each element in the 1231 /// chain by the binomial coefficient corresponding to it. In other words, we 1232 /// can evaluate {A,+,B,+,C,+,D} as: 1233 /// 1234 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1235 /// 1236 /// where BC(It, k) stands for binomial coefficient. 1237 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1238 ScalarEvolution &SE) const { 1239 const SCEV *Result = getStart(); 1240 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1241 // The computation is correct in the face of overflow provided that the 1242 // multiplication is performed _after_ the evaluation of the binomial 1243 // coefficient. 1244 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1245 if (isa<SCEVCouldNotCompute>(Coeff)) 1246 return Coeff; 1247 1248 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1249 } 1250 return Result; 1251 } 1252 1253 //===----------------------------------------------------------------------===// 1254 // SCEV Expression folder implementations 1255 //===----------------------------------------------------------------------===// 1256 1257 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1258 unsigned Depth) { 1259 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1260 "This is not a truncating conversion!"); 1261 assert(isSCEVable(Ty) && 1262 "This is not a conversion to a SCEVable type!"); 1263 Ty = getEffectiveSCEVType(Ty); 1264 1265 FoldingSetNodeID ID; 1266 ID.AddInteger(scTruncate); 1267 ID.AddPointer(Op); 1268 ID.AddPointer(Ty); 1269 void *IP = nullptr; 1270 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1271 1272 // Fold if the operand is constant. 1273 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1274 return getConstant( 1275 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1276 1277 // trunc(trunc(x)) --> trunc(x) 1278 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1279 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1280 1281 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1282 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1283 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1284 1285 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1286 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1287 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1288 1289 if (Depth > MaxCastDepth) { 1290 SCEV *S = 1291 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1292 UniqueSCEVs.InsertNode(S, IP); 1293 addToLoopUseLists(S); 1294 return S; 1295 } 1296 1297 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1298 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1299 // if after transforming we have at most one truncate, not counting truncates 1300 // that replace other casts. 1301 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1302 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1303 SmallVector<const SCEV *, 4> Operands; 1304 unsigned numTruncs = 0; 1305 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1306 ++i) { 1307 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1308 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S)) 1309 numTruncs++; 1310 Operands.push_back(S); 1311 } 1312 if (numTruncs < 2) { 1313 if (isa<SCEVAddExpr>(Op)) 1314 return getAddExpr(Operands); 1315 else if (isa<SCEVMulExpr>(Op)) 1316 return getMulExpr(Operands); 1317 else 1318 llvm_unreachable("Unexpected SCEV type for Op."); 1319 } 1320 // Although we checked in the beginning that ID is not in the cache, it is 1321 // possible that during recursion and different modification ID was inserted 1322 // into the cache. So if we find it, just return it. 1323 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1324 return S; 1325 } 1326 1327 // If the input value is a chrec scev, truncate the chrec's operands. 1328 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1329 SmallVector<const SCEV *, 4> Operands; 1330 for (const SCEV *Op : AddRec->operands()) 1331 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1332 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1333 } 1334 1335 // The cast wasn't folded; create an explicit cast node. We can reuse 1336 // the existing insert position since if we get here, we won't have 1337 // made any changes which would invalidate it. 1338 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1339 Op, Ty); 1340 UniqueSCEVs.InsertNode(S, IP); 1341 addToLoopUseLists(S); 1342 return S; 1343 } 1344 1345 // Get the limit of a recurrence such that incrementing by Step cannot cause 1346 // signed overflow as long as the value of the recurrence within the 1347 // loop does not exceed this limit before incrementing. 1348 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1349 ICmpInst::Predicate *Pred, 1350 ScalarEvolution *SE) { 1351 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1352 if (SE->isKnownPositive(Step)) { 1353 *Pred = ICmpInst::ICMP_SLT; 1354 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1355 SE->getSignedRangeMax(Step)); 1356 } 1357 if (SE->isKnownNegative(Step)) { 1358 *Pred = ICmpInst::ICMP_SGT; 1359 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1360 SE->getSignedRangeMin(Step)); 1361 } 1362 return nullptr; 1363 } 1364 1365 // Get the limit of a recurrence such that incrementing by Step cannot cause 1366 // unsigned overflow as long as the value of the recurrence within the loop does 1367 // not exceed this limit before incrementing. 1368 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1369 ICmpInst::Predicate *Pred, 1370 ScalarEvolution *SE) { 1371 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1372 *Pred = ICmpInst::ICMP_ULT; 1373 1374 return SE->getConstant(APInt::getMinValue(BitWidth) - 1375 SE->getUnsignedRangeMax(Step)); 1376 } 1377 1378 namespace { 1379 1380 struct ExtendOpTraitsBase { 1381 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1382 unsigned); 1383 }; 1384 1385 // Used to make code generic over signed and unsigned overflow. 1386 template <typename ExtendOp> struct ExtendOpTraits { 1387 // Members present: 1388 // 1389 // static const SCEV::NoWrapFlags WrapType; 1390 // 1391 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1392 // 1393 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1394 // ICmpInst::Predicate *Pred, 1395 // ScalarEvolution *SE); 1396 }; 1397 1398 template <> 1399 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1400 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1401 1402 static const GetExtendExprTy GetExtendExpr; 1403 1404 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1405 ICmpInst::Predicate *Pred, 1406 ScalarEvolution *SE) { 1407 return getSignedOverflowLimitForStep(Step, Pred, SE); 1408 } 1409 }; 1410 1411 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1412 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1413 1414 template <> 1415 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1416 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1417 1418 static const GetExtendExprTy GetExtendExpr; 1419 1420 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1421 ICmpInst::Predicate *Pred, 1422 ScalarEvolution *SE) { 1423 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1424 } 1425 }; 1426 1427 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1428 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1429 1430 } // end anonymous namespace 1431 1432 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1433 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1434 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1435 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1436 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1437 // expression "Step + sext/zext(PreIncAR)" is congruent with 1438 // "sext/zext(PostIncAR)" 1439 template <typename ExtendOpTy> 1440 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1441 ScalarEvolution *SE, unsigned Depth) { 1442 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1443 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1444 1445 const Loop *L = AR->getLoop(); 1446 const SCEV *Start = AR->getStart(); 1447 const SCEV *Step = AR->getStepRecurrence(*SE); 1448 1449 // Check for a simple looking step prior to loop entry. 1450 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1451 if (!SA) 1452 return nullptr; 1453 1454 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1455 // subtraction is expensive. For this purpose, perform a quick and dirty 1456 // difference, by checking for Step in the operand list. 1457 SmallVector<const SCEV *, 4> DiffOps; 1458 for (const SCEV *Op : SA->operands()) 1459 if (Op != Step) 1460 DiffOps.push_back(Op); 1461 1462 if (DiffOps.size() == SA->getNumOperands()) 1463 return nullptr; 1464 1465 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1466 // `Step`: 1467 1468 // 1. NSW/NUW flags on the step increment. 1469 auto PreStartFlags = 1470 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1471 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1472 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1473 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1474 1475 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1476 // "S+X does not sign/unsign-overflow". 1477 // 1478 1479 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1480 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1481 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1482 return PreStart; 1483 1484 // 2. Direct overflow check on the step operation's expression. 1485 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1486 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1487 const SCEV *OperandExtendedStart = 1488 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1489 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1490 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1491 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1492 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1493 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1494 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1495 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1496 } 1497 return PreStart; 1498 } 1499 1500 // 3. Loop precondition. 1501 ICmpInst::Predicate Pred; 1502 const SCEV *OverflowLimit = 1503 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1504 1505 if (OverflowLimit && 1506 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1507 return PreStart; 1508 1509 return nullptr; 1510 } 1511 1512 // Get the normalized zero or sign extended expression for this AddRec's Start. 1513 template <typename ExtendOpTy> 1514 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1515 ScalarEvolution *SE, 1516 unsigned Depth) { 1517 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1518 1519 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1520 if (!PreStart) 1521 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1522 1523 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1524 Depth), 1525 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1526 } 1527 1528 // Try to prove away overflow by looking at "nearby" add recurrences. A 1529 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1530 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1531 // 1532 // Formally: 1533 // 1534 // {S,+,X} == {S-T,+,X} + T 1535 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1536 // 1537 // If ({S-T,+,X} + T) does not overflow ... (1) 1538 // 1539 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1540 // 1541 // If {S-T,+,X} does not overflow ... (2) 1542 // 1543 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1544 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1545 // 1546 // If (S-T)+T does not overflow ... (3) 1547 // 1548 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1549 // == {Ext(S),+,Ext(X)} == LHS 1550 // 1551 // Thus, if (1), (2) and (3) are true for some T, then 1552 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1553 // 1554 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1555 // does not overflow" restricted to the 0th iteration. Therefore we only need 1556 // to check for (1) and (2). 1557 // 1558 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1559 // is `Delta` (defined below). 1560 template <typename ExtendOpTy> 1561 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1562 const SCEV *Step, 1563 const Loop *L) { 1564 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1565 1566 // We restrict `Start` to a constant to prevent SCEV from spending too much 1567 // time here. It is correct (but more expensive) to continue with a 1568 // non-constant `Start` and do a general SCEV subtraction to compute 1569 // `PreStart` below. 1570 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1571 if (!StartC) 1572 return false; 1573 1574 APInt StartAI = StartC->getAPInt(); 1575 1576 for (unsigned Delta : {-2, -1, 1, 2}) { 1577 const SCEV *PreStart = getConstant(StartAI - Delta); 1578 1579 FoldingSetNodeID ID; 1580 ID.AddInteger(scAddRecExpr); 1581 ID.AddPointer(PreStart); 1582 ID.AddPointer(Step); 1583 ID.AddPointer(L); 1584 void *IP = nullptr; 1585 const auto *PreAR = 1586 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1587 1588 // Give up if we don't already have the add recurrence we need because 1589 // actually constructing an add recurrence is relatively expensive. 1590 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1591 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1592 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1593 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1594 DeltaS, &Pred, this); 1595 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1596 return true; 1597 } 1598 } 1599 1600 return false; 1601 } 1602 1603 // Finds an integer D for an expression (C + x + y + ...) such that the top 1604 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1605 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1606 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1607 // the (C + x + y + ...) expression is \p WholeAddExpr. 1608 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1609 const SCEVConstant *ConstantTerm, 1610 const SCEVAddExpr *WholeAddExpr) { 1611 const APInt C = ConstantTerm->getAPInt(); 1612 const unsigned BitWidth = C.getBitWidth(); 1613 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1614 uint32_t TZ = BitWidth; 1615 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1616 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1617 if (TZ) { 1618 // Set D to be as many least significant bits of C as possible while still 1619 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1620 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1621 } 1622 return APInt(BitWidth, 0); 1623 } 1624 1625 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1626 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1627 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1628 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1629 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1630 const APInt &ConstantStart, 1631 const SCEV *Step) { 1632 const unsigned BitWidth = ConstantStart.getBitWidth(); 1633 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1634 if (TZ) 1635 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1636 : ConstantStart; 1637 return APInt(BitWidth, 0); 1638 } 1639 1640 const SCEV * 1641 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1642 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1643 "This is not an extending conversion!"); 1644 assert(isSCEVable(Ty) && 1645 "This is not a conversion to a SCEVable type!"); 1646 Ty = getEffectiveSCEVType(Ty); 1647 1648 // Fold if the operand is constant. 1649 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1650 return getConstant( 1651 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1652 1653 // zext(zext(x)) --> zext(x) 1654 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1655 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1656 1657 // Before doing any expensive analysis, check to see if we've already 1658 // computed a SCEV for this Op and Ty. 1659 FoldingSetNodeID ID; 1660 ID.AddInteger(scZeroExtend); 1661 ID.AddPointer(Op); 1662 ID.AddPointer(Ty); 1663 void *IP = nullptr; 1664 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1665 if (Depth > MaxCastDepth) { 1666 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1667 Op, Ty); 1668 UniqueSCEVs.InsertNode(S, IP); 1669 addToLoopUseLists(S); 1670 return S; 1671 } 1672 1673 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1674 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1675 // It's possible the bits taken off by the truncate were all zero bits. If 1676 // so, we should be able to simplify this further. 1677 const SCEV *X = ST->getOperand(); 1678 ConstantRange CR = getUnsignedRange(X); 1679 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1680 unsigned NewBits = getTypeSizeInBits(Ty); 1681 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1682 CR.zextOrTrunc(NewBits))) 1683 return getTruncateOrZeroExtend(X, Ty, Depth); 1684 } 1685 1686 // If the input value is a chrec scev, and we can prove that the value 1687 // did not overflow the old, smaller, value, we can zero extend all of the 1688 // operands (often constants). This allows analysis of something like 1689 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1690 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1691 if (AR->isAffine()) { 1692 const SCEV *Start = AR->getStart(); 1693 const SCEV *Step = AR->getStepRecurrence(*this); 1694 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1695 const Loop *L = AR->getLoop(); 1696 1697 if (!AR->hasNoUnsignedWrap()) { 1698 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1699 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1700 } 1701 1702 // If we have special knowledge that this addrec won't overflow, 1703 // we don't need to do any further analysis. 1704 if (AR->hasNoUnsignedWrap()) 1705 return getAddRecExpr( 1706 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1707 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1708 1709 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1710 // Note that this serves two purposes: It filters out loops that are 1711 // simply not analyzable, and it covers the case where this code is 1712 // being called from within backedge-taken count analysis, such that 1713 // attempting to ask for the backedge-taken count would likely result 1714 // in infinite recursion. In the later case, the analysis code will 1715 // cope with a conservative value, and it will take care to purge 1716 // that value once it has finished. 1717 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1718 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1719 // Manually compute the final value for AR, checking for 1720 // overflow. 1721 1722 // Check whether the backedge-taken count can be losslessly casted to 1723 // the addrec's type. The count is always unsigned. 1724 const SCEV *CastedMaxBECount = 1725 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1726 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1727 CastedMaxBECount, MaxBECount->getType(), Depth); 1728 if (MaxBECount == RecastedMaxBECount) { 1729 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1730 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1731 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1732 SCEV::FlagAnyWrap, Depth + 1); 1733 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1734 SCEV::FlagAnyWrap, 1735 Depth + 1), 1736 WideTy, Depth + 1); 1737 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1738 const SCEV *WideMaxBECount = 1739 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1740 const SCEV *OperandExtendedAdd = 1741 getAddExpr(WideStart, 1742 getMulExpr(WideMaxBECount, 1743 getZeroExtendExpr(Step, WideTy, Depth + 1), 1744 SCEV::FlagAnyWrap, Depth + 1), 1745 SCEV::FlagAnyWrap, Depth + 1); 1746 if (ZAdd == OperandExtendedAdd) { 1747 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1748 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1749 // Return the expression with the addrec on the outside. 1750 return getAddRecExpr( 1751 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1752 Depth + 1), 1753 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1754 AR->getNoWrapFlags()); 1755 } 1756 // Similar to above, only this time treat the step value as signed. 1757 // This covers loops that count down. 1758 OperandExtendedAdd = 1759 getAddExpr(WideStart, 1760 getMulExpr(WideMaxBECount, 1761 getSignExtendExpr(Step, WideTy, Depth + 1), 1762 SCEV::FlagAnyWrap, Depth + 1), 1763 SCEV::FlagAnyWrap, Depth + 1); 1764 if (ZAdd == OperandExtendedAdd) { 1765 // Cache knowledge of AR NW, which is propagated to this AddRec. 1766 // Negative step causes unsigned wrap, but it still can't self-wrap. 1767 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1768 // Return the expression with the addrec on the outside. 1769 return getAddRecExpr( 1770 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1771 Depth + 1), 1772 getSignExtendExpr(Step, Ty, Depth + 1), L, 1773 AR->getNoWrapFlags()); 1774 } 1775 } 1776 } 1777 1778 // Normally, in the cases we can prove no-overflow via a 1779 // backedge guarding condition, we can also compute a backedge 1780 // taken count for the loop. The exceptions are assumptions and 1781 // guards present in the loop -- SCEV is not great at exploiting 1782 // these to compute max backedge taken counts, but can still use 1783 // these to prove lack of overflow. Use this fact to avoid 1784 // doing extra work that may not pay off. 1785 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1786 !AC.assumptions().empty()) { 1787 // If the backedge is guarded by a comparison with the pre-inc 1788 // value the addrec is safe. Also, if the entry is guarded by 1789 // a comparison with the start value and the backedge is 1790 // guarded by a comparison with the post-inc value, the addrec 1791 // is safe. 1792 if (isKnownPositive(Step)) { 1793 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1794 getUnsignedRangeMax(Step)); 1795 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1796 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1797 // Cache knowledge of AR NUW, which is propagated to this 1798 // AddRec. 1799 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1800 // Return the expression with the addrec on the outside. 1801 return getAddRecExpr( 1802 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1803 Depth + 1), 1804 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1805 AR->getNoWrapFlags()); 1806 } 1807 } else if (isKnownNegative(Step)) { 1808 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1809 getSignedRangeMin(Step)); 1810 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1811 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1812 // Cache knowledge of AR NW, which is propagated to this 1813 // AddRec. Negative step causes unsigned wrap, but it 1814 // still can't self-wrap. 1815 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1816 // Return the expression with the addrec on the outside. 1817 return getAddRecExpr( 1818 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1819 Depth + 1), 1820 getSignExtendExpr(Step, Ty, Depth + 1), L, 1821 AR->getNoWrapFlags()); 1822 } 1823 } 1824 } 1825 1826 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1827 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1828 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1829 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1830 const APInt &C = SC->getAPInt(); 1831 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1832 if (D != 0) { 1833 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1834 const SCEV *SResidual = 1835 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1836 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1837 return getAddExpr(SZExtD, SZExtR, 1838 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1839 Depth + 1); 1840 } 1841 } 1842 1843 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1844 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1845 return getAddRecExpr( 1846 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1847 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1848 } 1849 } 1850 1851 // zext(A % B) --> zext(A) % zext(B) 1852 { 1853 const SCEV *LHS; 1854 const SCEV *RHS; 1855 if (matchURem(Op, LHS, RHS)) 1856 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1857 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1858 } 1859 1860 // zext(A / B) --> zext(A) / zext(B). 1861 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1862 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1863 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1864 1865 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1866 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1867 if (SA->hasNoUnsignedWrap()) { 1868 // If the addition does not unsign overflow then we can, by definition, 1869 // commute the zero extension with the addition operation. 1870 SmallVector<const SCEV *, 4> Ops; 1871 for (const auto *Op : SA->operands()) 1872 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1873 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1874 } 1875 1876 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1877 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1878 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1879 // 1880 // Often address arithmetics contain expressions like 1881 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1882 // This transformation is useful while proving that such expressions are 1883 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1884 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1885 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1886 if (D != 0) { 1887 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1888 const SCEV *SResidual = 1889 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1890 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1891 return getAddExpr(SZExtD, SZExtR, 1892 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1893 Depth + 1); 1894 } 1895 } 1896 } 1897 1898 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1899 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1900 if (SM->hasNoUnsignedWrap()) { 1901 // If the multiply does not unsign overflow then we can, by definition, 1902 // commute the zero extension with the multiply operation. 1903 SmallVector<const SCEV *, 4> Ops; 1904 for (const auto *Op : SM->operands()) 1905 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1906 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1907 } 1908 1909 // zext(2^K * (trunc X to iN)) to iM -> 1910 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1911 // 1912 // Proof: 1913 // 1914 // zext(2^K * (trunc X to iN)) to iM 1915 // = zext((trunc X to iN) << K) to iM 1916 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1917 // (because shl removes the top K bits) 1918 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1919 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1920 // 1921 if (SM->getNumOperands() == 2) 1922 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1923 if (MulLHS->getAPInt().isPowerOf2()) 1924 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1925 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1926 MulLHS->getAPInt().logBase2(); 1927 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1928 return getMulExpr( 1929 getZeroExtendExpr(MulLHS, Ty), 1930 getZeroExtendExpr( 1931 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1932 SCEV::FlagNUW, Depth + 1); 1933 } 1934 } 1935 1936 // The cast wasn't folded; create an explicit cast node. 1937 // Recompute the insert position, as it may have been invalidated. 1938 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1939 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1940 Op, Ty); 1941 UniqueSCEVs.InsertNode(S, IP); 1942 addToLoopUseLists(S); 1943 return S; 1944 } 1945 1946 const SCEV * 1947 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1948 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1949 "This is not an extending conversion!"); 1950 assert(isSCEVable(Ty) && 1951 "This is not a conversion to a SCEVable type!"); 1952 Ty = getEffectiveSCEVType(Ty); 1953 1954 // Fold if the operand is constant. 1955 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1956 return getConstant( 1957 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1958 1959 // sext(sext(x)) --> sext(x) 1960 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1961 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1962 1963 // sext(zext(x)) --> zext(x) 1964 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1965 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1966 1967 // Before doing any expensive analysis, check to see if we've already 1968 // computed a SCEV for this Op and Ty. 1969 FoldingSetNodeID ID; 1970 ID.AddInteger(scSignExtend); 1971 ID.AddPointer(Op); 1972 ID.AddPointer(Ty); 1973 void *IP = nullptr; 1974 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1975 // Limit recursion depth. 1976 if (Depth > MaxCastDepth) { 1977 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1978 Op, Ty); 1979 UniqueSCEVs.InsertNode(S, IP); 1980 addToLoopUseLists(S); 1981 return S; 1982 } 1983 1984 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1985 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1986 // It's possible the bits taken off by the truncate were all sign bits. If 1987 // so, we should be able to simplify this further. 1988 const SCEV *X = ST->getOperand(); 1989 ConstantRange CR = getSignedRange(X); 1990 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1991 unsigned NewBits = getTypeSizeInBits(Ty); 1992 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1993 CR.sextOrTrunc(NewBits))) 1994 return getTruncateOrSignExtend(X, Ty, Depth); 1995 } 1996 1997 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1998 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1999 if (SA->hasNoSignedWrap()) { 2000 // If the addition does not sign overflow then we can, by definition, 2001 // commute the sign extension with the addition operation. 2002 SmallVector<const SCEV *, 4> Ops; 2003 for (const auto *Op : SA->operands()) 2004 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 2005 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 2006 } 2007 2008 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 2009 // if D + (C - D + x + y + ...) could be proven to not signed wrap 2010 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 2011 // 2012 // For instance, this will bring two seemingly different expressions: 2013 // 1 + sext(5 + 20 * %x + 24 * %y) and 2014 // sext(6 + 20 * %x + 24 * %y) 2015 // to the same form: 2016 // 2 + sext(4 + 20 * %x + 24 * %y) 2017 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 2018 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 2019 if (D != 0) { 2020 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2021 const SCEV *SResidual = 2022 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 2023 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2024 return getAddExpr(SSExtD, SSExtR, 2025 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2026 Depth + 1); 2027 } 2028 } 2029 } 2030 // If the input value is a chrec scev, and we can prove that the value 2031 // did not overflow the old, smaller, value, we can sign extend all of the 2032 // operands (often constants). This allows analysis of something like 2033 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 2034 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 2035 if (AR->isAffine()) { 2036 const SCEV *Start = AR->getStart(); 2037 const SCEV *Step = AR->getStepRecurrence(*this); 2038 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 2039 const Loop *L = AR->getLoop(); 2040 2041 if (!AR->hasNoSignedWrap()) { 2042 auto NewFlags = proveNoWrapViaConstantRanges(AR); 2043 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 2044 } 2045 2046 // If we have special knowledge that this addrec won't overflow, 2047 // we don't need to do any further analysis. 2048 if (AR->hasNoSignedWrap()) 2049 return getAddRecExpr( 2050 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2051 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 2052 2053 // Check whether the backedge-taken count is SCEVCouldNotCompute. 2054 // Note that this serves two purposes: It filters out loops that are 2055 // simply not analyzable, and it covers the case where this code is 2056 // being called from within backedge-taken count analysis, such that 2057 // attempting to ask for the backedge-taken count would likely result 2058 // in infinite recursion. In the later case, the analysis code will 2059 // cope with a conservative value, and it will take care to purge 2060 // that value once it has finished. 2061 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 2062 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 2063 // Manually compute the final value for AR, checking for 2064 // overflow. 2065 2066 // Check whether the backedge-taken count can be losslessly casted to 2067 // the addrec's type. The count is always unsigned. 2068 const SCEV *CastedMaxBECount = 2069 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 2070 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 2071 CastedMaxBECount, MaxBECount->getType(), Depth); 2072 if (MaxBECount == RecastedMaxBECount) { 2073 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 2074 // Check whether Start+Step*MaxBECount has no signed overflow. 2075 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 2076 SCEV::FlagAnyWrap, Depth + 1); 2077 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 2078 SCEV::FlagAnyWrap, 2079 Depth + 1), 2080 WideTy, Depth + 1); 2081 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 2082 const SCEV *WideMaxBECount = 2083 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 2084 const SCEV *OperandExtendedAdd = 2085 getAddExpr(WideStart, 2086 getMulExpr(WideMaxBECount, 2087 getSignExtendExpr(Step, WideTy, Depth + 1), 2088 SCEV::FlagAnyWrap, Depth + 1), 2089 SCEV::FlagAnyWrap, Depth + 1); 2090 if (SAdd == OperandExtendedAdd) { 2091 // Cache knowledge of AR NSW, which is propagated to this AddRec. 2092 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2093 // Return the expression with the addrec on the outside. 2094 return getAddRecExpr( 2095 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2096 Depth + 1), 2097 getSignExtendExpr(Step, Ty, Depth + 1), L, 2098 AR->getNoWrapFlags()); 2099 } 2100 // Similar to above, only this time treat the step value as unsigned. 2101 // This covers loops that count up with an unsigned step. 2102 OperandExtendedAdd = 2103 getAddExpr(WideStart, 2104 getMulExpr(WideMaxBECount, 2105 getZeroExtendExpr(Step, WideTy, Depth + 1), 2106 SCEV::FlagAnyWrap, Depth + 1), 2107 SCEV::FlagAnyWrap, Depth + 1); 2108 if (SAdd == OperandExtendedAdd) { 2109 // If AR wraps around then 2110 // 2111 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2112 // => SAdd != OperandExtendedAdd 2113 // 2114 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2115 // (SAdd == OperandExtendedAdd => AR is NW) 2116 2117 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2118 2119 // Return the expression with the addrec on the outside. 2120 return getAddRecExpr( 2121 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2122 Depth + 1), 2123 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2124 AR->getNoWrapFlags()); 2125 } 2126 } 2127 } 2128 2129 // Normally, in the cases we can prove no-overflow via a 2130 // backedge guarding condition, we can also compute a backedge 2131 // taken count for the loop. The exceptions are assumptions and 2132 // guards present in the loop -- SCEV is not great at exploiting 2133 // these to compute max backedge taken counts, but can still use 2134 // these to prove lack of overflow. Use this fact to avoid 2135 // doing extra work that may not pay off. 2136 2137 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2138 !AC.assumptions().empty()) { 2139 // If the backedge is guarded by a comparison with the pre-inc 2140 // value the addrec is safe. Also, if the entry is guarded by 2141 // a comparison with the start value and the backedge is 2142 // guarded by a comparison with the post-inc value, the addrec 2143 // is safe. 2144 ICmpInst::Predicate Pred; 2145 const SCEV *OverflowLimit = 2146 getSignedOverflowLimitForStep(Step, &Pred, this); 2147 if (OverflowLimit && 2148 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2149 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2150 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2151 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2152 return getAddRecExpr( 2153 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2154 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2155 } 2156 } 2157 2158 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2159 // if D + (C - D + Step * n) could be proven to not signed wrap 2160 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2161 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2162 const APInt &C = SC->getAPInt(); 2163 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2164 if (D != 0) { 2165 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2166 const SCEV *SResidual = 2167 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2168 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2169 return getAddExpr(SSExtD, SSExtR, 2170 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2171 Depth + 1); 2172 } 2173 } 2174 2175 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2176 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2177 return getAddRecExpr( 2178 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2179 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2180 } 2181 } 2182 2183 // If the input value is provably positive and we could not simplify 2184 // away the sext build a zext instead. 2185 if (isKnownNonNegative(Op)) 2186 return getZeroExtendExpr(Op, Ty, Depth + 1); 2187 2188 // The cast wasn't folded; create an explicit cast node. 2189 // Recompute the insert position, as it may have been invalidated. 2190 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2191 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2192 Op, Ty); 2193 UniqueSCEVs.InsertNode(S, IP); 2194 addToLoopUseLists(S); 2195 return S; 2196 } 2197 2198 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2199 /// unspecified bits out to the given type. 2200 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2201 Type *Ty) { 2202 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2203 "This is not an extending conversion!"); 2204 assert(isSCEVable(Ty) && 2205 "This is not a conversion to a SCEVable type!"); 2206 Ty = getEffectiveSCEVType(Ty); 2207 2208 // Sign-extend negative constants. 2209 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2210 if (SC->getAPInt().isNegative()) 2211 return getSignExtendExpr(Op, Ty); 2212 2213 // Peel off a truncate cast. 2214 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2215 const SCEV *NewOp = T->getOperand(); 2216 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2217 return getAnyExtendExpr(NewOp, Ty); 2218 return getTruncateOrNoop(NewOp, Ty); 2219 } 2220 2221 // Next try a zext cast. If the cast is folded, use it. 2222 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2223 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2224 return ZExt; 2225 2226 // Next try a sext cast. If the cast is folded, use it. 2227 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2228 if (!isa<SCEVSignExtendExpr>(SExt)) 2229 return SExt; 2230 2231 // Force the cast to be folded into the operands of an addrec. 2232 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2233 SmallVector<const SCEV *, 4> Ops; 2234 for (const SCEV *Op : AR->operands()) 2235 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2236 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2237 } 2238 2239 // If the expression is obviously signed, use the sext cast value. 2240 if (isa<SCEVSMaxExpr>(Op)) 2241 return SExt; 2242 2243 // Absent any other information, use the zext cast value. 2244 return ZExt; 2245 } 2246 2247 /// Process the given Ops list, which is a list of operands to be added under 2248 /// the given scale, update the given map. This is a helper function for 2249 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2250 /// that would form an add expression like this: 2251 /// 2252 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2253 /// 2254 /// where A and B are constants, update the map with these values: 2255 /// 2256 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2257 /// 2258 /// and add 13 + A*B*29 to AccumulatedConstant. 2259 /// This will allow getAddRecExpr to produce this: 2260 /// 2261 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2262 /// 2263 /// This form often exposes folding opportunities that are hidden in 2264 /// the original operand list. 2265 /// 2266 /// Return true iff it appears that any interesting folding opportunities 2267 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2268 /// the common case where no interesting opportunities are present, and 2269 /// is also used as a check to avoid infinite recursion. 2270 static bool 2271 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2272 SmallVectorImpl<const SCEV *> &NewOps, 2273 APInt &AccumulatedConstant, 2274 const SCEV *const *Ops, size_t NumOperands, 2275 const APInt &Scale, 2276 ScalarEvolution &SE) { 2277 bool Interesting = false; 2278 2279 // Iterate over the add operands. They are sorted, with constants first. 2280 unsigned i = 0; 2281 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2282 ++i; 2283 // Pull a buried constant out to the outside. 2284 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2285 Interesting = true; 2286 AccumulatedConstant += Scale * C->getAPInt(); 2287 } 2288 2289 // Next comes everything else. We're especially interested in multiplies 2290 // here, but they're in the middle, so just visit the rest with one loop. 2291 for (; i != NumOperands; ++i) { 2292 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2293 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2294 APInt NewScale = 2295 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2296 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2297 // A multiplication of a constant with another add; recurse. 2298 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2299 Interesting |= 2300 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2301 Add->op_begin(), Add->getNumOperands(), 2302 NewScale, SE); 2303 } else { 2304 // A multiplication of a constant with some other value. Update 2305 // the map. 2306 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2307 const SCEV *Key = SE.getMulExpr(MulOps); 2308 auto Pair = M.insert({Key, NewScale}); 2309 if (Pair.second) { 2310 NewOps.push_back(Pair.first->first); 2311 } else { 2312 Pair.first->second += NewScale; 2313 // The map already had an entry for this value, which may indicate 2314 // a folding opportunity. 2315 Interesting = true; 2316 } 2317 } 2318 } else { 2319 // An ordinary operand. Update the map. 2320 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2321 M.insert({Ops[i], Scale}); 2322 if (Pair.second) { 2323 NewOps.push_back(Pair.first->first); 2324 } else { 2325 Pair.first->second += Scale; 2326 // The map already had an entry for this value, which may indicate 2327 // a folding opportunity. 2328 Interesting = true; 2329 } 2330 } 2331 } 2332 2333 return Interesting; 2334 } 2335 2336 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2337 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2338 // can't-overflow flags for the operation if possible. 2339 static SCEV::NoWrapFlags 2340 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2341 const ArrayRef<const SCEV *> Ops, 2342 SCEV::NoWrapFlags Flags) { 2343 using namespace std::placeholders; 2344 2345 using OBO = OverflowingBinaryOperator; 2346 2347 bool CanAnalyze = 2348 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2349 (void)CanAnalyze; 2350 assert(CanAnalyze && "don't call from other places!"); 2351 2352 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2353 SCEV::NoWrapFlags SignOrUnsignWrap = 2354 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2355 2356 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2357 auto IsKnownNonNegative = [&](const SCEV *S) { 2358 return SE->isKnownNonNegative(S); 2359 }; 2360 2361 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2362 Flags = 2363 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2364 2365 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2366 2367 if (SignOrUnsignWrap != SignOrUnsignMask && 2368 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2369 isa<SCEVConstant>(Ops[0])) { 2370 2371 auto Opcode = [&] { 2372 switch (Type) { 2373 case scAddExpr: 2374 return Instruction::Add; 2375 case scMulExpr: 2376 return Instruction::Mul; 2377 default: 2378 llvm_unreachable("Unexpected SCEV op."); 2379 } 2380 }(); 2381 2382 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2383 2384 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2385 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2386 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2387 Opcode, C, OBO::NoSignedWrap); 2388 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2389 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2390 } 2391 2392 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2393 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2394 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2395 Opcode, C, OBO::NoUnsignedWrap); 2396 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2397 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2398 } 2399 } 2400 2401 return Flags; 2402 } 2403 2404 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2405 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2406 } 2407 2408 /// Get a canonical add expression, or something simpler if possible. 2409 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2410 SCEV::NoWrapFlags Flags, 2411 unsigned Depth) { 2412 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2413 "only nuw or nsw allowed"); 2414 assert(!Ops.empty() && "Cannot get empty add!"); 2415 if (Ops.size() == 1) return Ops[0]; 2416 #ifndef NDEBUG 2417 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2418 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2419 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2420 "SCEVAddExpr operand types don't match!"); 2421 #endif 2422 2423 // Sort by complexity, this groups all similar expression types together. 2424 GroupByComplexity(Ops, &LI, DT); 2425 2426 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2427 2428 // If there are any constants, fold them together. 2429 unsigned Idx = 0; 2430 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2431 ++Idx; 2432 assert(Idx < Ops.size()); 2433 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2434 // We found two constants, fold them together! 2435 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2436 if (Ops.size() == 2) return Ops[0]; 2437 Ops.erase(Ops.begin()+1); // Erase the folded element 2438 LHSC = cast<SCEVConstant>(Ops[0]); 2439 } 2440 2441 // If we are left with a constant zero being added, strip it off. 2442 if (LHSC->getValue()->isZero()) { 2443 Ops.erase(Ops.begin()); 2444 --Idx; 2445 } 2446 2447 if (Ops.size() == 1) return Ops[0]; 2448 } 2449 2450 // Limit recursion calls depth. 2451 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2452 return getOrCreateAddExpr(Ops, Flags); 2453 2454 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2455 static_cast<SCEVAddExpr *>(S)->setNoWrapFlags(Flags); 2456 return S; 2457 } 2458 2459 // Okay, check to see if the same value occurs in the operand list more than 2460 // once. If so, merge them together into an multiply expression. Since we 2461 // sorted the list, these values are required to be adjacent. 2462 Type *Ty = Ops[0]->getType(); 2463 bool FoundMatch = false; 2464 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2465 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2466 // Scan ahead to count how many equal operands there are. 2467 unsigned Count = 2; 2468 while (i+Count != e && Ops[i+Count] == Ops[i]) 2469 ++Count; 2470 // Merge the values into a multiply. 2471 const SCEV *Scale = getConstant(Ty, Count); 2472 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2473 if (Ops.size() == Count) 2474 return Mul; 2475 Ops[i] = Mul; 2476 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2477 --i; e -= Count - 1; 2478 FoundMatch = true; 2479 } 2480 if (FoundMatch) 2481 return getAddExpr(Ops, Flags, Depth + 1); 2482 2483 // Check for truncates. If all the operands are truncated from the same 2484 // type, see if factoring out the truncate would permit the result to be 2485 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2486 // if the contents of the resulting outer trunc fold to something simple. 2487 auto FindTruncSrcType = [&]() -> Type * { 2488 // We're ultimately looking to fold an addrec of truncs and muls of only 2489 // constants and truncs, so if we find any other types of SCEV 2490 // as operands of the addrec then we bail and return nullptr here. 2491 // Otherwise, we return the type of the operand of a trunc that we find. 2492 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2493 return T->getOperand()->getType(); 2494 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2495 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2496 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2497 return T->getOperand()->getType(); 2498 } 2499 return nullptr; 2500 }; 2501 if (auto *SrcType = FindTruncSrcType()) { 2502 SmallVector<const SCEV *, 8> LargeOps; 2503 bool Ok = true; 2504 // Check all the operands to see if they can be represented in the 2505 // source type of the truncate. 2506 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2507 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2508 if (T->getOperand()->getType() != SrcType) { 2509 Ok = false; 2510 break; 2511 } 2512 LargeOps.push_back(T->getOperand()); 2513 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2514 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2515 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2516 SmallVector<const SCEV *, 8> LargeMulOps; 2517 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2518 if (const SCEVTruncateExpr *T = 2519 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2520 if (T->getOperand()->getType() != SrcType) { 2521 Ok = false; 2522 break; 2523 } 2524 LargeMulOps.push_back(T->getOperand()); 2525 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2526 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2527 } else { 2528 Ok = false; 2529 break; 2530 } 2531 } 2532 if (Ok) 2533 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2534 } else { 2535 Ok = false; 2536 break; 2537 } 2538 } 2539 if (Ok) { 2540 // Evaluate the expression in the larger type. 2541 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2542 // If it folds to something simple, use it. Otherwise, don't. 2543 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2544 return getTruncateExpr(Fold, Ty); 2545 } 2546 } 2547 2548 // Skip past any other cast SCEVs. 2549 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2550 ++Idx; 2551 2552 // If there are add operands they would be next. 2553 if (Idx < Ops.size()) { 2554 bool DeletedAdd = false; 2555 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2556 if (Ops.size() > AddOpsInlineThreshold || 2557 Add->getNumOperands() > AddOpsInlineThreshold) 2558 break; 2559 // If we have an add, expand the add operands onto the end of the operands 2560 // list. 2561 Ops.erase(Ops.begin()+Idx); 2562 Ops.append(Add->op_begin(), Add->op_end()); 2563 DeletedAdd = true; 2564 } 2565 2566 // If we deleted at least one add, we added operands to the end of the list, 2567 // and they are not necessarily sorted. Recurse to resort and resimplify 2568 // any operands we just acquired. 2569 if (DeletedAdd) 2570 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2571 } 2572 2573 // Skip over the add expression until we get to a multiply. 2574 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2575 ++Idx; 2576 2577 // Check to see if there are any folding opportunities present with 2578 // operands multiplied by constant values. 2579 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2580 uint64_t BitWidth = getTypeSizeInBits(Ty); 2581 DenseMap<const SCEV *, APInt> M; 2582 SmallVector<const SCEV *, 8> NewOps; 2583 APInt AccumulatedConstant(BitWidth, 0); 2584 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2585 Ops.data(), Ops.size(), 2586 APInt(BitWidth, 1), *this)) { 2587 struct APIntCompare { 2588 bool operator()(const APInt &LHS, const APInt &RHS) const { 2589 return LHS.ult(RHS); 2590 } 2591 }; 2592 2593 // Some interesting folding opportunity is present, so its worthwhile to 2594 // re-generate the operands list. Group the operands by constant scale, 2595 // to avoid multiplying by the same constant scale multiple times. 2596 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2597 for (const SCEV *NewOp : NewOps) 2598 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2599 // Re-generate the operands list. 2600 Ops.clear(); 2601 if (AccumulatedConstant != 0) 2602 Ops.push_back(getConstant(AccumulatedConstant)); 2603 for (auto &MulOp : MulOpLists) 2604 if (MulOp.first != 0) 2605 Ops.push_back(getMulExpr( 2606 getConstant(MulOp.first), 2607 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2608 SCEV::FlagAnyWrap, Depth + 1)); 2609 if (Ops.empty()) 2610 return getZero(Ty); 2611 if (Ops.size() == 1) 2612 return Ops[0]; 2613 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2614 } 2615 } 2616 2617 // If we are adding something to a multiply expression, make sure the 2618 // something is not already an operand of the multiply. If so, merge it into 2619 // the multiply. 2620 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2621 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2622 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2623 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2624 if (isa<SCEVConstant>(MulOpSCEV)) 2625 continue; 2626 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2627 if (MulOpSCEV == Ops[AddOp]) { 2628 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2629 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2630 if (Mul->getNumOperands() != 2) { 2631 // If the multiply has more than two operands, we must get the 2632 // Y*Z term. 2633 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2634 Mul->op_begin()+MulOp); 2635 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2636 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2637 } 2638 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2639 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2640 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2641 SCEV::FlagAnyWrap, Depth + 1); 2642 if (Ops.size() == 2) return OuterMul; 2643 if (AddOp < Idx) { 2644 Ops.erase(Ops.begin()+AddOp); 2645 Ops.erase(Ops.begin()+Idx-1); 2646 } else { 2647 Ops.erase(Ops.begin()+Idx); 2648 Ops.erase(Ops.begin()+AddOp-1); 2649 } 2650 Ops.push_back(OuterMul); 2651 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2652 } 2653 2654 // Check this multiply against other multiplies being added together. 2655 for (unsigned OtherMulIdx = Idx+1; 2656 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2657 ++OtherMulIdx) { 2658 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2659 // If MulOp occurs in OtherMul, we can fold the two multiplies 2660 // together. 2661 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2662 OMulOp != e; ++OMulOp) 2663 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2664 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2665 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2666 if (Mul->getNumOperands() != 2) { 2667 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2668 Mul->op_begin()+MulOp); 2669 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2670 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2671 } 2672 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2673 if (OtherMul->getNumOperands() != 2) { 2674 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2675 OtherMul->op_begin()+OMulOp); 2676 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2677 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2678 } 2679 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2680 const SCEV *InnerMulSum = 2681 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2682 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2683 SCEV::FlagAnyWrap, Depth + 1); 2684 if (Ops.size() == 2) return OuterMul; 2685 Ops.erase(Ops.begin()+Idx); 2686 Ops.erase(Ops.begin()+OtherMulIdx-1); 2687 Ops.push_back(OuterMul); 2688 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2689 } 2690 } 2691 } 2692 } 2693 2694 // If there are any add recurrences in the operands list, see if any other 2695 // added values are loop invariant. If so, we can fold them into the 2696 // recurrence. 2697 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2698 ++Idx; 2699 2700 // Scan over all recurrences, trying to fold loop invariants into them. 2701 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2702 // Scan all of the other operands to this add and add them to the vector if 2703 // they are loop invariant w.r.t. the recurrence. 2704 SmallVector<const SCEV *, 8> LIOps; 2705 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2706 const Loop *AddRecLoop = AddRec->getLoop(); 2707 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2708 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2709 LIOps.push_back(Ops[i]); 2710 Ops.erase(Ops.begin()+i); 2711 --i; --e; 2712 } 2713 2714 // If we found some loop invariants, fold them into the recurrence. 2715 if (!LIOps.empty()) { 2716 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2717 LIOps.push_back(AddRec->getStart()); 2718 2719 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2720 AddRec->op_end()); 2721 // This follows from the fact that the no-wrap flags on the outer add 2722 // expression are applicable on the 0th iteration, when the add recurrence 2723 // will be equal to its start value. 2724 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2725 2726 // Build the new addrec. Propagate the NUW and NSW flags if both the 2727 // outer add and the inner addrec are guaranteed to have no overflow. 2728 // Always propagate NW. 2729 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2730 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2731 2732 // If all of the other operands were loop invariant, we are done. 2733 if (Ops.size() == 1) return NewRec; 2734 2735 // Otherwise, add the folded AddRec by the non-invariant parts. 2736 for (unsigned i = 0;; ++i) 2737 if (Ops[i] == AddRec) { 2738 Ops[i] = NewRec; 2739 break; 2740 } 2741 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2742 } 2743 2744 // Okay, if there weren't any loop invariants to be folded, check to see if 2745 // there are multiple AddRec's with the same loop induction variable being 2746 // added together. If so, we can fold them. 2747 for (unsigned OtherIdx = Idx+1; 2748 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2749 ++OtherIdx) { 2750 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2751 // so that the 1st found AddRecExpr is dominated by all others. 2752 assert(DT.dominates( 2753 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2754 AddRec->getLoop()->getHeader()) && 2755 "AddRecExprs are not sorted in reverse dominance order?"); 2756 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2757 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2758 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2759 AddRec->op_end()); 2760 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2761 ++OtherIdx) { 2762 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2763 if (OtherAddRec->getLoop() == AddRecLoop) { 2764 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2765 i != e; ++i) { 2766 if (i >= AddRecOps.size()) { 2767 AddRecOps.append(OtherAddRec->op_begin()+i, 2768 OtherAddRec->op_end()); 2769 break; 2770 } 2771 SmallVector<const SCEV *, 2> TwoOps = { 2772 AddRecOps[i], OtherAddRec->getOperand(i)}; 2773 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2774 } 2775 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2776 } 2777 } 2778 // Step size has changed, so we cannot guarantee no self-wraparound. 2779 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2780 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2781 } 2782 } 2783 2784 // Otherwise couldn't fold anything into this recurrence. Move onto the 2785 // next one. 2786 } 2787 2788 // Okay, it looks like we really DO need an add expr. Check to see if we 2789 // already have one, otherwise create a new one. 2790 return getOrCreateAddExpr(Ops, Flags); 2791 } 2792 2793 const SCEV * 2794 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2795 SCEV::NoWrapFlags Flags) { 2796 FoldingSetNodeID ID; 2797 ID.AddInteger(scAddExpr); 2798 for (const SCEV *Op : Ops) 2799 ID.AddPointer(Op); 2800 void *IP = nullptr; 2801 SCEVAddExpr *S = 2802 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2803 if (!S) { 2804 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2805 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2806 S = new (SCEVAllocator) 2807 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2808 UniqueSCEVs.InsertNode(S, IP); 2809 addToLoopUseLists(S); 2810 } 2811 S->setNoWrapFlags(Flags); 2812 return S; 2813 } 2814 2815 const SCEV * 2816 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2817 const Loop *L, SCEV::NoWrapFlags Flags) { 2818 FoldingSetNodeID ID; 2819 ID.AddInteger(scAddRecExpr); 2820 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2821 ID.AddPointer(Ops[i]); 2822 ID.AddPointer(L); 2823 void *IP = nullptr; 2824 SCEVAddRecExpr *S = 2825 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2826 if (!S) { 2827 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2828 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2829 S = new (SCEVAllocator) 2830 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2831 UniqueSCEVs.InsertNode(S, IP); 2832 addToLoopUseLists(S); 2833 } 2834 S->setNoWrapFlags(Flags); 2835 return S; 2836 } 2837 2838 const SCEV * 2839 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2840 SCEV::NoWrapFlags Flags) { 2841 FoldingSetNodeID ID; 2842 ID.AddInteger(scMulExpr); 2843 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2844 ID.AddPointer(Ops[i]); 2845 void *IP = nullptr; 2846 SCEVMulExpr *S = 2847 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2848 if (!S) { 2849 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2850 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2851 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2852 O, Ops.size()); 2853 UniqueSCEVs.InsertNode(S, IP); 2854 addToLoopUseLists(S); 2855 } 2856 S->setNoWrapFlags(Flags); 2857 return S; 2858 } 2859 2860 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2861 uint64_t k = i*j; 2862 if (j > 1 && k / j != i) Overflow = true; 2863 return k; 2864 } 2865 2866 /// Compute the result of "n choose k", the binomial coefficient. If an 2867 /// intermediate computation overflows, Overflow will be set and the return will 2868 /// be garbage. Overflow is not cleared on absence of overflow. 2869 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2870 // We use the multiplicative formula: 2871 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2872 // At each iteration, we take the n-th term of the numeral and divide by the 2873 // (k-n)th term of the denominator. This division will always produce an 2874 // integral result, and helps reduce the chance of overflow in the 2875 // intermediate computations. However, we can still overflow even when the 2876 // final result would fit. 2877 2878 if (n == 0 || n == k) return 1; 2879 if (k > n) return 0; 2880 2881 if (k > n/2) 2882 k = n-k; 2883 2884 uint64_t r = 1; 2885 for (uint64_t i = 1; i <= k; ++i) { 2886 r = umul_ov(r, n-(i-1), Overflow); 2887 r /= i; 2888 } 2889 return r; 2890 } 2891 2892 /// Determine if any of the operands in this SCEV are a constant or if 2893 /// any of the add or multiply expressions in this SCEV contain a constant. 2894 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2895 struct FindConstantInAddMulChain { 2896 bool FoundConstant = false; 2897 2898 bool follow(const SCEV *S) { 2899 FoundConstant |= isa<SCEVConstant>(S); 2900 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2901 } 2902 2903 bool isDone() const { 2904 return FoundConstant; 2905 } 2906 }; 2907 2908 FindConstantInAddMulChain F; 2909 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2910 ST.visitAll(StartExpr); 2911 return F.FoundConstant; 2912 } 2913 2914 /// Get a canonical multiply expression, or something simpler if possible. 2915 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2916 SCEV::NoWrapFlags Flags, 2917 unsigned Depth) { 2918 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2919 "only nuw or nsw allowed"); 2920 assert(!Ops.empty() && "Cannot get empty mul!"); 2921 if (Ops.size() == 1) return Ops[0]; 2922 #ifndef NDEBUG 2923 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2924 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2925 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2926 "SCEVMulExpr operand types don't match!"); 2927 #endif 2928 2929 // Sort by complexity, this groups all similar expression types together. 2930 GroupByComplexity(Ops, &LI, DT); 2931 2932 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2933 2934 // Limit recursion calls depth. 2935 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2936 return getOrCreateMulExpr(Ops, Flags); 2937 2938 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2939 static_cast<SCEVMulExpr *>(S)->setNoWrapFlags(Flags); 2940 return S; 2941 } 2942 2943 // If there are any constants, fold them together. 2944 unsigned Idx = 0; 2945 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2946 2947 if (Ops.size() == 2) 2948 // C1*(C2+V) -> C1*C2 + C1*V 2949 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2950 // If any of Add's ops are Adds or Muls with a constant, apply this 2951 // transformation as well. 2952 // 2953 // TODO: There are some cases where this transformation is not 2954 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2955 // this transformation should be narrowed down. 2956 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2957 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2958 SCEV::FlagAnyWrap, Depth + 1), 2959 getMulExpr(LHSC, Add->getOperand(1), 2960 SCEV::FlagAnyWrap, Depth + 1), 2961 SCEV::FlagAnyWrap, Depth + 1); 2962 2963 ++Idx; 2964 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2965 // We found two constants, fold them together! 2966 ConstantInt *Fold = 2967 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt()); 2968 Ops[0] = getConstant(Fold); 2969 Ops.erase(Ops.begin()+1); // Erase the folded element 2970 if (Ops.size() == 1) return Ops[0]; 2971 LHSC = cast<SCEVConstant>(Ops[0]); 2972 } 2973 2974 // If we are left with a constant one being multiplied, strip it off. 2975 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) { 2976 Ops.erase(Ops.begin()); 2977 --Idx; 2978 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) { 2979 // If we have a multiply of zero, it will always be zero. 2980 return Ops[0]; 2981 } else if (Ops[0]->isAllOnesValue()) { 2982 // If we have a mul by -1 of an add, try distributing the -1 among the 2983 // add operands. 2984 if (Ops.size() == 2) { 2985 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2986 SmallVector<const SCEV *, 4> NewOps; 2987 bool AnyFolded = false; 2988 for (const SCEV *AddOp : Add->operands()) { 2989 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2990 Depth + 1); 2991 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2992 NewOps.push_back(Mul); 2993 } 2994 if (AnyFolded) 2995 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2996 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2997 // Negation preserves a recurrence's no self-wrap property. 2998 SmallVector<const SCEV *, 4> Operands; 2999 for (const SCEV *AddRecOp : AddRec->operands()) 3000 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 3001 Depth + 1)); 3002 3003 return getAddRecExpr(Operands, AddRec->getLoop(), 3004 AddRec->getNoWrapFlags(SCEV::FlagNW)); 3005 } 3006 } 3007 } 3008 3009 if (Ops.size() == 1) 3010 return Ops[0]; 3011 } 3012 3013 // Skip over the add expression until we get to a multiply. 3014 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 3015 ++Idx; 3016 3017 // If there are mul operands inline them all into this expression. 3018 if (Idx < Ops.size()) { 3019 bool DeletedMul = false; 3020 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 3021 if (Ops.size() > MulOpsInlineThreshold) 3022 break; 3023 // If we have an mul, expand the mul operands onto the end of the 3024 // operands list. 3025 Ops.erase(Ops.begin()+Idx); 3026 Ops.append(Mul->op_begin(), Mul->op_end()); 3027 DeletedMul = true; 3028 } 3029 3030 // If we deleted at least one mul, we added operands to the end of the 3031 // list, and they are not necessarily sorted. Recurse to resort and 3032 // resimplify any operands we just acquired. 3033 if (DeletedMul) 3034 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3035 } 3036 3037 // If there are any add recurrences in the operands list, see if any other 3038 // added values are loop invariant. If so, we can fold them into the 3039 // recurrence. 3040 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 3041 ++Idx; 3042 3043 // Scan over all recurrences, trying to fold loop invariants into them. 3044 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 3045 // Scan all of the other operands to this mul and add them to the vector 3046 // if they are loop invariant w.r.t. the recurrence. 3047 SmallVector<const SCEV *, 8> LIOps; 3048 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 3049 const Loop *AddRecLoop = AddRec->getLoop(); 3050 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3051 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 3052 LIOps.push_back(Ops[i]); 3053 Ops.erase(Ops.begin()+i); 3054 --i; --e; 3055 } 3056 3057 // If we found some loop invariants, fold them into the recurrence. 3058 if (!LIOps.empty()) { 3059 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 3060 SmallVector<const SCEV *, 4> NewOps; 3061 NewOps.reserve(AddRec->getNumOperands()); 3062 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 3063 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 3064 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 3065 SCEV::FlagAnyWrap, Depth + 1)); 3066 3067 // Build the new addrec. Propagate the NUW and NSW flags if both the 3068 // outer mul and the inner addrec are guaranteed to have no overflow. 3069 // 3070 // No self-wrap cannot be guaranteed after changing the step size, but 3071 // will be inferred if either NUW or NSW is true. 3072 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 3073 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 3074 3075 // If all of the other operands were loop invariant, we are done. 3076 if (Ops.size() == 1) return NewRec; 3077 3078 // Otherwise, multiply the folded AddRec by the non-invariant parts. 3079 for (unsigned i = 0;; ++i) 3080 if (Ops[i] == AddRec) { 3081 Ops[i] = NewRec; 3082 break; 3083 } 3084 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3085 } 3086 3087 // Okay, if there weren't any loop invariants to be folded, check to see 3088 // if there are multiple AddRec's with the same loop induction variable 3089 // being multiplied together. If so, we can fold them. 3090 3091 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 3092 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 3093 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 3094 // ]]],+,...up to x=2n}. 3095 // Note that the arguments to choose() are always integers with values 3096 // known at compile time, never SCEV objects. 3097 // 3098 // The implementation avoids pointless extra computations when the two 3099 // addrec's are of different length (mathematically, it's equivalent to 3100 // an infinite stream of zeros on the right). 3101 bool OpsModified = false; 3102 for (unsigned OtherIdx = Idx+1; 3103 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 3104 ++OtherIdx) { 3105 const SCEVAddRecExpr *OtherAddRec = 3106 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 3107 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 3108 continue; 3109 3110 // Limit max number of arguments to avoid creation of unreasonably big 3111 // SCEVAddRecs with very complex operands. 3112 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3113 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3114 continue; 3115 3116 bool Overflow = false; 3117 Type *Ty = AddRec->getType(); 3118 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3119 SmallVector<const SCEV*, 7> AddRecOps; 3120 for (int x = 0, xe = AddRec->getNumOperands() + 3121 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3122 SmallVector <const SCEV *, 7> SumOps; 3123 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3124 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3125 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3126 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3127 z < ze && !Overflow; ++z) { 3128 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3129 uint64_t Coeff; 3130 if (LargerThan64Bits) 3131 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3132 else 3133 Coeff = Coeff1*Coeff2; 3134 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3135 const SCEV *Term1 = AddRec->getOperand(y-z); 3136 const SCEV *Term2 = OtherAddRec->getOperand(z); 3137 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3138 SCEV::FlagAnyWrap, Depth + 1)); 3139 } 3140 } 3141 if (SumOps.empty()) 3142 SumOps.push_back(getZero(Ty)); 3143 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3144 } 3145 if (!Overflow) { 3146 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3147 SCEV::FlagAnyWrap); 3148 if (Ops.size() == 2) return NewAddRec; 3149 Ops[Idx] = NewAddRec; 3150 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3151 OpsModified = true; 3152 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3153 if (!AddRec) 3154 break; 3155 } 3156 } 3157 if (OpsModified) 3158 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3159 3160 // Otherwise couldn't fold anything into this recurrence. Move onto the 3161 // next one. 3162 } 3163 3164 // Okay, it looks like we really DO need an mul expr. Check to see if we 3165 // already have one, otherwise create a new one. 3166 return getOrCreateMulExpr(Ops, Flags); 3167 } 3168 3169 /// Represents an unsigned remainder expression based on unsigned division. 3170 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3171 const SCEV *RHS) { 3172 assert(getEffectiveSCEVType(LHS->getType()) == 3173 getEffectiveSCEVType(RHS->getType()) && 3174 "SCEVURemExpr operand types don't match!"); 3175 3176 // Short-circuit easy cases 3177 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3178 // If constant is one, the result is trivial 3179 if (RHSC->getValue()->isOne()) 3180 return getZero(LHS->getType()); // X urem 1 --> 0 3181 3182 // If constant is a power of two, fold into a zext(trunc(LHS)). 3183 if (RHSC->getAPInt().isPowerOf2()) { 3184 Type *FullTy = LHS->getType(); 3185 Type *TruncTy = 3186 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3187 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3188 } 3189 } 3190 3191 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3192 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3193 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3194 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3195 } 3196 3197 /// Get a canonical unsigned division expression, or something simpler if 3198 /// possible. 3199 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3200 const SCEV *RHS) { 3201 assert(getEffectiveSCEVType(LHS->getType()) == 3202 getEffectiveSCEVType(RHS->getType()) && 3203 "SCEVUDivExpr operand types don't match!"); 3204 3205 FoldingSetNodeID ID; 3206 ID.AddInteger(scUDivExpr); 3207 ID.AddPointer(LHS); 3208 ID.AddPointer(RHS); 3209 void *IP = nullptr; 3210 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3211 return S; 3212 3213 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3214 if (RHSC->getValue()->isOne()) 3215 return LHS; // X udiv 1 --> x 3216 // If the denominator is zero, the result of the udiv is undefined. Don't 3217 // try to analyze it, because the resolution chosen here may differ from 3218 // the resolution chosen in other parts of the compiler. 3219 if (!RHSC->getValue()->isZero()) { 3220 // Determine if the division can be folded into the operands of 3221 // its operands. 3222 // TODO: Generalize this to non-constants by using known-bits information. 3223 Type *Ty = LHS->getType(); 3224 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3225 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3226 // For non-power-of-two values, effectively round the value up to the 3227 // nearest power of two. 3228 if (!RHSC->getAPInt().isPowerOf2()) 3229 ++MaxShiftAmt; 3230 IntegerType *ExtTy = 3231 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3232 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3233 if (const SCEVConstant *Step = 3234 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3235 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3236 const APInt &StepInt = Step->getAPInt(); 3237 const APInt &DivInt = RHSC->getAPInt(); 3238 if (!StepInt.urem(DivInt) && 3239 getZeroExtendExpr(AR, ExtTy) == 3240 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3241 getZeroExtendExpr(Step, ExtTy), 3242 AR->getLoop(), SCEV::FlagAnyWrap)) { 3243 SmallVector<const SCEV *, 4> Operands; 3244 for (const SCEV *Op : AR->operands()) 3245 Operands.push_back(getUDivExpr(Op, RHS)); 3246 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3247 } 3248 /// Get a canonical UDivExpr for a recurrence. 3249 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3250 // We can currently only fold X%N if X is constant. 3251 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3252 if (StartC && !DivInt.urem(StepInt) && 3253 getZeroExtendExpr(AR, ExtTy) == 3254 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3255 getZeroExtendExpr(Step, ExtTy), 3256 AR->getLoop(), SCEV::FlagAnyWrap)) { 3257 const APInt &StartInt = StartC->getAPInt(); 3258 const APInt &StartRem = StartInt.urem(StepInt); 3259 if (StartRem != 0) { 3260 const SCEV *NewLHS = 3261 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3262 AR->getLoop(), SCEV::FlagNW); 3263 if (LHS != NewLHS) { 3264 LHS = NewLHS; 3265 3266 // Reset the ID to include the new LHS, and check if it is 3267 // already cached. 3268 ID.clear(); 3269 ID.AddInteger(scUDivExpr); 3270 ID.AddPointer(LHS); 3271 ID.AddPointer(RHS); 3272 IP = nullptr; 3273 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3274 return S; 3275 } 3276 } 3277 } 3278 } 3279 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3280 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3281 SmallVector<const SCEV *, 4> Operands; 3282 for (const SCEV *Op : M->operands()) 3283 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3284 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3285 // Find an operand that's safely divisible. 3286 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3287 const SCEV *Op = M->getOperand(i); 3288 const SCEV *Div = getUDivExpr(Op, RHSC); 3289 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3290 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3291 M->op_end()); 3292 Operands[i] = Div; 3293 return getMulExpr(Operands); 3294 } 3295 } 3296 } 3297 3298 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3299 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3300 if (auto *DivisorConstant = 3301 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3302 bool Overflow = false; 3303 APInt NewRHS = 3304 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3305 if (Overflow) { 3306 return getConstant(RHSC->getType(), 0, false); 3307 } 3308 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3309 } 3310 } 3311 3312 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3313 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3314 SmallVector<const SCEV *, 4> Operands; 3315 for (const SCEV *Op : A->operands()) 3316 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3317 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3318 Operands.clear(); 3319 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3320 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3321 if (isa<SCEVUDivExpr>(Op) || 3322 getMulExpr(Op, RHS) != A->getOperand(i)) 3323 break; 3324 Operands.push_back(Op); 3325 } 3326 if (Operands.size() == A->getNumOperands()) 3327 return getAddExpr(Operands); 3328 } 3329 } 3330 3331 // Fold if both operands are constant. 3332 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3333 Constant *LHSCV = LHSC->getValue(); 3334 Constant *RHSCV = RHSC->getValue(); 3335 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3336 RHSCV))); 3337 } 3338 } 3339 } 3340 3341 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3342 // changes). Make sure we get a new one. 3343 IP = nullptr; 3344 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3345 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3346 LHS, RHS); 3347 UniqueSCEVs.InsertNode(S, IP); 3348 addToLoopUseLists(S); 3349 return S; 3350 } 3351 3352 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3353 APInt A = C1->getAPInt().abs(); 3354 APInt B = C2->getAPInt().abs(); 3355 uint32_t ABW = A.getBitWidth(); 3356 uint32_t BBW = B.getBitWidth(); 3357 3358 if (ABW > BBW) 3359 B = B.zext(ABW); 3360 else if (ABW < BBW) 3361 A = A.zext(BBW); 3362 3363 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3364 } 3365 3366 /// Get a canonical unsigned division expression, or something simpler if 3367 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3368 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3369 /// it's not exact because the udiv may be clearing bits. 3370 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3371 const SCEV *RHS) { 3372 // TODO: we could try to find factors in all sorts of things, but for now we 3373 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3374 // end of this file for inspiration. 3375 3376 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3377 if (!Mul || !Mul->hasNoUnsignedWrap()) 3378 return getUDivExpr(LHS, RHS); 3379 3380 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3381 // If the mulexpr multiplies by a constant, then that constant must be the 3382 // first element of the mulexpr. 3383 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3384 if (LHSCst == RHSCst) { 3385 SmallVector<const SCEV *, 2> Operands; 3386 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3387 return getMulExpr(Operands); 3388 } 3389 3390 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3391 // that there's a factor provided by one of the other terms. We need to 3392 // check. 3393 APInt Factor = gcd(LHSCst, RHSCst); 3394 if (!Factor.isIntN(1)) { 3395 LHSCst = 3396 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3397 RHSCst = 3398 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3399 SmallVector<const SCEV *, 2> Operands; 3400 Operands.push_back(LHSCst); 3401 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3402 LHS = getMulExpr(Operands); 3403 RHS = RHSCst; 3404 Mul = dyn_cast<SCEVMulExpr>(LHS); 3405 if (!Mul) 3406 return getUDivExactExpr(LHS, RHS); 3407 } 3408 } 3409 } 3410 3411 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3412 if (Mul->getOperand(i) == RHS) { 3413 SmallVector<const SCEV *, 2> Operands; 3414 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3415 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3416 return getMulExpr(Operands); 3417 } 3418 } 3419 3420 return getUDivExpr(LHS, RHS); 3421 } 3422 3423 /// Get an add recurrence expression for the specified loop. Simplify the 3424 /// expression as much as possible. 3425 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3426 const Loop *L, 3427 SCEV::NoWrapFlags Flags) { 3428 SmallVector<const SCEV *, 4> Operands; 3429 Operands.push_back(Start); 3430 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3431 if (StepChrec->getLoop() == L) { 3432 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3433 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3434 } 3435 3436 Operands.push_back(Step); 3437 return getAddRecExpr(Operands, L, Flags); 3438 } 3439 3440 /// Get an add recurrence expression for the specified loop. Simplify the 3441 /// expression as much as possible. 3442 const SCEV * 3443 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3444 const Loop *L, SCEV::NoWrapFlags Flags) { 3445 if (Operands.size() == 1) return Operands[0]; 3446 #ifndef NDEBUG 3447 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3448 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3449 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3450 "SCEVAddRecExpr operand types don't match!"); 3451 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3452 assert(isLoopInvariant(Operands[i], L) && 3453 "SCEVAddRecExpr operand is not loop-invariant!"); 3454 #endif 3455 3456 if (Operands.back()->isZero()) { 3457 Operands.pop_back(); 3458 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3459 } 3460 3461 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3462 // use that information to infer NUW and NSW flags. However, computing a 3463 // BE count requires calling getAddRecExpr, so we may not yet have a 3464 // meaningful BE count at this point (and if we don't, we'd be stuck 3465 // with a SCEVCouldNotCompute as the cached BE count). 3466 3467 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3468 3469 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3470 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3471 const Loop *NestedLoop = NestedAR->getLoop(); 3472 if (L->contains(NestedLoop) 3473 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3474 : (!NestedLoop->contains(L) && 3475 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3476 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3477 NestedAR->op_end()); 3478 Operands[0] = NestedAR->getStart(); 3479 // AddRecs require their operands be loop-invariant with respect to their 3480 // loops. Don't perform this transformation if it would break this 3481 // requirement. 3482 bool AllInvariant = all_of( 3483 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3484 3485 if (AllInvariant) { 3486 // Create a recurrence for the outer loop with the same step size. 3487 // 3488 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3489 // inner recurrence has the same property. 3490 SCEV::NoWrapFlags OuterFlags = 3491 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3492 3493 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3494 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3495 return isLoopInvariant(Op, NestedLoop); 3496 }); 3497 3498 if (AllInvariant) { 3499 // Ok, both add recurrences are valid after the transformation. 3500 // 3501 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3502 // the outer recurrence has the same property. 3503 SCEV::NoWrapFlags InnerFlags = 3504 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3505 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3506 } 3507 } 3508 // Reset Operands to its original state. 3509 Operands[0] = NestedAR; 3510 } 3511 } 3512 3513 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3514 // already have one, otherwise create a new one. 3515 return getOrCreateAddRecExpr(Operands, L, Flags); 3516 } 3517 3518 const SCEV * 3519 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3520 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3521 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3522 // getSCEV(Base)->getType() has the same address space as Base->getType() 3523 // because SCEV::getType() preserves the address space. 3524 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3525 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3526 // instruction to its SCEV, because the Instruction may be guarded by control 3527 // flow and the no-overflow bits may not be valid for the expression in any 3528 // context. This can be fixed similarly to how these flags are handled for 3529 // adds. 3530 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3531 : SCEV::FlagAnyWrap; 3532 3533 const SCEV *TotalOffset = getZero(IntIdxTy); 3534 Type *CurTy = GEP->getType(); 3535 bool FirstIter = true; 3536 for (const SCEV *IndexExpr : IndexExprs) { 3537 // Compute the (potentially symbolic) offset in bytes for this index. 3538 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3539 // For a struct, add the member offset. 3540 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3541 unsigned FieldNo = Index->getZExtValue(); 3542 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3543 3544 // Add the field offset to the running total offset. 3545 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3546 3547 // Update CurTy to the type of the field at Index. 3548 CurTy = STy->getTypeAtIndex(Index); 3549 } else { 3550 // Update CurTy to its element type. 3551 if (FirstIter) { 3552 assert(isa<PointerType>(CurTy) && 3553 "The first index of a GEP indexes a pointer"); 3554 CurTy = GEP->getSourceElementType(); 3555 FirstIter = false; 3556 } else { 3557 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3558 } 3559 // For an array, add the element offset, explicitly scaled. 3560 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3561 // Getelementptr indices are signed. 3562 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3563 3564 // Multiply the index by the element size to compute the element offset. 3565 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3566 3567 // Add the element offset to the running total offset. 3568 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3569 } 3570 } 3571 3572 // Add the total offset from all the GEP indices to the base. 3573 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3574 } 3575 3576 std::tuple<SCEV *, FoldingSetNodeID, void *> 3577 ScalarEvolution::findExistingSCEVInCache(int SCEVType, 3578 ArrayRef<const SCEV *> Ops) { 3579 FoldingSetNodeID ID; 3580 void *IP = nullptr; 3581 ID.AddInteger(SCEVType); 3582 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3583 ID.AddPointer(Ops[i]); 3584 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3585 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3586 } 3587 3588 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind, 3589 SmallVectorImpl<const SCEV *> &Ops) { 3590 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3591 if (Ops.size() == 1) return Ops[0]; 3592 #ifndef NDEBUG 3593 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3594 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3595 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3596 "Operand types don't match!"); 3597 #endif 3598 3599 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3600 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3601 3602 // Sort by complexity, this groups all similar expression types together. 3603 GroupByComplexity(Ops, &LI, DT); 3604 3605 // Check if we have created the same expression before. 3606 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3607 return S; 3608 } 3609 3610 // If there are any constants, fold them together. 3611 unsigned Idx = 0; 3612 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3613 ++Idx; 3614 assert(Idx < Ops.size()); 3615 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3616 if (Kind == scSMaxExpr) 3617 return APIntOps::smax(LHS, RHS); 3618 else if (Kind == scSMinExpr) 3619 return APIntOps::smin(LHS, RHS); 3620 else if (Kind == scUMaxExpr) 3621 return APIntOps::umax(LHS, RHS); 3622 else if (Kind == scUMinExpr) 3623 return APIntOps::umin(LHS, RHS); 3624 llvm_unreachable("Unknown SCEV min/max opcode"); 3625 }; 3626 3627 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3628 // We found two constants, fold them together! 3629 ConstantInt *Fold = ConstantInt::get( 3630 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3631 Ops[0] = getConstant(Fold); 3632 Ops.erase(Ops.begin()+1); // Erase the folded element 3633 if (Ops.size() == 1) return Ops[0]; 3634 LHSC = cast<SCEVConstant>(Ops[0]); 3635 } 3636 3637 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3638 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3639 3640 if (IsMax ? IsMinV : IsMaxV) { 3641 // If we are left with a constant minimum(/maximum)-int, strip it off. 3642 Ops.erase(Ops.begin()); 3643 --Idx; 3644 } else if (IsMax ? IsMaxV : IsMinV) { 3645 // If we have a max(/min) with a constant maximum(/minimum)-int, 3646 // it will always be the extremum. 3647 return LHSC; 3648 } 3649 3650 if (Ops.size() == 1) return Ops[0]; 3651 } 3652 3653 // Find the first operation of the same kind 3654 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3655 ++Idx; 3656 3657 // Check to see if one of the operands is of the same kind. If so, expand its 3658 // operands onto our operand list, and recurse to simplify. 3659 if (Idx < Ops.size()) { 3660 bool DeletedAny = false; 3661 while (Ops[Idx]->getSCEVType() == Kind) { 3662 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3663 Ops.erase(Ops.begin()+Idx); 3664 Ops.append(SMME->op_begin(), SMME->op_end()); 3665 DeletedAny = true; 3666 } 3667 3668 if (DeletedAny) 3669 return getMinMaxExpr(Kind, Ops); 3670 } 3671 3672 // Okay, check to see if the same value occurs in the operand list twice. If 3673 // so, delete one. Since we sorted the list, these values are required to 3674 // be adjacent. 3675 llvm::CmpInst::Predicate GEPred = 3676 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3677 llvm::CmpInst::Predicate LEPred = 3678 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3679 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3680 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3681 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3682 if (Ops[i] == Ops[i + 1] || 3683 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3684 // X op Y op Y --> X op Y 3685 // X op Y --> X, if we know X, Y are ordered appropriately 3686 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3687 --i; 3688 --e; 3689 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3690 Ops[i + 1])) { 3691 // X op Y --> Y, if we know X, Y are ordered appropriately 3692 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3693 --i; 3694 --e; 3695 } 3696 } 3697 3698 if (Ops.size() == 1) return Ops[0]; 3699 3700 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3701 3702 // Okay, it looks like we really DO need an expr. Check to see if we 3703 // already have one, otherwise create a new one. 3704 const SCEV *ExistingSCEV; 3705 FoldingSetNodeID ID; 3706 void *IP; 3707 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3708 if (ExistingSCEV) 3709 return ExistingSCEV; 3710 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3711 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3712 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr( 3713 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size()); 3714 3715 UniqueSCEVs.InsertNode(S, IP); 3716 addToLoopUseLists(S); 3717 return S; 3718 } 3719 3720 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3721 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3722 return getSMaxExpr(Ops); 3723 } 3724 3725 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3726 return getMinMaxExpr(scSMaxExpr, Ops); 3727 } 3728 3729 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3730 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3731 return getUMaxExpr(Ops); 3732 } 3733 3734 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3735 return getMinMaxExpr(scUMaxExpr, Ops); 3736 } 3737 3738 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3739 const SCEV *RHS) { 3740 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3741 return getSMinExpr(Ops); 3742 } 3743 3744 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3745 return getMinMaxExpr(scSMinExpr, Ops); 3746 } 3747 3748 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3749 const SCEV *RHS) { 3750 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3751 return getUMinExpr(Ops); 3752 } 3753 3754 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3755 return getMinMaxExpr(scUMinExpr, Ops); 3756 } 3757 3758 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3759 // We can bypass creating a target-independent 3760 // constant expression and then folding it back into a ConstantInt. 3761 // This is just a compile-time optimization. 3762 if (isa<ScalableVectorType>(AllocTy)) { 3763 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); 3764 Constant *One = ConstantInt::get(IntTy, 1); 3765 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); 3766 return getSCEV(ConstantExpr::getPtrToInt(GEP, IntTy)); 3767 } 3768 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3769 } 3770 3771 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3772 StructType *STy, 3773 unsigned FieldNo) { 3774 // We can bypass creating a target-independent 3775 // constant expression and then folding it back into a ConstantInt. 3776 // This is just a compile-time optimization. 3777 return getConstant( 3778 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3779 } 3780 3781 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3782 // Don't attempt to do anything other than create a SCEVUnknown object 3783 // here. createSCEV only calls getUnknown after checking for all other 3784 // interesting possibilities, and any other code that calls getUnknown 3785 // is doing so in order to hide a value from SCEV canonicalization. 3786 3787 FoldingSetNodeID ID; 3788 ID.AddInteger(scUnknown); 3789 ID.AddPointer(V); 3790 void *IP = nullptr; 3791 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3792 assert(cast<SCEVUnknown>(S)->getValue() == V && 3793 "Stale SCEVUnknown in uniquing map!"); 3794 return S; 3795 } 3796 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3797 FirstUnknown); 3798 FirstUnknown = cast<SCEVUnknown>(S); 3799 UniqueSCEVs.InsertNode(S, IP); 3800 return S; 3801 } 3802 3803 //===----------------------------------------------------------------------===// 3804 // Basic SCEV Analysis and PHI Idiom Recognition Code 3805 // 3806 3807 /// Test if values of the given type are analyzable within the SCEV 3808 /// framework. This primarily includes integer types, and it can optionally 3809 /// include pointer types if the ScalarEvolution class has access to 3810 /// target-specific information. 3811 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3812 // Integers and pointers are always SCEVable. 3813 return Ty->isIntOrPtrTy(); 3814 } 3815 3816 /// Return the size in bits of the specified type, for which isSCEVable must 3817 /// return true. 3818 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3819 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3820 if (Ty->isPointerTy()) 3821 return getDataLayout().getIndexTypeSizeInBits(Ty); 3822 return getDataLayout().getTypeSizeInBits(Ty); 3823 } 3824 3825 /// Return a type with the same bitwidth as the given type and which represents 3826 /// how SCEV will treat the given type, for which isSCEVable must return 3827 /// true. For pointer types, this is the pointer index sized integer type. 3828 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3829 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3830 3831 if (Ty->isIntegerTy()) 3832 return Ty; 3833 3834 // The only other support type is pointer. 3835 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3836 return getDataLayout().getIndexType(Ty); 3837 } 3838 3839 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3840 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3841 } 3842 3843 const SCEV *ScalarEvolution::getCouldNotCompute() { 3844 return CouldNotCompute.get(); 3845 } 3846 3847 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3848 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3849 auto *SU = dyn_cast<SCEVUnknown>(S); 3850 return SU && SU->getValue() == nullptr; 3851 }); 3852 3853 return !ContainsNulls; 3854 } 3855 3856 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3857 HasRecMapType::iterator I = HasRecMap.find(S); 3858 if (I != HasRecMap.end()) 3859 return I->second; 3860 3861 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>); 3862 HasRecMap.insert({S, FoundAddRec}); 3863 return FoundAddRec; 3864 } 3865 3866 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3867 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3868 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3869 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3870 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3871 if (!Add) 3872 return {S, nullptr}; 3873 3874 if (Add->getNumOperands() != 2) 3875 return {S, nullptr}; 3876 3877 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3878 if (!ConstOp) 3879 return {S, nullptr}; 3880 3881 return {Add->getOperand(1), ConstOp->getValue()}; 3882 } 3883 3884 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3885 /// by the value and offset from any ValueOffsetPair in the set. 3886 SetVector<ScalarEvolution::ValueOffsetPair> * 3887 ScalarEvolution::getSCEVValues(const SCEV *S) { 3888 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3889 if (SI == ExprValueMap.end()) 3890 return nullptr; 3891 #ifndef NDEBUG 3892 if (VerifySCEVMap) { 3893 // Check there is no dangling Value in the set returned. 3894 for (const auto &VE : SI->second) 3895 assert(ValueExprMap.count(VE.first)); 3896 } 3897 #endif 3898 return &SI->second; 3899 } 3900 3901 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3902 /// cannot be used separately. eraseValueFromMap should be used to remove 3903 /// V from ValueExprMap and ExprValueMap at the same time. 3904 void ScalarEvolution::eraseValueFromMap(Value *V) { 3905 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3906 if (I != ValueExprMap.end()) { 3907 const SCEV *S = I->second; 3908 // Remove {V, 0} from the set of ExprValueMap[S] 3909 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3910 SV->remove({V, nullptr}); 3911 3912 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3913 const SCEV *Stripped; 3914 ConstantInt *Offset; 3915 std::tie(Stripped, Offset) = splitAddExpr(S); 3916 if (Offset != nullptr) { 3917 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3918 SV->remove({V, Offset}); 3919 } 3920 ValueExprMap.erase(V); 3921 } 3922 } 3923 3924 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3925 /// TODO: In reality it is better to check the poison recursively 3926 /// but this is better than nothing. 3927 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3928 if (auto *I = dyn_cast<Instruction>(V)) { 3929 if (isa<OverflowingBinaryOperator>(I)) { 3930 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3931 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3932 return true; 3933 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3934 return true; 3935 } 3936 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3937 return true; 3938 } 3939 return false; 3940 } 3941 3942 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3943 /// create a new one. 3944 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3945 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3946 3947 const SCEV *S = getExistingSCEV(V); 3948 if (S == nullptr) { 3949 S = createSCEV(V); 3950 // During PHI resolution, it is possible to create two SCEVs for the same 3951 // V, so it is needed to double check whether V->S is inserted into 3952 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3953 std::pair<ValueExprMapType::iterator, bool> Pair = 3954 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3955 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3956 ExprValueMap[S].insert({V, nullptr}); 3957 3958 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3959 // ExprValueMap. 3960 const SCEV *Stripped = S; 3961 ConstantInt *Offset = nullptr; 3962 std::tie(Stripped, Offset) = splitAddExpr(S); 3963 // If stripped is SCEVUnknown, don't bother to save 3964 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3965 // increase the complexity of the expansion code. 3966 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3967 // because it may generate add/sub instead of GEP in SCEV expansion. 3968 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3969 !isa<GetElementPtrInst>(V)) 3970 ExprValueMap[Stripped].insert({V, Offset}); 3971 } 3972 } 3973 return S; 3974 } 3975 3976 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3977 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3978 3979 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3980 if (I != ValueExprMap.end()) { 3981 const SCEV *S = I->second; 3982 if (checkValidity(S)) 3983 return S; 3984 eraseValueFromMap(V); 3985 forgetMemoizedResults(S); 3986 } 3987 return nullptr; 3988 } 3989 3990 /// Return a SCEV corresponding to -V = -1*V 3991 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3992 SCEV::NoWrapFlags Flags) { 3993 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3994 return getConstant( 3995 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3996 3997 Type *Ty = V->getType(); 3998 Ty = getEffectiveSCEVType(Ty); 3999 return getMulExpr( 4000 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags); 4001 } 4002 4003 /// If Expr computes ~A, return A else return nullptr 4004 static const SCEV *MatchNotExpr(const SCEV *Expr) { 4005 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 4006 if (!Add || Add->getNumOperands() != 2 || 4007 !Add->getOperand(0)->isAllOnesValue()) 4008 return nullptr; 4009 4010 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 4011 if (!AddRHS || AddRHS->getNumOperands() != 2 || 4012 !AddRHS->getOperand(0)->isAllOnesValue()) 4013 return nullptr; 4014 4015 return AddRHS->getOperand(1); 4016 } 4017 4018 /// Return a SCEV corresponding to ~V = -1-V 4019 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 4020 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 4021 return getConstant( 4022 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 4023 4024 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 4025 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 4026 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 4027 SmallVector<const SCEV *, 2> MatchedOperands; 4028 for (const SCEV *Operand : MME->operands()) { 4029 const SCEV *Matched = MatchNotExpr(Operand); 4030 if (!Matched) 4031 return (const SCEV *)nullptr; 4032 MatchedOperands.push_back(Matched); 4033 } 4034 return getMinMaxExpr( 4035 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())), 4036 MatchedOperands); 4037 }; 4038 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 4039 return Replaced; 4040 } 4041 4042 Type *Ty = V->getType(); 4043 Ty = getEffectiveSCEVType(Ty); 4044 const SCEV *AllOnes = 4045 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))); 4046 return getMinusSCEV(AllOnes, V); 4047 } 4048 4049 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 4050 SCEV::NoWrapFlags Flags, 4051 unsigned Depth) { 4052 // Fast path: X - X --> 0. 4053 if (LHS == RHS) 4054 return getZero(LHS->getType()); 4055 4056 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 4057 // makes it so that we cannot make much use of NUW. 4058 auto AddFlags = SCEV::FlagAnyWrap; 4059 const bool RHSIsNotMinSigned = 4060 !getSignedRangeMin(RHS).isMinSignedValue(); 4061 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 4062 // Let M be the minimum representable signed value. Then (-1)*RHS 4063 // signed-wraps if and only if RHS is M. That can happen even for 4064 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 4065 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 4066 // (-1)*RHS, we need to prove that RHS != M. 4067 // 4068 // If LHS is non-negative and we know that LHS - RHS does not 4069 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 4070 // either by proving that RHS > M or that LHS >= 0. 4071 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 4072 AddFlags = SCEV::FlagNSW; 4073 } 4074 } 4075 4076 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 4077 // RHS is NSW and LHS >= 0. 4078 // 4079 // The difficulty here is that the NSW flag may have been proven 4080 // relative to a loop that is to be found in a recurrence in LHS and 4081 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 4082 // larger scope than intended. 4083 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 4084 4085 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 4086 } 4087 4088 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 4089 unsigned Depth) { 4090 Type *SrcTy = V->getType(); 4091 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4092 "Cannot truncate or zero extend with non-integer arguments!"); 4093 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4094 return V; // No conversion 4095 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4096 return getTruncateExpr(V, Ty, Depth); 4097 return getZeroExtendExpr(V, Ty, Depth); 4098 } 4099 4100 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4101 unsigned Depth) { 4102 Type *SrcTy = V->getType(); 4103 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4104 "Cannot truncate or zero extend with non-integer arguments!"); 4105 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4106 return V; // No conversion 4107 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4108 return getTruncateExpr(V, Ty, Depth); 4109 return getSignExtendExpr(V, Ty, Depth); 4110 } 4111 4112 const SCEV * 4113 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4114 Type *SrcTy = V->getType(); 4115 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4116 "Cannot noop or zero extend with non-integer arguments!"); 4117 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4118 "getNoopOrZeroExtend cannot truncate!"); 4119 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4120 return V; // No conversion 4121 return getZeroExtendExpr(V, Ty); 4122 } 4123 4124 const SCEV * 4125 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4126 Type *SrcTy = V->getType(); 4127 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4128 "Cannot noop or sign extend with non-integer arguments!"); 4129 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4130 "getNoopOrSignExtend cannot truncate!"); 4131 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4132 return V; // No conversion 4133 return getSignExtendExpr(V, Ty); 4134 } 4135 4136 const SCEV * 4137 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4138 Type *SrcTy = V->getType(); 4139 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4140 "Cannot noop or any extend with non-integer arguments!"); 4141 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4142 "getNoopOrAnyExtend cannot truncate!"); 4143 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4144 return V; // No conversion 4145 return getAnyExtendExpr(V, Ty); 4146 } 4147 4148 const SCEV * 4149 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4150 Type *SrcTy = V->getType(); 4151 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4152 "Cannot truncate or noop with non-integer arguments!"); 4153 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4154 "getTruncateOrNoop cannot extend!"); 4155 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4156 return V; // No conversion 4157 return getTruncateExpr(V, Ty); 4158 } 4159 4160 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4161 const SCEV *RHS) { 4162 const SCEV *PromotedLHS = LHS; 4163 const SCEV *PromotedRHS = RHS; 4164 4165 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4166 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4167 else 4168 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4169 4170 return getUMaxExpr(PromotedLHS, PromotedRHS); 4171 } 4172 4173 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4174 const SCEV *RHS) { 4175 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4176 return getUMinFromMismatchedTypes(Ops); 4177 } 4178 4179 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4180 SmallVectorImpl<const SCEV *> &Ops) { 4181 assert(!Ops.empty() && "At least one operand must be!"); 4182 // Trivial case. 4183 if (Ops.size() == 1) 4184 return Ops[0]; 4185 4186 // Find the max type first. 4187 Type *MaxType = nullptr; 4188 for (auto *S : Ops) 4189 if (MaxType) 4190 MaxType = getWiderType(MaxType, S->getType()); 4191 else 4192 MaxType = S->getType(); 4193 4194 // Extend all ops to max type. 4195 SmallVector<const SCEV *, 2> PromotedOps; 4196 for (auto *S : Ops) 4197 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4198 4199 // Generate umin. 4200 return getUMinExpr(PromotedOps); 4201 } 4202 4203 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4204 // A pointer operand may evaluate to a nonpointer expression, such as null. 4205 if (!V->getType()->isPointerTy()) 4206 return V; 4207 4208 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) { 4209 return getPointerBase(Cast->getOperand()); 4210 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4211 const SCEV *PtrOp = nullptr; 4212 for (const SCEV *NAryOp : NAry->operands()) { 4213 if (NAryOp->getType()->isPointerTy()) { 4214 // Cannot find the base of an expression with multiple pointer operands. 4215 if (PtrOp) 4216 return V; 4217 PtrOp = NAryOp; 4218 } 4219 } 4220 if (!PtrOp) 4221 return V; 4222 return getPointerBase(PtrOp); 4223 } 4224 return V; 4225 } 4226 4227 /// Push users of the given Instruction onto the given Worklist. 4228 static void 4229 PushDefUseChildren(Instruction *I, 4230 SmallVectorImpl<Instruction *> &Worklist) { 4231 // Push the def-use children onto the Worklist stack. 4232 for (User *U : I->users()) 4233 Worklist.push_back(cast<Instruction>(U)); 4234 } 4235 4236 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4237 SmallVector<Instruction *, 16> Worklist; 4238 PushDefUseChildren(PN, Worklist); 4239 4240 SmallPtrSet<Instruction *, 8> Visited; 4241 Visited.insert(PN); 4242 while (!Worklist.empty()) { 4243 Instruction *I = Worklist.pop_back_val(); 4244 if (!Visited.insert(I).second) 4245 continue; 4246 4247 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4248 if (It != ValueExprMap.end()) { 4249 const SCEV *Old = It->second; 4250 4251 // Short-circuit the def-use traversal if the symbolic name 4252 // ceases to appear in expressions. 4253 if (Old != SymName && !hasOperand(Old, SymName)) 4254 continue; 4255 4256 // SCEVUnknown for a PHI either means that it has an unrecognized 4257 // structure, it's a PHI that's in the progress of being computed 4258 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4259 // additional loop trip count information isn't going to change anything. 4260 // In the second case, createNodeForPHI will perform the necessary 4261 // updates on its own when it gets to that point. In the third, we do 4262 // want to forget the SCEVUnknown. 4263 if (!isa<PHINode>(I) || 4264 !isa<SCEVUnknown>(Old) || 4265 (I != PN && Old == SymName)) { 4266 eraseValueFromMap(It->first); 4267 forgetMemoizedResults(Old); 4268 } 4269 } 4270 4271 PushDefUseChildren(I, Worklist); 4272 } 4273 } 4274 4275 namespace { 4276 4277 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4278 /// expression in case its Loop is L. If it is not L then 4279 /// if IgnoreOtherLoops is true then use AddRec itself 4280 /// otherwise rewrite cannot be done. 4281 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4282 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4283 public: 4284 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4285 bool IgnoreOtherLoops = true) { 4286 SCEVInitRewriter Rewriter(L, SE); 4287 const SCEV *Result = Rewriter.visit(S); 4288 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4289 return SE.getCouldNotCompute(); 4290 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4291 ? SE.getCouldNotCompute() 4292 : Result; 4293 } 4294 4295 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4296 if (!SE.isLoopInvariant(Expr, L)) 4297 SeenLoopVariantSCEVUnknown = true; 4298 return Expr; 4299 } 4300 4301 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4302 // Only re-write AddRecExprs for this loop. 4303 if (Expr->getLoop() == L) 4304 return Expr->getStart(); 4305 SeenOtherLoops = true; 4306 return Expr; 4307 } 4308 4309 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4310 4311 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4312 4313 private: 4314 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4315 : SCEVRewriteVisitor(SE), L(L) {} 4316 4317 const Loop *L; 4318 bool SeenLoopVariantSCEVUnknown = false; 4319 bool SeenOtherLoops = false; 4320 }; 4321 4322 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4323 /// increment expression in case its Loop is L. If it is not L then 4324 /// use AddRec itself. 4325 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4326 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4327 public: 4328 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4329 SCEVPostIncRewriter Rewriter(L, SE); 4330 const SCEV *Result = Rewriter.visit(S); 4331 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4332 ? SE.getCouldNotCompute() 4333 : Result; 4334 } 4335 4336 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4337 if (!SE.isLoopInvariant(Expr, L)) 4338 SeenLoopVariantSCEVUnknown = true; 4339 return Expr; 4340 } 4341 4342 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4343 // Only re-write AddRecExprs for this loop. 4344 if (Expr->getLoop() == L) 4345 return Expr->getPostIncExpr(SE); 4346 SeenOtherLoops = true; 4347 return Expr; 4348 } 4349 4350 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4351 4352 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4353 4354 private: 4355 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4356 : SCEVRewriteVisitor(SE), L(L) {} 4357 4358 const Loop *L; 4359 bool SeenLoopVariantSCEVUnknown = false; 4360 bool SeenOtherLoops = false; 4361 }; 4362 4363 /// This class evaluates the compare condition by matching it against the 4364 /// condition of loop latch. If there is a match we assume a true value 4365 /// for the condition while building SCEV nodes. 4366 class SCEVBackedgeConditionFolder 4367 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4368 public: 4369 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4370 ScalarEvolution &SE) { 4371 bool IsPosBECond = false; 4372 Value *BECond = nullptr; 4373 if (BasicBlock *Latch = L->getLoopLatch()) { 4374 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4375 if (BI && BI->isConditional()) { 4376 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4377 "Both outgoing branches should not target same header!"); 4378 BECond = BI->getCondition(); 4379 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4380 } else { 4381 return S; 4382 } 4383 } 4384 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4385 return Rewriter.visit(S); 4386 } 4387 4388 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4389 const SCEV *Result = Expr; 4390 bool InvariantF = SE.isLoopInvariant(Expr, L); 4391 4392 if (!InvariantF) { 4393 Instruction *I = cast<Instruction>(Expr->getValue()); 4394 switch (I->getOpcode()) { 4395 case Instruction::Select: { 4396 SelectInst *SI = cast<SelectInst>(I); 4397 Optional<const SCEV *> Res = 4398 compareWithBackedgeCondition(SI->getCondition()); 4399 if (Res.hasValue()) { 4400 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4401 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4402 } 4403 break; 4404 } 4405 default: { 4406 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4407 if (Res.hasValue()) 4408 Result = Res.getValue(); 4409 break; 4410 } 4411 } 4412 } 4413 return Result; 4414 } 4415 4416 private: 4417 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4418 bool IsPosBECond, ScalarEvolution &SE) 4419 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4420 IsPositiveBECond(IsPosBECond) {} 4421 4422 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4423 4424 const Loop *L; 4425 /// Loop back condition. 4426 Value *BackedgeCond = nullptr; 4427 /// Set to true if loop back is on positive branch condition. 4428 bool IsPositiveBECond; 4429 }; 4430 4431 Optional<const SCEV *> 4432 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4433 4434 // If value matches the backedge condition for loop latch, 4435 // then return a constant evolution node based on loopback 4436 // branch taken. 4437 if (BackedgeCond == IC) 4438 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4439 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4440 return None; 4441 } 4442 4443 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4444 public: 4445 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4446 ScalarEvolution &SE) { 4447 SCEVShiftRewriter Rewriter(L, SE); 4448 const SCEV *Result = Rewriter.visit(S); 4449 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4450 } 4451 4452 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4453 // Only allow AddRecExprs for this loop. 4454 if (!SE.isLoopInvariant(Expr, L)) 4455 Valid = false; 4456 return Expr; 4457 } 4458 4459 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4460 if (Expr->getLoop() == L && Expr->isAffine()) 4461 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4462 Valid = false; 4463 return Expr; 4464 } 4465 4466 bool isValid() { return Valid; } 4467 4468 private: 4469 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4470 : SCEVRewriteVisitor(SE), L(L) {} 4471 4472 const Loop *L; 4473 bool Valid = true; 4474 }; 4475 4476 } // end anonymous namespace 4477 4478 SCEV::NoWrapFlags 4479 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4480 if (!AR->isAffine()) 4481 return SCEV::FlagAnyWrap; 4482 4483 using OBO = OverflowingBinaryOperator; 4484 4485 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4486 4487 if (!AR->hasNoSignedWrap()) { 4488 ConstantRange AddRecRange = getSignedRange(AR); 4489 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4490 4491 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4492 Instruction::Add, IncRange, OBO::NoSignedWrap); 4493 if (NSWRegion.contains(AddRecRange)) 4494 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4495 } 4496 4497 if (!AR->hasNoUnsignedWrap()) { 4498 ConstantRange AddRecRange = getUnsignedRange(AR); 4499 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4500 4501 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4502 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4503 if (NUWRegion.contains(AddRecRange)) 4504 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4505 } 4506 4507 return Result; 4508 } 4509 4510 namespace { 4511 4512 /// Represents an abstract binary operation. This may exist as a 4513 /// normal instruction or constant expression, or may have been 4514 /// derived from an expression tree. 4515 struct BinaryOp { 4516 unsigned Opcode; 4517 Value *LHS; 4518 Value *RHS; 4519 bool IsNSW = false; 4520 bool IsNUW = false; 4521 4522 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4523 /// constant expression. 4524 Operator *Op = nullptr; 4525 4526 explicit BinaryOp(Operator *Op) 4527 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4528 Op(Op) { 4529 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4530 IsNSW = OBO->hasNoSignedWrap(); 4531 IsNUW = OBO->hasNoUnsignedWrap(); 4532 } 4533 } 4534 4535 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4536 bool IsNUW = false) 4537 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {} 4538 }; 4539 4540 } // end anonymous namespace 4541 4542 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4543 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4544 auto *Op = dyn_cast<Operator>(V); 4545 if (!Op) 4546 return None; 4547 4548 // Implementation detail: all the cleverness here should happen without 4549 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4550 // SCEV expressions when possible, and we should not break that. 4551 4552 switch (Op->getOpcode()) { 4553 case Instruction::Add: 4554 case Instruction::Sub: 4555 case Instruction::Mul: 4556 case Instruction::UDiv: 4557 case Instruction::URem: 4558 case Instruction::And: 4559 case Instruction::Or: 4560 case Instruction::AShr: 4561 case Instruction::Shl: 4562 return BinaryOp(Op); 4563 4564 case Instruction::Xor: 4565 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4566 // If the RHS of the xor is a signmask, then this is just an add. 4567 // Instcombine turns add of signmask into xor as a strength reduction step. 4568 if (RHSC->getValue().isSignMask()) 4569 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4570 return BinaryOp(Op); 4571 4572 case Instruction::LShr: 4573 // Turn logical shift right of a constant into a unsigned divide. 4574 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4575 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4576 4577 // If the shift count is not less than the bitwidth, the result of 4578 // the shift is undefined. Don't try to analyze it, because the 4579 // resolution chosen here may differ from the resolution chosen in 4580 // other parts of the compiler. 4581 if (SA->getValue().ult(BitWidth)) { 4582 Constant *X = 4583 ConstantInt::get(SA->getContext(), 4584 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4585 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4586 } 4587 } 4588 return BinaryOp(Op); 4589 4590 case Instruction::ExtractValue: { 4591 auto *EVI = cast<ExtractValueInst>(Op); 4592 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4593 break; 4594 4595 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4596 if (!WO) 4597 break; 4598 4599 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4600 bool Signed = WO->isSigned(); 4601 // TODO: Should add nuw/nsw flags for mul as well. 4602 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4603 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4604 4605 // Now that we know that all uses of the arithmetic-result component of 4606 // CI are guarded by the overflow check, we can go ahead and pretend 4607 // that the arithmetic is non-overflowing. 4608 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4609 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4610 } 4611 4612 default: 4613 break; 4614 } 4615 4616 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4617 // semantics as a Sub, return a binary sub expression. 4618 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4619 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4620 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4621 4622 return None; 4623 } 4624 4625 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4626 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4627 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4628 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4629 /// follows one of the following patterns: 4630 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4631 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4632 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4633 /// we return the type of the truncation operation, and indicate whether the 4634 /// truncated type should be treated as signed/unsigned by setting 4635 /// \p Signed to true/false, respectively. 4636 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4637 bool &Signed, ScalarEvolution &SE) { 4638 // The case where Op == SymbolicPHI (that is, with no type conversions on 4639 // the way) is handled by the regular add recurrence creating logic and 4640 // would have already been triggered in createAddRecForPHI. Reaching it here 4641 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4642 // because one of the other operands of the SCEVAddExpr updating this PHI is 4643 // not invariant). 4644 // 4645 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4646 // this case predicates that allow us to prove that Op == SymbolicPHI will 4647 // be added. 4648 if (Op == SymbolicPHI) 4649 return nullptr; 4650 4651 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4652 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4653 if (SourceBits != NewBits) 4654 return nullptr; 4655 4656 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4657 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4658 if (!SExt && !ZExt) 4659 return nullptr; 4660 const SCEVTruncateExpr *Trunc = 4661 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4662 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4663 if (!Trunc) 4664 return nullptr; 4665 const SCEV *X = Trunc->getOperand(); 4666 if (X != SymbolicPHI) 4667 return nullptr; 4668 Signed = SExt != nullptr; 4669 return Trunc->getType(); 4670 } 4671 4672 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4673 if (!PN->getType()->isIntegerTy()) 4674 return nullptr; 4675 const Loop *L = LI.getLoopFor(PN->getParent()); 4676 if (!L || L->getHeader() != PN->getParent()) 4677 return nullptr; 4678 return L; 4679 } 4680 4681 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4682 // computation that updates the phi follows the following pattern: 4683 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4684 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4685 // If so, try to see if it can be rewritten as an AddRecExpr under some 4686 // Predicates. If successful, return them as a pair. Also cache the results 4687 // of the analysis. 4688 // 4689 // Example usage scenario: 4690 // Say the Rewriter is called for the following SCEV: 4691 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4692 // where: 4693 // %X = phi i64 (%Start, %BEValue) 4694 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4695 // and call this function with %SymbolicPHI = %X. 4696 // 4697 // The analysis will find that the value coming around the backedge has 4698 // the following SCEV: 4699 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4700 // Upon concluding that this matches the desired pattern, the function 4701 // will return the pair {NewAddRec, SmallPredsVec} where: 4702 // NewAddRec = {%Start,+,%Step} 4703 // SmallPredsVec = {P1, P2, P3} as follows: 4704 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4705 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4706 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4707 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4708 // under the predicates {P1,P2,P3}. 4709 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4710 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4711 // 4712 // TODO's: 4713 // 4714 // 1) Extend the Induction descriptor to also support inductions that involve 4715 // casts: When needed (namely, when we are called in the context of the 4716 // vectorizer induction analysis), a Set of cast instructions will be 4717 // populated by this method, and provided back to isInductionPHI. This is 4718 // needed to allow the vectorizer to properly record them to be ignored by 4719 // the cost model and to avoid vectorizing them (otherwise these casts, 4720 // which are redundant under the runtime overflow checks, will be 4721 // vectorized, which can be costly). 4722 // 4723 // 2) Support additional induction/PHISCEV patterns: We also want to support 4724 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4725 // after the induction update operation (the induction increment): 4726 // 4727 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4728 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4729 // 4730 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4731 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4732 // 4733 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4734 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4735 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4736 SmallVector<const SCEVPredicate *, 3> Predicates; 4737 4738 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4739 // return an AddRec expression under some predicate. 4740 4741 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4742 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4743 assert(L && "Expecting an integer loop header phi"); 4744 4745 // The loop may have multiple entrances or multiple exits; we can analyze 4746 // this phi as an addrec if it has a unique entry value and a unique 4747 // backedge value. 4748 Value *BEValueV = nullptr, *StartValueV = nullptr; 4749 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4750 Value *V = PN->getIncomingValue(i); 4751 if (L->contains(PN->getIncomingBlock(i))) { 4752 if (!BEValueV) { 4753 BEValueV = V; 4754 } else if (BEValueV != V) { 4755 BEValueV = nullptr; 4756 break; 4757 } 4758 } else if (!StartValueV) { 4759 StartValueV = V; 4760 } else if (StartValueV != V) { 4761 StartValueV = nullptr; 4762 break; 4763 } 4764 } 4765 if (!BEValueV || !StartValueV) 4766 return None; 4767 4768 const SCEV *BEValue = getSCEV(BEValueV); 4769 4770 // If the value coming around the backedge is an add with the symbolic 4771 // value we just inserted, possibly with casts that we can ignore under 4772 // an appropriate runtime guard, then we found a simple induction variable! 4773 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4774 if (!Add) 4775 return None; 4776 4777 // If there is a single occurrence of the symbolic value, possibly 4778 // casted, replace it with a recurrence. 4779 unsigned FoundIndex = Add->getNumOperands(); 4780 Type *TruncTy = nullptr; 4781 bool Signed; 4782 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4783 if ((TruncTy = 4784 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4785 if (FoundIndex == e) { 4786 FoundIndex = i; 4787 break; 4788 } 4789 4790 if (FoundIndex == Add->getNumOperands()) 4791 return None; 4792 4793 // Create an add with everything but the specified operand. 4794 SmallVector<const SCEV *, 8> Ops; 4795 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4796 if (i != FoundIndex) 4797 Ops.push_back(Add->getOperand(i)); 4798 const SCEV *Accum = getAddExpr(Ops); 4799 4800 // The runtime checks will not be valid if the step amount is 4801 // varying inside the loop. 4802 if (!isLoopInvariant(Accum, L)) 4803 return None; 4804 4805 // *** Part2: Create the predicates 4806 4807 // Analysis was successful: we have a phi-with-cast pattern for which we 4808 // can return an AddRec expression under the following predicates: 4809 // 4810 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4811 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4812 // P2: An Equal predicate that guarantees that 4813 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4814 // P3: An Equal predicate that guarantees that 4815 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4816 // 4817 // As we next prove, the above predicates guarantee that: 4818 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4819 // 4820 // 4821 // More formally, we want to prove that: 4822 // Expr(i+1) = Start + (i+1) * Accum 4823 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4824 // 4825 // Given that: 4826 // 1) Expr(0) = Start 4827 // 2) Expr(1) = Start + Accum 4828 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4829 // 3) Induction hypothesis (step i): 4830 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4831 // 4832 // Proof: 4833 // Expr(i+1) = 4834 // = Start + (i+1)*Accum 4835 // = (Start + i*Accum) + Accum 4836 // = Expr(i) + Accum 4837 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4838 // :: from step i 4839 // 4840 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4841 // 4842 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4843 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4844 // + Accum :: from P3 4845 // 4846 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4847 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4848 // 4849 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4850 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4851 // 4852 // By induction, the same applies to all iterations 1<=i<n: 4853 // 4854 4855 // Create a truncated addrec for which we will add a no overflow check (P1). 4856 const SCEV *StartVal = getSCEV(StartValueV); 4857 const SCEV *PHISCEV = 4858 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4859 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4860 4861 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4862 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4863 // will be constant. 4864 // 4865 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4866 // add P1. 4867 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4868 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4869 Signed ? SCEVWrapPredicate::IncrementNSSW 4870 : SCEVWrapPredicate::IncrementNUSW; 4871 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4872 Predicates.push_back(AddRecPred); 4873 } 4874 4875 // Create the Equal Predicates P2,P3: 4876 4877 // It is possible that the predicates P2 and/or P3 are computable at 4878 // compile time due to StartVal and/or Accum being constants. 4879 // If either one is, then we can check that now and escape if either P2 4880 // or P3 is false. 4881 4882 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4883 // for each of StartVal and Accum 4884 auto getExtendedExpr = [&](const SCEV *Expr, 4885 bool CreateSignExtend) -> const SCEV * { 4886 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4887 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4888 const SCEV *ExtendedExpr = 4889 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4890 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4891 return ExtendedExpr; 4892 }; 4893 4894 // Given: 4895 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4896 // = getExtendedExpr(Expr) 4897 // Determine whether the predicate P: Expr == ExtendedExpr 4898 // is known to be false at compile time 4899 auto PredIsKnownFalse = [&](const SCEV *Expr, 4900 const SCEV *ExtendedExpr) -> bool { 4901 return Expr != ExtendedExpr && 4902 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4903 }; 4904 4905 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4906 if (PredIsKnownFalse(StartVal, StartExtended)) { 4907 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4908 return None; 4909 } 4910 4911 // The Step is always Signed (because the overflow checks are either 4912 // NSSW or NUSW) 4913 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4914 if (PredIsKnownFalse(Accum, AccumExtended)) { 4915 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4916 return None; 4917 } 4918 4919 auto AppendPredicate = [&](const SCEV *Expr, 4920 const SCEV *ExtendedExpr) -> void { 4921 if (Expr != ExtendedExpr && 4922 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4923 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4924 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4925 Predicates.push_back(Pred); 4926 } 4927 }; 4928 4929 AppendPredicate(StartVal, StartExtended); 4930 AppendPredicate(Accum, AccumExtended); 4931 4932 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4933 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4934 // into NewAR if it will also add the runtime overflow checks specified in 4935 // Predicates. 4936 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4937 4938 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4939 std::make_pair(NewAR, Predicates); 4940 // Remember the result of the analysis for this SCEV at this locayyytion. 4941 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4942 return PredRewrite; 4943 } 4944 4945 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4946 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4947 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4948 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4949 if (!L) 4950 return None; 4951 4952 // Check to see if we already analyzed this PHI. 4953 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4954 if (I != PredicatedSCEVRewrites.end()) { 4955 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4956 I->second; 4957 // Analysis was done before and failed to create an AddRec: 4958 if (Rewrite.first == SymbolicPHI) 4959 return None; 4960 // Analysis was done before and succeeded to create an AddRec under 4961 // a predicate: 4962 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4963 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4964 return Rewrite; 4965 } 4966 4967 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4968 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4969 4970 // Record in the cache that the analysis failed 4971 if (!Rewrite) { 4972 SmallVector<const SCEVPredicate *, 3> Predicates; 4973 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4974 return None; 4975 } 4976 4977 return Rewrite; 4978 } 4979 4980 // FIXME: This utility is currently required because the Rewriter currently 4981 // does not rewrite this expression: 4982 // {0, +, (sext ix (trunc iy to ix) to iy)} 4983 // into {0, +, %step}, 4984 // even when the following Equal predicate exists: 4985 // "%step == (sext ix (trunc iy to ix) to iy)". 4986 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4987 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4988 if (AR1 == AR2) 4989 return true; 4990 4991 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4992 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4993 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4994 return false; 4995 return true; 4996 }; 4997 4998 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4999 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 5000 return false; 5001 return true; 5002 } 5003 5004 /// A helper function for createAddRecFromPHI to handle simple cases. 5005 /// 5006 /// This function tries to find an AddRec expression for the simplest (yet most 5007 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 5008 /// If it fails, createAddRecFromPHI will use a more general, but slow, 5009 /// technique for finding the AddRec expression. 5010 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 5011 Value *BEValueV, 5012 Value *StartValueV) { 5013 const Loop *L = LI.getLoopFor(PN->getParent()); 5014 assert(L && L->getHeader() == PN->getParent()); 5015 assert(BEValueV && StartValueV); 5016 5017 auto BO = MatchBinaryOp(BEValueV, DT); 5018 if (!BO) 5019 return nullptr; 5020 5021 if (BO->Opcode != Instruction::Add) 5022 return nullptr; 5023 5024 const SCEV *Accum = nullptr; 5025 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 5026 Accum = getSCEV(BO->RHS); 5027 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 5028 Accum = getSCEV(BO->LHS); 5029 5030 if (!Accum) 5031 return nullptr; 5032 5033 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5034 if (BO->IsNUW) 5035 Flags = setFlags(Flags, SCEV::FlagNUW); 5036 if (BO->IsNSW) 5037 Flags = setFlags(Flags, SCEV::FlagNSW); 5038 5039 const SCEV *StartVal = getSCEV(StartValueV); 5040 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5041 5042 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5043 5044 // We can add Flags to the post-inc expression only if we 5045 // know that it is *undefined behavior* for BEValueV to 5046 // overflow. 5047 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5048 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5049 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5050 5051 return PHISCEV; 5052 } 5053 5054 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 5055 const Loop *L = LI.getLoopFor(PN->getParent()); 5056 if (!L || L->getHeader() != PN->getParent()) 5057 return nullptr; 5058 5059 // The loop may have multiple entrances or multiple exits; we can analyze 5060 // this phi as an addrec if it has a unique entry value and a unique 5061 // backedge value. 5062 Value *BEValueV = nullptr, *StartValueV = nullptr; 5063 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 5064 Value *V = PN->getIncomingValue(i); 5065 if (L->contains(PN->getIncomingBlock(i))) { 5066 if (!BEValueV) { 5067 BEValueV = V; 5068 } else if (BEValueV != V) { 5069 BEValueV = nullptr; 5070 break; 5071 } 5072 } else if (!StartValueV) { 5073 StartValueV = V; 5074 } else if (StartValueV != V) { 5075 StartValueV = nullptr; 5076 break; 5077 } 5078 } 5079 if (!BEValueV || !StartValueV) 5080 return nullptr; 5081 5082 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 5083 "PHI node already processed?"); 5084 5085 // First, try to find AddRec expression without creating a fictituos symbolic 5086 // value for PN. 5087 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 5088 return S; 5089 5090 // Handle PHI node value symbolically. 5091 const SCEV *SymbolicName = getUnknown(PN); 5092 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5093 5094 // Using this symbolic name for the PHI, analyze the value coming around 5095 // the back-edge. 5096 const SCEV *BEValue = getSCEV(BEValueV); 5097 5098 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5099 // has a special value for the first iteration of the loop. 5100 5101 // If the value coming around the backedge is an add with the symbolic 5102 // value we just inserted, then we found a simple induction variable! 5103 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5104 // If there is a single occurrence of the symbolic value, replace it 5105 // with a recurrence. 5106 unsigned FoundIndex = Add->getNumOperands(); 5107 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5108 if (Add->getOperand(i) == SymbolicName) 5109 if (FoundIndex == e) { 5110 FoundIndex = i; 5111 break; 5112 } 5113 5114 if (FoundIndex != Add->getNumOperands()) { 5115 // Create an add with everything but the specified operand. 5116 SmallVector<const SCEV *, 8> Ops; 5117 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5118 if (i != FoundIndex) 5119 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5120 L, *this)); 5121 const SCEV *Accum = getAddExpr(Ops); 5122 5123 // This is not a valid addrec if the step amount is varying each 5124 // loop iteration, but is not itself an addrec in this loop. 5125 if (isLoopInvariant(Accum, L) || 5126 (isa<SCEVAddRecExpr>(Accum) && 5127 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5128 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5129 5130 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5131 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5132 if (BO->IsNUW) 5133 Flags = setFlags(Flags, SCEV::FlagNUW); 5134 if (BO->IsNSW) 5135 Flags = setFlags(Flags, SCEV::FlagNSW); 5136 } 5137 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5138 // If the increment is an inbounds GEP, then we know the address 5139 // space cannot be wrapped around. We cannot make any guarantee 5140 // about signed or unsigned overflow because pointers are 5141 // unsigned but we may have a negative index from the base 5142 // pointer. We can guarantee that no unsigned wrap occurs if the 5143 // indices form a positive value. 5144 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5145 Flags = setFlags(Flags, SCEV::FlagNW); 5146 5147 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5148 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5149 Flags = setFlags(Flags, SCEV::FlagNUW); 5150 } 5151 5152 // We cannot transfer nuw and nsw flags from subtraction 5153 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5154 // for instance. 5155 } 5156 5157 const SCEV *StartVal = getSCEV(StartValueV); 5158 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5159 5160 // Okay, for the entire analysis of this edge we assumed the PHI 5161 // to be symbolic. We now need to go back and purge all of the 5162 // entries for the scalars that use the symbolic expression. 5163 forgetSymbolicName(PN, SymbolicName); 5164 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5165 5166 // We can add Flags to the post-inc expression only if we 5167 // know that it is *undefined behavior* for BEValueV to 5168 // overflow. 5169 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5170 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5171 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5172 5173 return PHISCEV; 5174 } 5175 } 5176 } else { 5177 // Otherwise, this could be a loop like this: 5178 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5179 // In this case, j = {1,+,1} and BEValue is j. 5180 // Because the other in-value of i (0) fits the evolution of BEValue 5181 // i really is an addrec evolution. 5182 // 5183 // We can generalize this saying that i is the shifted value of BEValue 5184 // by one iteration: 5185 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5186 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5187 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5188 if (Shifted != getCouldNotCompute() && 5189 Start != getCouldNotCompute()) { 5190 const SCEV *StartVal = getSCEV(StartValueV); 5191 if (Start == StartVal) { 5192 // Okay, for the entire analysis of this edge we assumed the PHI 5193 // to be symbolic. We now need to go back and purge all of the 5194 // entries for the scalars that use the symbolic expression. 5195 forgetSymbolicName(PN, SymbolicName); 5196 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5197 return Shifted; 5198 } 5199 } 5200 } 5201 5202 // Remove the temporary PHI node SCEV that has been inserted while intending 5203 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5204 // as it will prevent later (possibly simpler) SCEV expressions to be added 5205 // to the ValueExprMap. 5206 eraseValueFromMap(PN); 5207 5208 return nullptr; 5209 } 5210 5211 // Checks if the SCEV S is available at BB. S is considered available at BB 5212 // if S can be materialized at BB without introducing a fault. 5213 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5214 BasicBlock *BB) { 5215 struct CheckAvailable { 5216 bool TraversalDone = false; 5217 bool Available = true; 5218 5219 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5220 BasicBlock *BB = nullptr; 5221 DominatorTree &DT; 5222 5223 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5224 : L(L), BB(BB), DT(DT) {} 5225 5226 bool setUnavailable() { 5227 TraversalDone = true; 5228 Available = false; 5229 return false; 5230 } 5231 5232 bool follow(const SCEV *S) { 5233 switch (S->getSCEVType()) { 5234 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend: 5235 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr: 5236 case scUMinExpr: 5237 case scSMinExpr: 5238 // These expressions are available if their operand(s) is/are. 5239 return true; 5240 5241 case scAddRecExpr: { 5242 // We allow add recurrences that are on the loop BB is in, or some 5243 // outer loop. This guarantees availability because the value of the 5244 // add recurrence at BB is simply the "current" value of the induction 5245 // variable. We can relax this in the future; for instance an add 5246 // recurrence on a sibling dominating loop is also available at BB. 5247 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5248 if (L && (ARLoop == L || ARLoop->contains(L))) 5249 return true; 5250 5251 return setUnavailable(); 5252 } 5253 5254 case scUnknown: { 5255 // For SCEVUnknown, we check for simple dominance. 5256 const auto *SU = cast<SCEVUnknown>(S); 5257 Value *V = SU->getValue(); 5258 5259 if (isa<Argument>(V)) 5260 return false; 5261 5262 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5263 return false; 5264 5265 return setUnavailable(); 5266 } 5267 5268 case scUDivExpr: 5269 case scCouldNotCompute: 5270 // We do not try to smart about these at all. 5271 return setUnavailable(); 5272 } 5273 llvm_unreachable("switch should be fully covered!"); 5274 } 5275 5276 bool isDone() { return TraversalDone; } 5277 }; 5278 5279 CheckAvailable CA(L, BB, DT); 5280 SCEVTraversal<CheckAvailable> ST(CA); 5281 5282 ST.visitAll(S); 5283 return CA.Available; 5284 } 5285 5286 // Try to match a control flow sequence that branches out at BI and merges back 5287 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5288 // match. 5289 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5290 Value *&C, Value *&LHS, Value *&RHS) { 5291 C = BI->getCondition(); 5292 5293 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5294 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5295 5296 if (!LeftEdge.isSingleEdge()) 5297 return false; 5298 5299 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5300 5301 Use &LeftUse = Merge->getOperandUse(0); 5302 Use &RightUse = Merge->getOperandUse(1); 5303 5304 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5305 LHS = LeftUse; 5306 RHS = RightUse; 5307 return true; 5308 } 5309 5310 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5311 LHS = RightUse; 5312 RHS = LeftUse; 5313 return true; 5314 } 5315 5316 return false; 5317 } 5318 5319 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5320 auto IsReachable = 5321 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5322 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5323 const Loop *L = LI.getLoopFor(PN->getParent()); 5324 5325 // We don't want to break LCSSA, even in a SCEV expression tree. 5326 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5327 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5328 return nullptr; 5329 5330 // Try to match 5331 // 5332 // br %cond, label %left, label %right 5333 // left: 5334 // br label %merge 5335 // right: 5336 // br label %merge 5337 // merge: 5338 // V = phi [ %x, %left ], [ %y, %right ] 5339 // 5340 // as "select %cond, %x, %y" 5341 5342 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5343 assert(IDom && "At least the entry block should dominate PN"); 5344 5345 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5346 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5347 5348 if (BI && BI->isConditional() && 5349 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5350 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5351 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5352 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5353 } 5354 5355 return nullptr; 5356 } 5357 5358 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5359 if (const SCEV *S = createAddRecFromPHI(PN)) 5360 return S; 5361 5362 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5363 return S; 5364 5365 // If the PHI has a single incoming value, follow that value, unless the 5366 // PHI's incoming blocks are in a different loop, in which case doing so 5367 // risks breaking LCSSA form. Instcombine would normally zap these, but 5368 // it doesn't have DominatorTree information, so it may miss cases. 5369 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5370 if (LI.replacementPreservesLCSSAForm(PN, V)) 5371 return getSCEV(V); 5372 5373 // If it's not a loop phi, we can't handle it yet. 5374 return getUnknown(PN); 5375 } 5376 5377 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5378 Value *Cond, 5379 Value *TrueVal, 5380 Value *FalseVal) { 5381 // Handle "constant" branch or select. This can occur for instance when a 5382 // loop pass transforms an inner loop and moves on to process the outer loop. 5383 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5384 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5385 5386 // Try to match some simple smax or umax patterns. 5387 auto *ICI = dyn_cast<ICmpInst>(Cond); 5388 if (!ICI) 5389 return getUnknown(I); 5390 5391 Value *LHS = ICI->getOperand(0); 5392 Value *RHS = ICI->getOperand(1); 5393 5394 switch (ICI->getPredicate()) { 5395 case ICmpInst::ICMP_SLT: 5396 case ICmpInst::ICMP_SLE: 5397 std::swap(LHS, RHS); 5398 LLVM_FALLTHROUGH; 5399 case ICmpInst::ICMP_SGT: 5400 case ICmpInst::ICMP_SGE: 5401 // a >s b ? a+x : b+x -> smax(a, b)+x 5402 // a >s b ? b+x : a+x -> smin(a, b)+x 5403 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5404 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5405 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5406 const SCEV *LA = getSCEV(TrueVal); 5407 const SCEV *RA = getSCEV(FalseVal); 5408 const SCEV *LDiff = getMinusSCEV(LA, LS); 5409 const SCEV *RDiff = getMinusSCEV(RA, RS); 5410 if (LDiff == RDiff) 5411 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5412 LDiff = getMinusSCEV(LA, RS); 5413 RDiff = getMinusSCEV(RA, LS); 5414 if (LDiff == RDiff) 5415 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5416 } 5417 break; 5418 case ICmpInst::ICMP_ULT: 5419 case ICmpInst::ICMP_ULE: 5420 std::swap(LHS, RHS); 5421 LLVM_FALLTHROUGH; 5422 case ICmpInst::ICMP_UGT: 5423 case ICmpInst::ICMP_UGE: 5424 // a >u b ? a+x : b+x -> umax(a, b)+x 5425 // a >u b ? b+x : a+x -> umin(a, b)+x 5426 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5427 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5428 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5429 const SCEV *LA = getSCEV(TrueVal); 5430 const SCEV *RA = getSCEV(FalseVal); 5431 const SCEV *LDiff = getMinusSCEV(LA, LS); 5432 const SCEV *RDiff = getMinusSCEV(RA, RS); 5433 if (LDiff == RDiff) 5434 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5435 LDiff = getMinusSCEV(LA, RS); 5436 RDiff = getMinusSCEV(RA, LS); 5437 if (LDiff == RDiff) 5438 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5439 } 5440 break; 5441 case ICmpInst::ICMP_NE: 5442 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5443 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5444 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5445 const SCEV *One = getOne(I->getType()); 5446 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5447 const SCEV *LA = getSCEV(TrueVal); 5448 const SCEV *RA = getSCEV(FalseVal); 5449 const SCEV *LDiff = getMinusSCEV(LA, LS); 5450 const SCEV *RDiff = getMinusSCEV(RA, One); 5451 if (LDiff == RDiff) 5452 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5453 } 5454 break; 5455 case ICmpInst::ICMP_EQ: 5456 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5457 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5458 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5459 const SCEV *One = getOne(I->getType()); 5460 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5461 const SCEV *LA = getSCEV(TrueVal); 5462 const SCEV *RA = getSCEV(FalseVal); 5463 const SCEV *LDiff = getMinusSCEV(LA, One); 5464 const SCEV *RDiff = getMinusSCEV(RA, LS); 5465 if (LDiff == RDiff) 5466 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5467 } 5468 break; 5469 default: 5470 break; 5471 } 5472 5473 return getUnknown(I); 5474 } 5475 5476 /// Expand GEP instructions into add and multiply operations. This allows them 5477 /// to be analyzed by regular SCEV code. 5478 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5479 // Don't attempt to analyze GEPs over unsized objects. 5480 if (!GEP->getSourceElementType()->isSized()) 5481 return getUnknown(GEP); 5482 5483 SmallVector<const SCEV *, 4> IndexExprs; 5484 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5485 IndexExprs.push_back(getSCEV(*Index)); 5486 return getGEPExpr(GEP, IndexExprs); 5487 } 5488 5489 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5490 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5491 return C->getAPInt().countTrailingZeros(); 5492 5493 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5494 return std::min(GetMinTrailingZeros(T->getOperand()), 5495 (uint32_t)getTypeSizeInBits(T->getType())); 5496 5497 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5498 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5499 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5500 ? getTypeSizeInBits(E->getType()) 5501 : OpRes; 5502 } 5503 5504 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5505 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5506 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5507 ? getTypeSizeInBits(E->getType()) 5508 : OpRes; 5509 } 5510 5511 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5512 // The result is the min of all operands results. 5513 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5514 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5515 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5516 return MinOpRes; 5517 } 5518 5519 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5520 // The result is the sum of all operands results. 5521 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5522 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5523 for (unsigned i = 1, e = M->getNumOperands(); 5524 SumOpRes != BitWidth && i != e; ++i) 5525 SumOpRes = 5526 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5527 return SumOpRes; 5528 } 5529 5530 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5531 // The result is the min of all operands results. 5532 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5533 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5534 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5535 return MinOpRes; 5536 } 5537 5538 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5539 // The result is the min of all operands results. 5540 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5541 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5542 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5543 return MinOpRes; 5544 } 5545 5546 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5547 // The result is the min of all operands results. 5548 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5549 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5550 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5551 return MinOpRes; 5552 } 5553 5554 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5555 // For a SCEVUnknown, ask ValueTracking. 5556 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5557 return Known.countMinTrailingZeros(); 5558 } 5559 5560 // SCEVUDivExpr 5561 return 0; 5562 } 5563 5564 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5565 auto I = MinTrailingZerosCache.find(S); 5566 if (I != MinTrailingZerosCache.end()) 5567 return I->second; 5568 5569 uint32_t Result = GetMinTrailingZerosImpl(S); 5570 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5571 assert(InsertPair.second && "Should insert a new key"); 5572 return InsertPair.first->second; 5573 } 5574 5575 /// Helper method to assign a range to V from metadata present in the IR. 5576 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5577 if (Instruction *I = dyn_cast<Instruction>(V)) 5578 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5579 return getConstantRangeFromMetadata(*MD); 5580 5581 return None; 5582 } 5583 5584 /// Determine the range for a particular SCEV. If SignHint is 5585 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5586 /// with a "cleaner" unsigned (resp. signed) representation. 5587 const ConstantRange & 5588 ScalarEvolution::getRangeRef(const SCEV *S, 5589 ScalarEvolution::RangeSignHint SignHint) { 5590 DenseMap<const SCEV *, ConstantRange> &Cache = 5591 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5592 : SignedRanges; 5593 ConstantRange::PreferredRangeType RangeType = 5594 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5595 ? ConstantRange::Unsigned : ConstantRange::Signed; 5596 5597 // See if we've computed this range already. 5598 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5599 if (I != Cache.end()) 5600 return I->second; 5601 5602 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5603 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5604 5605 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5606 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5607 using OBO = OverflowingBinaryOperator; 5608 5609 // If the value has known zeros, the maximum value will have those known zeros 5610 // as well. 5611 uint32_t TZ = GetMinTrailingZeros(S); 5612 if (TZ != 0) { 5613 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5614 ConservativeResult = 5615 ConstantRange(APInt::getMinValue(BitWidth), 5616 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5617 else 5618 ConservativeResult = ConstantRange( 5619 APInt::getSignedMinValue(BitWidth), 5620 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5621 } 5622 5623 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5624 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5625 unsigned WrapType = OBO::AnyWrap; 5626 if (Add->hasNoSignedWrap()) 5627 WrapType |= OBO::NoSignedWrap; 5628 if (Add->hasNoUnsignedWrap()) 5629 WrapType |= OBO::NoUnsignedWrap; 5630 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5631 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5632 WrapType, RangeType); 5633 return setRange(Add, SignHint, 5634 ConservativeResult.intersectWith(X, RangeType)); 5635 } 5636 5637 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5638 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5639 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5640 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5641 return setRange(Mul, SignHint, 5642 ConservativeResult.intersectWith(X, RangeType)); 5643 } 5644 5645 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5646 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5647 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5648 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5649 return setRange(SMax, SignHint, 5650 ConservativeResult.intersectWith(X, RangeType)); 5651 } 5652 5653 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5654 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5655 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5656 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5657 return setRange(UMax, SignHint, 5658 ConservativeResult.intersectWith(X, RangeType)); 5659 } 5660 5661 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5662 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5663 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5664 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5665 return setRange(SMin, SignHint, 5666 ConservativeResult.intersectWith(X, RangeType)); 5667 } 5668 5669 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5670 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5671 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5672 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5673 return setRange(UMin, SignHint, 5674 ConservativeResult.intersectWith(X, RangeType)); 5675 } 5676 5677 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5678 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5679 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5680 return setRange(UDiv, SignHint, 5681 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5682 } 5683 5684 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5685 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5686 return setRange(ZExt, SignHint, 5687 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5688 RangeType)); 5689 } 5690 5691 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5692 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5693 return setRange(SExt, SignHint, 5694 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5695 RangeType)); 5696 } 5697 5698 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5699 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5700 return setRange(Trunc, SignHint, 5701 ConservativeResult.intersectWith(X.truncate(BitWidth), 5702 RangeType)); 5703 } 5704 5705 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5706 // If there's no unsigned wrap, the value will never be less than its 5707 // initial value. 5708 if (AddRec->hasNoUnsignedWrap()) { 5709 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5710 if (!UnsignedMinValue.isNullValue()) 5711 ConservativeResult = ConservativeResult.intersectWith( 5712 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5713 } 5714 5715 // If there's no signed wrap, and all the operands except initial value have 5716 // the same sign or zero, the value won't ever be: 5717 // 1: smaller than initial value if operands are non negative, 5718 // 2: bigger than initial value if operands are non positive. 5719 // For both cases, value can not cross signed min/max boundary. 5720 if (AddRec->hasNoSignedWrap()) { 5721 bool AllNonNeg = true; 5722 bool AllNonPos = true; 5723 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5724 if (!isKnownNonNegative(AddRec->getOperand(i))) 5725 AllNonNeg = false; 5726 if (!isKnownNonPositive(AddRec->getOperand(i))) 5727 AllNonPos = false; 5728 } 5729 if (AllNonNeg) 5730 ConservativeResult = ConservativeResult.intersectWith( 5731 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5732 APInt::getSignedMinValue(BitWidth)), 5733 RangeType); 5734 else if (AllNonPos) 5735 ConservativeResult = ConservativeResult.intersectWith( 5736 ConstantRange::getNonEmpty( 5737 APInt::getSignedMinValue(BitWidth), 5738 getSignedRangeMax(AddRec->getStart()) + 1), 5739 RangeType); 5740 } 5741 5742 // TODO: non-affine addrec 5743 if (AddRec->isAffine()) { 5744 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5745 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5746 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5747 auto RangeFromAffine = getRangeForAffineAR( 5748 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5749 BitWidth); 5750 if (!RangeFromAffine.isFullSet()) 5751 ConservativeResult = 5752 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5753 5754 auto RangeFromFactoring = getRangeViaFactoring( 5755 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5756 BitWidth); 5757 if (!RangeFromFactoring.isFullSet()) 5758 ConservativeResult = 5759 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5760 } 5761 } 5762 5763 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5764 } 5765 5766 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5767 // Check if the IR explicitly contains !range metadata. 5768 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5769 if (MDRange.hasValue()) 5770 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5771 RangeType); 5772 5773 // Split here to avoid paying the compile-time cost of calling both 5774 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5775 // if needed. 5776 const DataLayout &DL = getDataLayout(); 5777 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5778 // For a SCEVUnknown, ask ValueTracking. 5779 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5780 if (Known.getBitWidth() != BitWidth) 5781 Known = Known.zextOrTrunc(BitWidth); 5782 // If Known does not result in full-set, intersect with it. 5783 if (Known.getMinValue() != Known.getMaxValue() + 1) 5784 ConservativeResult = ConservativeResult.intersectWith( 5785 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5786 RangeType); 5787 } else { 5788 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5789 "generalize as needed!"); 5790 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5791 // If the pointer size is larger than the index size type, this can cause 5792 // NS to be larger than BitWidth. So compensate for this. 5793 if (U->getType()->isPointerTy()) { 5794 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5795 int ptrIdxDiff = ptrSize - BitWidth; 5796 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5797 NS -= ptrIdxDiff; 5798 } 5799 5800 if (NS > 1) 5801 ConservativeResult = ConservativeResult.intersectWith( 5802 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5803 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5804 RangeType); 5805 } 5806 5807 // A range of Phi is a subset of union of all ranges of its input. 5808 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5809 // Make sure that we do not run over cycled Phis. 5810 if (PendingPhiRanges.insert(Phi).second) { 5811 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5812 for (auto &Op : Phi->operands()) { 5813 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5814 RangeFromOps = RangeFromOps.unionWith(OpRange); 5815 // No point to continue if we already have a full set. 5816 if (RangeFromOps.isFullSet()) 5817 break; 5818 } 5819 ConservativeResult = 5820 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5821 bool Erased = PendingPhiRanges.erase(Phi); 5822 assert(Erased && "Failed to erase Phi properly?"); 5823 (void) Erased; 5824 } 5825 } 5826 5827 return setRange(U, SignHint, std::move(ConservativeResult)); 5828 } 5829 5830 return setRange(S, SignHint, std::move(ConservativeResult)); 5831 } 5832 5833 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5834 // values that the expression can take. Initially, the expression has a value 5835 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5836 // argument defines if we treat Step as signed or unsigned. 5837 static ConstantRange getRangeForAffineARHelper(APInt Step, 5838 const ConstantRange &StartRange, 5839 const APInt &MaxBECount, 5840 unsigned BitWidth, bool Signed) { 5841 // If either Step or MaxBECount is 0, then the expression won't change, and we 5842 // just need to return the initial range. 5843 if (Step == 0 || MaxBECount == 0) 5844 return StartRange; 5845 5846 // If we don't know anything about the initial value (i.e. StartRange is 5847 // FullRange), then we don't know anything about the final range either. 5848 // Return FullRange. 5849 if (StartRange.isFullSet()) 5850 return ConstantRange::getFull(BitWidth); 5851 5852 // If Step is signed and negative, then we use its absolute value, but we also 5853 // note that we're moving in the opposite direction. 5854 bool Descending = Signed && Step.isNegative(); 5855 5856 if (Signed) 5857 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5858 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5859 // This equations hold true due to the well-defined wrap-around behavior of 5860 // APInt. 5861 Step = Step.abs(); 5862 5863 // Check if Offset is more than full span of BitWidth. If it is, the 5864 // expression is guaranteed to overflow. 5865 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5866 return ConstantRange::getFull(BitWidth); 5867 5868 // Offset is by how much the expression can change. Checks above guarantee no 5869 // overflow here. 5870 APInt Offset = Step * MaxBECount; 5871 5872 // Minimum value of the final range will match the minimal value of StartRange 5873 // if the expression is increasing and will be decreased by Offset otherwise. 5874 // Maximum value of the final range will match the maximal value of StartRange 5875 // if the expression is decreasing and will be increased by Offset otherwise. 5876 APInt StartLower = StartRange.getLower(); 5877 APInt StartUpper = StartRange.getUpper() - 1; 5878 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5879 : (StartUpper + std::move(Offset)); 5880 5881 // It's possible that the new minimum/maximum value will fall into the initial 5882 // range (due to wrap around). This means that the expression can take any 5883 // value in this bitwidth, and we have to return full range. 5884 if (StartRange.contains(MovedBoundary)) 5885 return ConstantRange::getFull(BitWidth); 5886 5887 APInt NewLower = 5888 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5889 APInt NewUpper = 5890 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5891 NewUpper += 1; 5892 5893 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5894 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5895 } 5896 5897 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5898 const SCEV *Step, 5899 const SCEV *MaxBECount, 5900 unsigned BitWidth) { 5901 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5902 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5903 "Precondition!"); 5904 5905 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5906 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5907 5908 // First, consider step signed. 5909 ConstantRange StartSRange = getSignedRange(Start); 5910 ConstantRange StepSRange = getSignedRange(Step); 5911 5912 // If Step can be both positive and negative, we need to find ranges for the 5913 // maximum absolute step values in both directions and union them. 5914 ConstantRange SR = 5915 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5916 MaxBECountValue, BitWidth, /* Signed = */ true); 5917 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5918 StartSRange, MaxBECountValue, 5919 BitWidth, /* Signed = */ true)); 5920 5921 // Next, consider step unsigned. 5922 ConstantRange UR = getRangeForAffineARHelper( 5923 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5924 MaxBECountValue, BitWidth, /* Signed = */ false); 5925 5926 // Finally, intersect signed and unsigned ranges. 5927 return SR.intersectWith(UR, ConstantRange::Smallest); 5928 } 5929 5930 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start, 5931 const SCEV *Step, 5932 const SCEV *MaxBECount, 5933 unsigned BitWidth) { 5934 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q}) 5935 // == RangeOf({A,+,P}) union RangeOf({B,+,Q}) 5936 5937 struct SelectPattern { 5938 Value *Condition = nullptr; 5939 APInt TrueValue; 5940 APInt FalseValue; 5941 5942 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth, 5943 const SCEV *S) { 5944 Optional<unsigned> CastOp; 5945 APInt Offset(BitWidth, 0); 5946 5947 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth && 5948 "Should be!"); 5949 5950 // Peel off a constant offset: 5951 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) { 5952 // In the future we could consider being smarter here and handle 5953 // {Start+Step,+,Step} too. 5954 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0))) 5955 return; 5956 5957 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt(); 5958 S = SA->getOperand(1); 5959 } 5960 5961 // Peel off a cast operation 5962 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) { 5963 CastOp = SCast->getSCEVType(); 5964 S = SCast->getOperand(); 5965 } 5966 5967 using namespace llvm::PatternMatch; 5968 5969 auto *SU = dyn_cast<SCEVUnknown>(S); 5970 const APInt *TrueVal, *FalseVal; 5971 if (!SU || 5972 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal), 5973 m_APInt(FalseVal)))) { 5974 Condition = nullptr; 5975 return; 5976 } 5977 5978 TrueValue = *TrueVal; 5979 FalseValue = *FalseVal; 5980 5981 // Re-apply the cast we peeled off earlier 5982 if (CastOp.hasValue()) 5983 switch (*CastOp) { 5984 default: 5985 llvm_unreachable("Unknown SCEV cast type!"); 5986 5987 case scTruncate: 5988 TrueValue = TrueValue.trunc(BitWidth); 5989 FalseValue = FalseValue.trunc(BitWidth); 5990 break; 5991 case scZeroExtend: 5992 TrueValue = TrueValue.zext(BitWidth); 5993 FalseValue = FalseValue.zext(BitWidth); 5994 break; 5995 case scSignExtend: 5996 TrueValue = TrueValue.sext(BitWidth); 5997 FalseValue = FalseValue.sext(BitWidth); 5998 break; 5999 } 6000 6001 // Re-apply the constant offset we peeled off earlier 6002 TrueValue += Offset; 6003 FalseValue += Offset; 6004 } 6005 6006 bool isRecognized() { return Condition != nullptr; } 6007 }; 6008 6009 SelectPattern StartPattern(*this, BitWidth, Start); 6010 if (!StartPattern.isRecognized()) 6011 return ConstantRange::getFull(BitWidth); 6012 6013 SelectPattern StepPattern(*this, BitWidth, Step); 6014 if (!StepPattern.isRecognized()) 6015 return ConstantRange::getFull(BitWidth); 6016 6017 if (StartPattern.Condition != StepPattern.Condition) { 6018 // We don't handle this case today; but we could, by considering four 6019 // possibilities below instead of two. I'm not sure if there are cases where 6020 // that will help over what getRange already does, though. 6021 return ConstantRange::getFull(BitWidth); 6022 } 6023 6024 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to 6025 // construct arbitrary general SCEV expressions here. This function is called 6026 // from deep in the call stack, and calling getSCEV (on a sext instruction, 6027 // say) can end up caching a suboptimal value. 6028 6029 // FIXME: without the explicit `this` receiver below, MSVC errors out with 6030 // C2352 and C2512 (otherwise it isn't needed). 6031 6032 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue); 6033 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue); 6034 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue); 6035 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue); 6036 6037 ConstantRange TrueRange = 6038 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth); 6039 ConstantRange FalseRange = 6040 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth); 6041 6042 return TrueRange.unionWith(FalseRange); 6043 } 6044 6045 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) { 6046 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap; 6047 const BinaryOperator *BinOp = cast<BinaryOperator>(V); 6048 6049 // Return early if there are no flags to propagate to the SCEV. 6050 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6051 if (BinOp->hasNoUnsignedWrap()) 6052 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 6053 if (BinOp->hasNoSignedWrap()) 6054 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 6055 if (Flags == SCEV::FlagAnyWrap) 6056 return SCEV::FlagAnyWrap; 6057 6058 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap; 6059 } 6060 6061 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) { 6062 // Here we check that I is in the header of the innermost loop containing I, 6063 // since we only deal with instructions in the loop header. The actual loop we 6064 // need to check later will come from an add recurrence, but getting that 6065 // requires computing the SCEV of the operands, which can be expensive. This 6066 // check we can do cheaply to rule out some cases early. 6067 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent()); 6068 if (InnermostContainingLoop == nullptr || 6069 InnermostContainingLoop->getHeader() != I->getParent()) 6070 return false; 6071 6072 // Only proceed if we can prove that I does not yield poison. 6073 if (!programUndefinedIfPoison(I)) 6074 return false; 6075 6076 // At this point we know that if I is executed, then it does not wrap 6077 // according to at least one of NSW or NUW. If I is not executed, then we do 6078 // not know if the calculation that I represents would wrap. Multiple 6079 // instructions can map to the same SCEV. If we apply NSW or NUW from I to 6080 // the SCEV, we must guarantee no wrapping for that SCEV also when it is 6081 // derived from other instructions that map to the same SCEV. We cannot make 6082 // that guarantee for cases where I is not executed. So we need to find the 6083 // loop that I is considered in relation to and prove that I is executed for 6084 // every iteration of that loop. That implies that the value that I 6085 // calculates does not wrap anywhere in the loop, so then we can apply the 6086 // flags to the SCEV. 6087 // 6088 // We check isLoopInvariant to disambiguate in case we are adding recurrences 6089 // from different loops, so that we know which loop to prove that I is 6090 // executed in. 6091 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) { 6092 // I could be an extractvalue from a call to an overflow intrinsic. 6093 // TODO: We can do better here in some cases. 6094 if (!isSCEVable(I->getOperand(OpIndex)->getType())) 6095 return false; 6096 const SCEV *Op = getSCEV(I->getOperand(OpIndex)); 6097 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 6098 bool AllOtherOpsLoopInvariant = true; 6099 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands(); 6100 ++OtherOpIndex) { 6101 if (OtherOpIndex != OpIndex) { 6102 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex)); 6103 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) { 6104 AllOtherOpsLoopInvariant = false; 6105 break; 6106 } 6107 } 6108 } 6109 if (AllOtherOpsLoopInvariant && 6110 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop())) 6111 return true; 6112 } 6113 } 6114 return false; 6115 } 6116 6117 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) { 6118 // If we know that \c I can never be poison period, then that's enough. 6119 if (isSCEVExprNeverPoison(I)) 6120 return true; 6121 6122 // For an add recurrence specifically, we assume that infinite loops without 6123 // side effects are undefined behavior, and then reason as follows: 6124 // 6125 // If the add recurrence is poison in any iteration, it is poison on all 6126 // future iterations (since incrementing poison yields poison). If the result 6127 // of the add recurrence is fed into the loop latch condition and the loop 6128 // does not contain any throws or exiting blocks other than the latch, we now 6129 // have the ability to "choose" whether the backedge is taken or not (by 6130 // choosing a sufficiently evil value for the poison feeding into the branch) 6131 // for every iteration including and after the one in which \p I first became 6132 // poison. There are two possibilities (let's call the iteration in which \p 6133 // I first became poison as K): 6134 // 6135 // 1. In the set of iterations including and after K, the loop body executes 6136 // no side effects. In this case executing the backege an infinte number 6137 // of times will yield undefined behavior. 6138 // 6139 // 2. In the set of iterations including and after K, the loop body executes 6140 // at least one side effect. In this case, that specific instance of side 6141 // effect is control dependent on poison, which also yields undefined 6142 // behavior. 6143 6144 auto *ExitingBB = L->getExitingBlock(); 6145 auto *LatchBB = L->getLoopLatch(); 6146 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB) 6147 return false; 6148 6149 SmallPtrSet<const Instruction *, 16> Pushed; 6150 SmallVector<const Instruction *, 8> PoisonStack; 6151 6152 // We start by assuming \c I, the post-inc add recurrence, is poison. Only 6153 // things that are known to be poison under that assumption go on the 6154 // PoisonStack. 6155 Pushed.insert(I); 6156 PoisonStack.push_back(I); 6157 6158 bool LatchControlDependentOnPoison = false; 6159 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) { 6160 const Instruction *Poison = PoisonStack.pop_back_val(); 6161 6162 for (auto *PoisonUser : Poison->users()) { 6163 if (propagatesPoison(cast<Instruction>(PoisonUser))) { 6164 if (Pushed.insert(cast<Instruction>(PoisonUser)).second) 6165 PoisonStack.push_back(cast<Instruction>(PoisonUser)); 6166 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) { 6167 assert(BI->isConditional() && "Only possibility!"); 6168 if (BI->getParent() == LatchBB) { 6169 LatchControlDependentOnPoison = true; 6170 break; 6171 } 6172 } 6173 } 6174 } 6175 6176 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L); 6177 } 6178 6179 ScalarEvolution::LoopProperties 6180 ScalarEvolution::getLoopProperties(const Loop *L) { 6181 using LoopProperties = ScalarEvolution::LoopProperties; 6182 6183 auto Itr = LoopPropertiesCache.find(L); 6184 if (Itr == LoopPropertiesCache.end()) { 6185 auto HasSideEffects = [](Instruction *I) { 6186 if (auto *SI = dyn_cast<StoreInst>(I)) 6187 return !SI->isSimple(); 6188 6189 return I->mayHaveSideEffects(); 6190 }; 6191 6192 LoopProperties LP = {/* HasNoAbnormalExits */ true, 6193 /*HasNoSideEffects*/ true}; 6194 6195 for (auto *BB : L->getBlocks()) 6196 for (auto &I : *BB) { 6197 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 6198 LP.HasNoAbnormalExits = false; 6199 if (HasSideEffects(&I)) 6200 LP.HasNoSideEffects = false; 6201 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects) 6202 break; // We're already as pessimistic as we can get. 6203 } 6204 6205 auto InsertPair = LoopPropertiesCache.insert({L, LP}); 6206 assert(InsertPair.second && "We just checked!"); 6207 Itr = InsertPair.first; 6208 } 6209 6210 return Itr->second; 6211 } 6212 6213 const SCEV *ScalarEvolution::createSCEV(Value *V) { 6214 if (!isSCEVable(V->getType())) 6215 return getUnknown(V); 6216 6217 if (Instruction *I = dyn_cast<Instruction>(V)) { 6218 // Don't attempt to analyze instructions in blocks that aren't 6219 // reachable. Such instructions don't matter, and they aren't required 6220 // to obey basic rules for definitions dominating uses which this 6221 // analysis depends on. 6222 if (!DT.isReachableFromEntry(I->getParent())) 6223 return getUnknown(UndefValue::get(V->getType())); 6224 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) 6225 return getConstant(CI); 6226 else if (isa<ConstantPointerNull>(V)) 6227 return getZero(V->getType()); 6228 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6229 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6230 else if (!isa<ConstantExpr>(V)) 6231 return getUnknown(V); 6232 6233 Operator *U = cast<Operator>(V); 6234 if (auto BO = MatchBinaryOp(U, DT)) { 6235 switch (BO->Opcode) { 6236 case Instruction::Add: { 6237 // The simple thing to do would be to just call getSCEV on both operands 6238 // and call getAddExpr with the result. However if we're looking at a 6239 // bunch of things all added together, this can be quite inefficient, 6240 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6241 // Instead, gather up all the operands and make a single getAddExpr call. 6242 // LLVM IR canonical form means we need only traverse the left operands. 6243 SmallVector<const SCEV *, 4> AddOps; 6244 do { 6245 if (BO->Op) { 6246 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6247 AddOps.push_back(OpSCEV); 6248 break; 6249 } 6250 6251 // If a NUW or NSW flag can be applied to the SCEV for this 6252 // addition, then compute the SCEV for this addition by itself 6253 // with a separate call to getAddExpr. We need to do that 6254 // instead of pushing the operands of the addition onto AddOps, 6255 // since the flags are only known to apply to this particular 6256 // addition - they may not apply to other additions that can be 6257 // formed with operands from AddOps. 6258 const SCEV *RHS = getSCEV(BO->RHS); 6259 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6260 if (Flags != SCEV::FlagAnyWrap) { 6261 const SCEV *LHS = getSCEV(BO->LHS); 6262 if (BO->Opcode == Instruction::Sub) 6263 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6264 else 6265 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6266 break; 6267 } 6268 } 6269 6270 if (BO->Opcode == Instruction::Sub) 6271 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6272 else 6273 AddOps.push_back(getSCEV(BO->RHS)); 6274 6275 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6276 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6277 NewBO->Opcode != Instruction::Sub)) { 6278 AddOps.push_back(getSCEV(BO->LHS)); 6279 break; 6280 } 6281 BO = NewBO; 6282 } while (true); 6283 6284 return getAddExpr(AddOps); 6285 } 6286 6287 case Instruction::Mul: { 6288 SmallVector<const SCEV *, 4> MulOps; 6289 do { 6290 if (BO->Op) { 6291 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6292 MulOps.push_back(OpSCEV); 6293 break; 6294 } 6295 6296 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6297 if (Flags != SCEV::FlagAnyWrap) { 6298 MulOps.push_back( 6299 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6300 break; 6301 } 6302 } 6303 6304 MulOps.push_back(getSCEV(BO->RHS)); 6305 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6306 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6307 MulOps.push_back(getSCEV(BO->LHS)); 6308 break; 6309 } 6310 BO = NewBO; 6311 } while (true); 6312 6313 return getMulExpr(MulOps); 6314 } 6315 case Instruction::UDiv: 6316 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6317 case Instruction::URem: 6318 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6319 case Instruction::Sub: { 6320 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6321 if (BO->Op) 6322 Flags = getNoWrapFlagsFromUB(BO->Op); 6323 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6324 } 6325 case Instruction::And: 6326 // For an expression like x&255 that merely masks off the high bits, 6327 // use zext(trunc(x)) as the SCEV expression. 6328 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6329 if (CI->isZero()) 6330 return getSCEV(BO->RHS); 6331 if (CI->isMinusOne()) 6332 return getSCEV(BO->LHS); 6333 const APInt &A = CI->getValue(); 6334 6335 // Instcombine's ShrinkDemandedConstant may strip bits out of 6336 // constants, obscuring what would otherwise be a low-bits mask. 6337 // Use computeKnownBits to compute what ShrinkDemandedConstant 6338 // knew about to reconstruct a low-bits mask value. 6339 unsigned LZ = A.countLeadingZeros(); 6340 unsigned TZ = A.countTrailingZeros(); 6341 unsigned BitWidth = A.getBitWidth(); 6342 KnownBits Known(BitWidth); 6343 computeKnownBits(BO->LHS, Known, getDataLayout(), 6344 0, &AC, nullptr, &DT); 6345 6346 APInt EffectiveMask = 6347 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6348 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6349 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6350 const SCEV *LHS = getSCEV(BO->LHS); 6351 const SCEV *ShiftedLHS = nullptr; 6352 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6353 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6354 // For an expression like (x * 8) & 8, simplify the multiply. 6355 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6356 unsigned GCD = std::min(MulZeros, TZ); 6357 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6358 SmallVector<const SCEV*, 4> MulOps; 6359 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6360 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6361 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6362 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6363 } 6364 } 6365 if (!ShiftedLHS) 6366 ShiftedLHS = getUDivExpr(LHS, MulCount); 6367 return getMulExpr( 6368 getZeroExtendExpr( 6369 getTruncateExpr(ShiftedLHS, 6370 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6371 BO->LHS->getType()), 6372 MulCount); 6373 } 6374 } 6375 break; 6376 6377 case Instruction::Or: 6378 // If the RHS of the Or is a constant, we may have something like: 6379 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6380 // optimizations will transparently handle this case. 6381 // 6382 // In order for this transformation to be safe, the LHS must be of the 6383 // form X*(2^n) and the Or constant must be less than 2^n. 6384 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6385 const SCEV *LHS = getSCEV(BO->LHS); 6386 const APInt &CIVal = CI->getValue(); 6387 if (GetMinTrailingZeros(LHS) >= 6388 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6389 // Build a plain add SCEV. 6390 const SCEV *S = getAddExpr(LHS, getSCEV(CI)); 6391 // If the LHS of the add was an addrec and it has no-wrap flags, 6392 // transfer the no-wrap flags, since an or won't introduce a wrap. 6393 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) { 6394 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS); 6395 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags( 6396 OldAR->getNoWrapFlags()); 6397 } 6398 return S; 6399 } 6400 } 6401 break; 6402 6403 case Instruction::Xor: 6404 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6405 // If the RHS of xor is -1, then this is a not operation. 6406 if (CI->isMinusOne()) 6407 return getNotSCEV(getSCEV(BO->LHS)); 6408 6409 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6410 // This is a variant of the check for xor with -1, and it handles 6411 // the case where instcombine has trimmed non-demanded bits out 6412 // of an xor with -1. 6413 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6414 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6415 if (LBO->getOpcode() == Instruction::And && 6416 LCI->getValue() == CI->getValue()) 6417 if (const SCEVZeroExtendExpr *Z = 6418 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6419 Type *UTy = BO->LHS->getType(); 6420 const SCEV *Z0 = Z->getOperand(); 6421 Type *Z0Ty = Z0->getType(); 6422 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6423 6424 // If C is a low-bits mask, the zero extend is serving to 6425 // mask off the high bits. Complement the operand and 6426 // re-apply the zext. 6427 if (CI->getValue().isMask(Z0TySize)) 6428 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6429 6430 // If C is a single bit, it may be in the sign-bit position 6431 // before the zero-extend. In this case, represent the xor 6432 // using an add, which is equivalent, and re-apply the zext. 6433 APInt Trunc = CI->getValue().trunc(Z0TySize); 6434 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6435 Trunc.isSignMask()) 6436 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6437 UTy); 6438 } 6439 } 6440 break; 6441 6442 case Instruction::Shl: 6443 // Turn shift left of a constant amount into a multiply. 6444 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6445 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6446 6447 // If the shift count is not less than the bitwidth, the result of 6448 // the shift is undefined. Don't try to analyze it, because the 6449 // resolution chosen here may differ from the resolution chosen in 6450 // other parts of the compiler. 6451 if (SA->getValue().uge(BitWidth)) 6452 break; 6453 6454 // It is currently not resolved how to interpret NSW for left 6455 // shift by BitWidth - 1, so we avoid applying flags in that 6456 // case. Remove this check (or this comment) once the situation 6457 // is resolved. See 6458 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html 6459 // and http://reviews.llvm.org/D8890 . 6460 auto Flags = SCEV::FlagAnyWrap; 6461 if (BO->Op && SA->getValue().ult(BitWidth - 1)) 6462 Flags = getNoWrapFlagsFromUB(BO->Op); 6463 6464 Constant *X = ConstantInt::get( 6465 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6466 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6467 } 6468 break; 6469 6470 case Instruction::AShr: { 6471 // AShr X, C, where C is a constant. 6472 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6473 if (!CI) 6474 break; 6475 6476 Type *OuterTy = BO->LHS->getType(); 6477 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6478 // If the shift count is not less than the bitwidth, the result of 6479 // the shift is undefined. Don't try to analyze it, because the 6480 // resolution chosen here may differ from the resolution chosen in 6481 // other parts of the compiler. 6482 if (CI->getValue().uge(BitWidth)) 6483 break; 6484 6485 if (CI->isZero()) 6486 return getSCEV(BO->LHS); // shift by zero --> noop 6487 6488 uint64_t AShrAmt = CI->getZExtValue(); 6489 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6490 6491 Operator *L = dyn_cast<Operator>(BO->LHS); 6492 if (L && L->getOpcode() == Instruction::Shl) { 6493 // X = Shl A, n 6494 // Y = AShr X, m 6495 // Both n and m are constant. 6496 6497 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6498 if (L->getOperand(1) == BO->RHS) 6499 // For a two-shift sext-inreg, i.e. n = m, 6500 // use sext(trunc(x)) as the SCEV expression. 6501 return getSignExtendExpr( 6502 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6503 6504 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6505 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6506 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6507 if (ShlAmt > AShrAmt) { 6508 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6509 // expression. We already checked that ShlAmt < BitWidth, so 6510 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6511 // ShlAmt - AShrAmt < Amt. 6512 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6513 ShlAmt - AShrAmt); 6514 return getSignExtendExpr( 6515 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6516 getConstant(Mul)), OuterTy); 6517 } 6518 } 6519 } 6520 break; 6521 } 6522 } 6523 } 6524 6525 switch (U->getOpcode()) { 6526 case Instruction::Trunc: 6527 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6528 6529 case Instruction::ZExt: 6530 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6531 6532 case Instruction::SExt: 6533 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6534 // The NSW flag of a subtract does not always survive the conversion to 6535 // A + (-1)*B. By pushing sign extension onto its operands we are much 6536 // more likely to preserve NSW and allow later AddRec optimisations. 6537 // 6538 // NOTE: This is effectively duplicating this logic from getSignExtend: 6539 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6540 // but by that point the NSW information has potentially been lost. 6541 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6542 Type *Ty = U->getType(); 6543 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6544 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6545 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6546 } 6547 } 6548 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6549 6550 case Instruction::BitCast: 6551 // BitCasts are no-op casts so we just eliminate the cast. 6552 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6553 return getSCEV(U->getOperand(0)); 6554 break; 6555 6556 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can 6557 // lead to pointer expressions which cannot safely be expanded to GEPs, 6558 // because ScalarEvolution doesn't respect the GEP aliasing rules when 6559 // simplifying integer expressions. 6560 6561 case Instruction::GetElementPtr: 6562 return createNodeForGEP(cast<GEPOperator>(U)); 6563 6564 case Instruction::PHI: 6565 return createNodeForPHI(cast<PHINode>(U)); 6566 6567 case Instruction::Select: 6568 // U can also be a select constant expr, which let fall through. Since 6569 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6570 // constant expressions cannot have instructions as operands, we'd have 6571 // returned getUnknown for a select constant expressions anyway. 6572 if (isa<Instruction>(U)) 6573 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6574 U->getOperand(1), U->getOperand(2)); 6575 break; 6576 6577 case Instruction::Call: 6578 case Instruction::Invoke: 6579 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6580 return getSCEV(RV); 6581 break; 6582 } 6583 6584 return getUnknown(V); 6585 } 6586 6587 //===----------------------------------------------------------------------===// 6588 // Iteration Count Computation Code 6589 // 6590 6591 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6592 if (!ExitCount) 6593 return 0; 6594 6595 ConstantInt *ExitConst = ExitCount->getValue(); 6596 6597 // Guard against huge trip counts. 6598 if (ExitConst->getValue().getActiveBits() > 32) 6599 return 0; 6600 6601 // In case of integer overflow, this returns 0, which is correct. 6602 return ((unsigned)ExitConst->getZExtValue()) + 1; 6603 } 6604 6605 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6606 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6607 return getSmallConstantTripCount(L, ExitingBB); 6608 6609 // No trip count information for multiple exits. 6610 return 0; 6611 } 6612 6613 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6614 BasicBlock *ExitingBlock) { 6615 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6616 assert(L->isLoopExiting(ExitingBlock) && 6617 "Exiting block must actually branch out of the loop!"); 6618 const SCEVConstant *ExitCount = 6619 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6620 return getConstantTripCount(ExitCount); 6621 } 6622 6623 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6624 const auto *MaxExitCount = 6625 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6626 return getConstantTripCount(MaxExitCount); 6627 } 6628 6629 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6630 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6631 return getSmallConstantTripMultiple(L, ExitingBB); 6632 6633 // No trip multiple information for multiple exits. 6634 return 0; 6635 } 6636 6637 /// Returns the largest constant divisor of the trip count of this loop as a 6638 /// normal unsigned value, if possible. This means that the actual trip count is 6639 /// always a multiple of the returned value (don't forget the trip count could 6640 /// very well be zero as well!). 6641 /// 6642 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6643 /// multiple of a constant (which is also the case if the trip count is simply 6644 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6645 /// if the trip count is very large (>= 2^32). 6646 /// 6647 /// As explained in the comments for getSmallConstantTripCount, this assumes 6648 /// that control exits the loop via ExitingBlock. 6649 unsigned 6650 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6651 BasicBlock *ExitingBlock) { 6652 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6653 assert(L->isLoopExiting(ExitingBlock) && 6654 "Exiting block must actually branch out of the loop!"); 6655 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6656 if (ExitCount == getCouldNotCompute()) 6657 return 1; 6658 6659 // Get the trip count from the BE count by adding 1. 6660 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6661 6662 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6663 if (!TC) 6664 // Attempt to factor more general cases. Returns the greatest power of 6665 // two divisor. If overflow happens, the trip count expression is still 6666 // divisible by the greatest power of 2 divisor returned. 6667 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6668 6669 ConstantInt *Result = TC->getValue(); 6670 6671 // Guard against huge trip counts (this requires checking 6672 // for zero to handle the case where the trip count == -1 and the 6673 // addition wraps). 6674 if (!Result || Result->getValue().getActiveBits() > 32 || 6675 Result->getValue().getActiveBits() == 0) 6676 return 1; 6677 6678 return (unsigned)Result->getZExtValue(); 6679 } 6680 6681 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6682 BasicBlock *ExitingBlock, 6683 ExitCountKind Kind) { 6684 switch (Kind) { 6685 case Exact: 6686 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6687 case ConstantMaximum: 6688 return getBackedgeTakenInfo(L).getMax(ExitingBlock, this); 6689 }; 6690 llvm_unreachable("Invalid ExitCountKind!"); 6691 } 6692 6693 const SCEV * 6694 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6695 SCEVUnionPredicate &Preds) { 6696 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6697 } 6698 6699 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6700 ExitCountKind Kind) { 6701 switch (Kind) { 6702 case Exact: 6703 return getBackedgeTakenInfo(L).getExact(L, this); 6704 case ConstantMaximum: 6705 return getBackedgeTakenInfo(L).getMax(this); 6706 }; 6707 llvm_unreachable("Invalid ExitCountKind!"); 6708 } 6709 6710 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6711 return getBackedgeTakenInfo(L).isMaxOrZero(this); 6712 } 6713 6714 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6715 static void 6716 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6717 BasicBlock *Header = L->getHeader(); 6718 6719 // Push all Loop-header PHIs onto the Worklist stack. 6720 for (PHINode &PN : Header->phis()) 6721 Worklist.push_back(&PN); 6722 } 6723 6724 const ScalarEvolution::BackedgeTakenInfo & 6725 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6726 auto &BTI = getBackedgeTakenInfo(L); 6727 if (BTI.hasFullInfo()) 6728 return BTI; 6729 6730 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6731 6732 if (!Pair.second) 6733 return Pair.first->second; 6734 6735 BackedgeTakenInfo Result = 6736 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6737 6738 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6739 } 6740 6741 const ScalarEvolution::BackedgeTakenInfo & 6742 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6743 // Initially insert an invalid entry for this loop. If the insertion 6744 // succeeds, proceed to actually compute a backedge-taken count and 6745 // update the value. The temporary CouldNotCompute value tells SCEV 6746 // code elsewhere that it shouldn't attempt to request a new 6747 // backedge-taken count, which could result in infinite recursion. 6748 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6749 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6750 if (!Pair.second) 6751 return Pair.first->second; 6752 6753 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6754 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6755 // must be cleared in this scope. 6756 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6757 6758 // In product build, there are no usage of statistic. 6759 (void)NumTripCountsComputed; 6760 (void)NumTripCountsNotComputed; 6761 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6762 const SCEV *BEExact = Result.getExact(L, this); 6763 if (BEExact != getCouldNotCompute()) { 6764 assert(isLoopInvariant(BEExact, L) && 6765 isLoopInvariant(Result.getMax(this), L) && 6766 "Computed backedge-taken count isn't loop invariant for loop!"); 6767 ++NumTripCountsComputed; 6768 } 6769 else if (Result.getMax(this) == getCouldNotCompute() && 6770 isa<PHINode>(L->getHeader()->begin())) { 6771 // Only count loops that have phi nodes as not being computable. 6772 ++NumTripCountsNotComputed; 6773 } 6774 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6775 6776 // Now that we know more about the trip count for this loop, forget any 6777 // existing SCEV values for PHI nodes in this loop since they are only 6778 // conservative estimates made without the benefit of trip count 6779 // information. This is similar to the code in forgetLoop, except that 6780 // it handles SCEVUnknown PHI nodes specially. 6781 if (Result.hasAnyInfo()) { 6782 SmallVector<Instruction *, 16> Worklist; 6783 PushLoopPHIs(L, Worklist); 6784 6785 SmallPtrSet<Instruction *, 8> Discovered; 6786 while (!Worklist.empty()) { 6787 Instruction *I = Worklist.pop_back_val(); 6788 6789 ValueExprMapType::iterator It = 6790 ValueExprMap.find_as(static_cast<Value *>(I)); 6791 if (It != ValueExprMap.end()) { 6792 const SCEV *Old = It->second; 6793 6794 // SCEVUnknown for a PHI either means that it has an unrecognized 6795 // structure, or it's a PHI that's in the progress of being computed 6796 // by createNodeForPHI. In the former case, additional loop trip 6797 // count information isn't going to change anything. In the later 6798 // case, createNodeForPHI will perform the necessary updates on its 6799 // own when it gets to that point. 6800 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6801 eraseValueFromMap(It->first); 6802 forgetMemoizedResults(Old); 6803 } 6804 if (PHINode *PN = dyn_cast<PHINode>(I)) 6805 ConstantEvolutionLoopExitValue.erase(PN); 6806 } 6807 6808 // Since we don't need to invalidate anything for correctness and we're 6809 // only invalidating to make SCEV's results more precise, we get to stop 6810 // early to avoid invalidating too much. This is especially important in 6811 // cases like: 6812 // 6813 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6814 // loop0: 6815 // %pn0 = phi 6816 // ... 6817 // loop1: 6818 // %pn1 = phi 6819 // ... 6820 // 6821 // where both loop0 and loop1's backedge taken count uses the SCEV 6822 // expression for %v. If we don't have the early stop below then in cases 6823 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6824 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6825 // count for loop1, effectively nullifying SCEV's trip count cache. 6826 for (auto *U : I->users()) 6827 if (auto *I = dyn_cast<Instruction>(U)) { 6828 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6829 if (LoopForUser && L->contains(LoopForUser) && 6830 Discovered.insert(I).second) 6831 Worklist.push_back(I); 6832 } 6833 } 6834 } 6835 6836 // Re-lookup the insert position, since the call to 6837 // computeBackedgeTakenCount above could result in a 6838 // recusive call to getBackedgeTakenInfo (on a different 6839 // loop), which would invalidate the iterator computed 6840 // earlier. 6841 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6842 } 6843 6844 void ScalarEvolution::forgetAllLoops() { 6845 // This method is intended to forget all info about loops. It should 6846 // invalidate caches as if the following happened: 6847 // - The trip counts of all loops have changed arbitrarily 6848 // - Every llvm::Value has been updated in place to produce a different 6849 // result. 6850 BackedgeTakenCounts.clear(); 6851 PredicatedBackedgeTakenCounts.clear(); 6852 LoopPropertiesCache.clear(); 6853 ConstantEvolutionLoopExitValue.clear(); 6854 ValueExprMap.clear(); 6855 ValuesAtScopes.clear(); 6856 LoopDispositions.clear(); 6857 BlockDispositions.clear(); 6858 UnsignedRanges.clear(); 6859 SignedRanges.clear(); 6860 ExprValueMap.clear(); 6861 HasRecMap.clear(); 6862 MinTrailingZerosCache.clear(); 6863 PredicatedSCEVRewrites.clear(); 6864 } 6865 6866 void ScalarEvolution::forgetLoop(const Loop *L) { 6867 // Drop any stored trip count value. 6868 auto RemoveLoopFromBackedgeMap = 6869 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6870 auto BTCPos = Map.find(L); 6871 if (BTCPos != Map.end()) { 6872 BTCPos->second.clear(); 6873 Map.erase(BTCPos); 6874 } 6875 }; 6876 6877 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6878 SmallVector<Instruction *, 32> Worklist; 6879 SmallPtrSet<Instruction *, 16> Visited; 6880 6881 // Iterate over all the loops and sub-loops to drop SCEV information. 6882 while (!LoopWorklist.empty()) { 6883 auto *CurrL = LoopWorklist.pop_back_val(); 6884 6885 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6886 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6887 6888 // Drop information about predicated SCEV rewrites for this loop. 6889 for (auto I = PredicatedSCEVRewrites.begin(); 6890 I != PredicatedSCEVRewrites.end();) { 6891 std::pair<const SCEV *, const Loop *> Entry = I->first; 6892 if (Entry.second == CurrL) 6893 PredicatedSCEVRewrites.erase(I++); 6894 else 6895 ++I; 6896 } 6897 6898 auto LoopUsersItr = LoopUsers.find(CurrL); 6899 if (LoopUsersItr != LoopUsers.end()) { 6900 for (auto *S : LoopUsersItr->second) 6901 forgetMemoizedResults(S); 6902 LoopUsers.erase(LoopUsersItr); 6903 } 6904 6905 // Drop information about expressions based on loop-header PHIs. 6906 PushLoopPHIs(CurrL, Worklist); 6907 6908 while (!Worklist.empty()) { 6909 Instruction *I = Worklist.pop_back_val(); 6910 if (!Visited.insert(I).second) 6911 continue; 6912 6913 ValueExprMapType::iterator It = 6914 ValueExprMap.find_as(static_cast<Value *>(I)); 6915 if (It != ValueExprMap.end()) { 6916 eraseValueFromMap(It->first); 6917 forgetMemoizedResults(It->second); 6918 if (PHINode *PN = dyn_cast<PHINode>(I)) 6919 ConstantEvolutionLoopExitValue.erase(PN); 6920 } 6921 6922 PushDefUseChildren(I, Worklist); 6923 } 6924 6925 LoopPropertiesCache.erase(CurrL); 6926 // Forget all contained loops too, to avoid dangling entries in the 6927 // ValuesAtScopes map. 6928 LoopWorklist.append(CurrL->begin(), CurrL->end()); 6929 } 6930 } 6931 6932 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 6933 while (Loop *Parent = L->getParentLoop()) 6934 L = Parent; 6935 forgetLoop(L); 6936 } 6937 6938 void ScalarEvolution::forgetValue(Value *V) { 6939 Instruction *I = dyn_cast<Instruction>(V); 6940 if (!I) return; 6941 6942 // Drop information about expressions based on loop-header PHIs. 6943 SmallVector<Instruction *, 16> Worklist; 6944 Worklist.push_back(I); 6945 6946 SmallPtrSet<Instruction *, 8> Visited; 6947 while (!Worklist.empty()) { 6948 I = Worklist.pop_back_val(); 6949 if (!Visited.insert(I).second) 6950 continue; 6951 6952 ValueExprMapType::iterator It = 6953 ValueExprMap.find_as(static_cast<Value *>(I)); 6954 if (It != ValueExprMap.end()) { 6955 eraseValueFromMap(It->first); 6956 forgetMemoizedResults(It->second); 6957 if (PHINode *PN = dyn_cast<PHINode>(I)) 6958 ConstantEvolutionLoopExitValue.erase(PN); 6959 } 6960 6961 PushDefUseChildren(I, Worklist); 6962 } 6963 } 6964 6965 /// Get the exact loop backedge taken count considering all loop exits. A 6966 /// computable result can only be returned for loops with all exiting blocks 6967 /// dominating the latch. howFarToZero assumes that the limit of each loop test 6968 /// is never skipped. This is a valid assumption as long as the loop exits via 6969 /// that test. For precise results, it is the caller's responsibility to specify 6970 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 6971 const SCEV * 6972 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 6973 SCEVUnionPredicate *Preds) const { 6974 // If any exits were not computable, the loop is not computable. 6975 if (!isComplete() || ExitNotTaken.empty()) 6976 return SE->getCouldNotCompute(); 6977 6978 const BasicBlock *Latch = L->getLoopLatch(); 6979 // All exiting blocks we have collected must dominate the only backedge. 6980 if (!Latch) 6981 return SE->getCouldNotCompute(); 6982 6983 // All exiting blocks we have gathered dominate loop's latch, so exact trip 6984 // count is simply a minimum out of all these calculated exit counts. 6985 SmallVector<const SCEV *, 2> Ops; 6986 for (auto &ENT : ExitNotTaken) { 6987 const SCEV *BECount = ENT.ExactNotTaken; 6988 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 6989 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 6990 "We should only have known counts for exiting blocks that dominate " 6991 "latch!"); 6992 6993 Ops.push_back(BECount); 6994 6995 if (Preds && !ENT.hasAlwaysTruePredicate()) 6996 Preds->add(ENT.Predicate.get()); 6997 6998 assert((Preds || ENT.hasAlwaysTruePredicate()) && 6999 "Predicate should be always true!"); 7000 } 7001 7002 return SE->getUMinFromMismatchedTypes(Ops); 7003 } 7004 7005 /// Get the exact not taken count for this loop exit. 7006 const SCEV * 7007 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock, 7008 ScalarEvolution *SE) const { 7009 for (auto &ENT : ExitNotTaken) 7010 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7011 return ENT.ExactNotTaken; 7012 7013 return SE->getCouldNotCompute(); 7014 } 7015 7016 const SCEV * 7017 ScalarEvolution::BackedgeTakenInfo::getMax(BasicBlock *ExitingBlock, 7018 ScalarEvolution *SE) const { 7019 for (auto &ENT : ExitNotTaken) 7020 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7021 return ENT.MaxNotTaken; 7022 7023 return SE->getCouldNotCompute(); 7024 } 7025 7026 /// getMax - Get the max backedge taken count for the loop. 7027 const SCEV * 7028 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const { 7029 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7030 return !ENT.hasAlwaysTruePredicate(); 7031 }; 7032 7033 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax()) 7034 return SE->getCouldNotCompute(); 7035 7036 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) && 7037 "No point in having a non-constant max backedge taken count!"); 7038 return getMax(); 7039 } 7040 7041 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const { 7042 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7043 return !ENT.hasAlwaysTruePredicate(); 7044 }; 7045 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7046 } 7047 7048 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 7049 ScalarEvolution *SE) const { 7050 if (getMax() && getMax() != SE->getCouldNotCompute() && 7051 SE->hasOperand(getMax(), S)) 7052 return true; 7053 7054 for (auto &ENT : ExitNotTaken) 7055 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 7056 SE->hasOperand(ENT.ExactNotTaken, S)) 7057 return true; 7058 7059 return false; 7060 } 7061 7062 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7063 : ExactNotTaken(E), MaxNotTaken(E) { 7064 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7065 isa<SCEVConstant>(MaxNotTaken)) && 7066 "No point in having a non-constant max backedge taken count!"); 7067 } 7068 7069 ScalarEvolution::ExitLimit::ExitLimit( 7070 const SCEV *E, const SCEV *M, bool MaxOrZero, 7071 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7072 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7073 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7074 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7075 "Exact is not allowed to be less precise than Max"); 7076 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7077 isa<SCEVConstant>(MaxNotTaken)) && 7078 "No point in having a non-constant max backedge taken count!"); 7079 for (auto *PredSet : PredSetList) 7080 for (auto *P : *PredSet) 7081 addPredicate(P); 7082 } 7083 7084 ScalarEvolution::ExitLimit::ExitLimit( 7085 const SCEV *E, const SCEV *M, bool MaxOrZero, 7086 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7087 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7088 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7089 isa<SCEVConstant>(MaxNotTaken)) && 7090 "No point in having a non-constant max backedge taken count!"); 7091 } 7092 7093 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7094 bool MaxOrZero) 7095 : ExitLimit(E, M, MaxOrZero, None) { 7096 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7097 isa<SCEVConstant>(MaxNotTaken)) && 7098 "No point in having a non-constant max backedge taken count!"); 7099 } 7100 7101 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7102 /// computable exit into a persistent ExitNotTakenInfo array. 7103 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7104 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> 7105 ExitCounts, 7106 bool Complete, const SCEV *MaxCount, bool MaxOrZero) 7107 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) { 7108 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7109 7110 ExitNotTaken.reserve(ExitCounts.size()); 7111 std::transform( 7112 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7113 [&](const EdgeExitInfo &EEI) { 7114 BasicBlock *ExitBB = EEI.first; 7115 const ExitLimit &EL = EEI.second; 7116 if (EL.Predicates.empty()) 7117 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7118 nullptr); 7119 7120 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7121 for (auto *Pred : EL.Predicates) 7122 Predicate->add(Pred); 7123 7124 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7125 std::move(Predicate)); 7126 }); 7127 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) && 7128 "No point in having a non-constant max backedge taken count!"); 7129 } 7130 7131 /// Invalidate this result and free the ExitNotTakenInfo array. 7132 void ScalarEvolution::BackedgeTakenInfo::clear() { 7133 ExitNotTaken.clear(); 7134 } 7135 7136 /// Compute the number of times the backedge of the specified loop will execute. 7137 ScalarEvolution::BackedgeTakenInfo 7138 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7139 bool AllowPredicates) { 7140 SmallVector<BasicBlock *, 8> ExitingBlocks; 7141 L->getExitingBlocks(ExitingBlocks); 7142 7143 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7144 7145 SmallVector<EdgeExitInfo, 4> ExitCounts; 7146 bool CouldComputeBECount = true; 7147 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7148 const SCEV *MustExitMaxBECount = nullptr; 7149 const SCEV *MayExitMaxBECount = nullptr; 7150 bool MustExitMaxOrZero = false; 7151 7152 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7153 // and compute maxBECount. 7154 // Do a union of all the predicates here. 7155 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7156 BasicBlock *ExitBB = ExitingBlocks[i]; 7157 7158 // We canonicalize untaken exits to br (constant), ignore them so that 7159 // proving an exit untaken doesn't negatively impact our ability to reason 7160 // about the loop as whole. 7161 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7162 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7163 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7164 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7165 continue; 7166 } 7167 7168 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7169 7170 assert((AllowPredicates || EL.Predicates.empty()) && 7171 "Predicated exit limit when predicates are not allowed!"); 7172 7173 // 1. For each exit that can be computed, add an entry to ExitCounts. 7174 // CouldComputeBECount is true only if all exits can be computed. 7175 if (EL.ExactNotTaken == getCouldNotCompute()) 7176 // We couldn't compute an exact value for this exit, so 7177 // we won't be able to compute an exact value for the loop. 7178 CouldComputeBECount = false; 7179 else 7180 ExitCounts.emplace_back(ExitBB, EL); 7181 7182 // 2. Derive the loop's MaxBECount from each exit's max number of 7183 // non-exiting iterations. Partition the loop exits into two kinds: 7184 // LoopMustExits and LoopMayExits. 7185 // 7186 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7187 // is a LoopMayExit. If any computable LoopMustExit is found, then 7188 // MaxBECount is the minimum EL.MaxNotTaken of computable 7189 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7190 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7191 // computable EL.MaxNotTaken. 7192 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7193 DT.dominates(ExitBB, Latch)) { 7194 if (!MustExitMaxBECount) { 7195 MustExitMaxBECount = EL.MaxNotTaken; 7196 MustExitMaxOrZero = EL.MaxOrZero; 7197 } else { 7198 MustExitMaxBECount = 7199 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7200 } 7201 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7202 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7203 MayExitMaxBECount = EL.MaxNotTaken; 7204 else { 7205 MayExitMaxBECount = 7206 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7207 } 7208 } 7209 } 7210 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7211 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7212 // The loop backedge will be taken the maximum or zero times if there's 7213 // a single exit that must be taken the maximum or zero times. 7214 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7215 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7216 MaxBECount, MaxOrZero); 7217 } 7218 7219 ScalarEvolution::ExitLimit 7220 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7221 bool AllowPredicates) { 7222 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7223 // If our exiting block does not dominate the latch, then its connection with 7224 // loop's exit limit may be far from trivial. 7225 const BasicBlock *Latch = L->getLoopLatch(); 7226 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7227 return getCouldNotCompute(); 7228 7229 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7230 Instruction *Term = ExitingBlock->getTerminator(); 7231 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7232 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7233 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7234 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7235 "It should have one successor in loop and one exit block!"); 7236 // Proceed to the next level to examine the exit condition expression. 7237 return computeExitLimitFromCond( 7238 L, BI->getCondition(), ExitIfTrue, 7239 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7240 } 7241 7242 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7243 // For switch, make sure that there is a single exit from the loop. 7244 BasicBlock *Exit = nullptr; 7245 for (auto *SBB : successors(ExitingBlock)) 7246 if (!L->contains(SBB)) { 7247 if (Exit) // Multiple exit successors. 7248 return getCouldNotCompute(); 7249 Exit = SBB; 7250 } 7251 assert(Exit && "Exiting block must have at least one exit"); 7252 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7253 /*ControlsExit=*/IsOnlyExit); 7254 } 7255 7256 return getCouldNotCompute(); 7257 } 7258 7259 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7260 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7261 bool ControlsExit, bool AllowPredicates) { 7262 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7263 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7264 ControlsExit, AllowPredicates); 7265 } 7266 7267 Optional<ScalarEvolution::ExitLimit> 7268 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7269 bool ExitIfTrue, bool ControlsExit, 7270 bool AllowPredicates) { 7271 (void)this->L; 7272 (void)this->ExitIfTrue; 7273 (void)this->AllowPredicates; 7274 7275 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7276 this->AllowPredicates == AllowPredicates && 7277 "Variance in assumed invariant key components!"); 7278 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7279 if (Itr == TripCountMap.end()) 7280 return None; 7281 return Itr->second; 7282 } 7283 7284 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7285 bool ExitIfTrue, 7286 bool ControlsExit, 7287 bool AllowPredicates, 7288 const ExitLimit &EL) { 7289 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7290 this->AllowPredicates == AllowPredicates && 7291 "Variance in assumed invariant key components!"); 7292 7293 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7294 assert(InsertResult.second && "Expected successful insertion!"); 7295 (void)InsertResult; 7296 (void)ExitIfTrue; 7297 } 7298 7299 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7300 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7301 bool ControlsExit, bool AllowPredicates) { 7302 7303 if (auto MaybeEL = 7304 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7305 return *MaybeEL; 7306 7307 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7308 ControlsExit, AllowPredicates); 7309 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7310 return EL; 7311 } 7312 7313 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7314 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7315 bool ControlsExit, bool AllowPredicates) { 7316 // Check if the controlling expression for this loop is an And or Or. 7317 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7318 if (BO->getOpcode() == Instruction::And) { 7319 // Recurse on the operands of the and. 7320 bool EitherMayExit = !ExitIfTrue; 7321 ExitLimit EL0 = computeExitLimitFromCondCached( 7322 Cache, L, BO->getOperand(0), ExitIfTrue, 7323 ControlsExit && !EitherMayExit, AllowPredicates); 7324 ExitLimit EL1 = computeExitLimitFromCondCached( 7325 Cache, L, BO->getOperand(1), ExitIfTrue, 7326 ControlsExit && !EitherMayExit, AllowPredicates); 7327 // Be robust against unsimplified IR for the form "and i1 X, true" 7328 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7329 return CI->isOne() ? EL0 : EL1; 7330 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7331 return CI->isOne() ? EL1 : EL0; 7332 const SCEV *BECount = getCouldNotCompute(); 7333 const SCEV *MaxBECount = getCouldNotCompute(); 7334 if (EitherMayExit) { 7335 // Both conditions must be true for the loop to continue executing. 7336 // Choose the less conservative count. 7337 if (EL0.ExactNotTaken == getCouldNotCompute() || 7338 EL1.ExactNotTaken == getCouldNotCompute()) 7339 BECount = getCouldNotCompute(); 7340 else 7341 BECount = 7342 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7343 if (EL0.MaxNotTaken == getCouldNotCompute()) 7344 MaxBECount = EL1.MaxNotTaken; 7345 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7346 MaxBECount = EL0.MaxNotTaken; 7347 else 7348 MaxBECount = 7349 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7350 } else { 7351 // Both conditions must be true at the same time for the loop to exit. 7352 // For now, be conservative. 7353 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7354 MaxBECount = EL0.MaxNotTaken; 7355 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7356 BECount = EL0.ExactNotTaken; 7357 } 7358 7359 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7360 // to be more aggressive when computing BECount than when computing 7361 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7362 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7363 // to not. 7364 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7365 !isa<SCEVCouldNotCompute>(BECount)) 7366 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7367 7368 return ExitLimit(BECount, MaxBECount, false, 7369 {&EL0.Predicates, &EL1.Predicates}); 7370 } 7371 if (BO->getOpcode() == Instruction::Or) { 7372 // Recurse on the operands of the or. 7373 bool EitherMayExit = ExitIfTrue; 7374 ExitLimit EL0 = computeExitLimitFromCondCached( 7375 Cache, L, BO->getOperand(0), ExitIfTrue, 7376 ControlsExit && !EitherMayExit, AllowPredicates); 7377 ExitLimit EL1 = computeExitLimitFromCondCached( 7378 Cache, L, BO->getOperand(1), ExitIfTrue, 7379 ControlsExit && !EitherMayExit, AllowPredicates); 7380 // Be robust against unsimplified IR for the form "or i1 X, true" 7381 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7382 return CI->isZero() ? EL0 : EL1; 7383 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7384 return CI->isZero() ? EL1 : EL0; 7385 const SCEV *BECount = getCouldNotCompute(); 7386 const SCEV *MaxBECount = getCouldNotCompute(); 7387 if (EitherMayExit) { 7388 // Both conditions must be false for the loop to continue executing. 7389 // Choose the less conservative count. 7390 if (EL0.ExactNotTaken == getCouldNotCompute() || 7391 EL1.ExactNotTaken == getCouldNotCompute()) 7392 BECount = getCouldNotCompute(); 7393 else 7394 BECount = 7395 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7396 if (EL0.MaxNotTaken == getCouldNotCompute()) 7397 MaxBECount = EL1.MaxNotTaken; 7398 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7399 MaxBECount = EL0.MaxNotTaken; 7400 else 7401 MaxBECount = 7402 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7403 } else { 7404 // Both conditions must be false at the same time for the loop to exit. 7405 // For now, be conservative. 7406 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7407 MaxBECount = EL0.MaxNotTaken; 7408 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7409 BECount = EL0.ExactNotTaken; 7410 } 7411 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7412 // to be more aggressive when computing BECount than when computing 7413 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7414 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7415 // to not. 7416 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7417 !isa<SCEVCouldNotCompute>(BECount)) 7418 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7419 7420 return ExitLimit(BECount, MaxBECount, false, 7421 {&EL0.Predicates, &EL1.Predicates}); 7422 } 7423 } 7424 7425 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7426 // Proceed to the next level to examine the icmp. 7427 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7428 ExitLimit EL = 7429 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7430 if (EL.hasFullInfo() || !AllowPredicates) 7431 return EL; 7432 7433 // Try again, but use SCEV predicates this time. 7434 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7435 /*AllowPredicates=*/true); 7436 } 7437 7438 // Check for a constant condition. These are normally stripped out by 7439 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7440 // preserve the CFG and is temporarily leaving constant conditions 7441 // in place. 7442 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7443 if (ExitIfTrue == !CI->getZExtValue()) 7444 // The backedge is always taken. 7445 return getCouldNotCompute(); 7446 else 7447 // The backedge is never taken. 7448 return getZero(CI->getType()); 7449 } 7450 7451 // If it's not an integer or pointer comparison then compute it the hard way. 7452 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7453 } 7454 7455 ScalarEvolution::ExitLimit 7456 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7457 ICmpInst *ExitCond, 7458 bool ExitIfTrue, 7459 bool ControlsExit, 7460 bool AllowPredicates) { 7461 // If the condition was exit on true, convert the condition to exit on false 7462 ICmpInst::Predicate Pred; 7463 if (!ExitIfTrue) 7464 Pred = ExitCond->getPredicate(); 7465 else 7466 Pred = ExitCond->getInversePredicate(); 7467 const ICmpInst::Predicate OriginalPred = Pred; 7468 7469 // Handle common loops like: for (X = "string"; *X; ++X) 7470 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7471 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7472 ExitLimit ItCnt = 7473 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7474 if (ItCnt.hasAnyInfo()) 7475 return ItCnt; 7476 } 7477 7478 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7479 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7480 7481 // Try to evaluate any dependencies out of the loop. 7482 LHS = getSCEVAtScope(LHS, L); 7483 RHS = getSCEVAtScope(RHS, L); 7484 7485 // At this point, we would like to compute how many iterations of the 7486 // loop the predicate will return true for these inputs. 7487 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7488 // If there is a loop-invariant, force it into the RHS. 7489 std::swap(LHS, RHS); 7490 Pred = ICmpInst::getSwappedPredicate(Pred); 7491 } 7492 7493 // Simplify the operands before analyzing them. 7494 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7495 7496 // If we have a comparison of a chrec against a constant, try to use value 7497 // ranges to answer this query. 7498 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7499 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7500 if (AddRec->getLoop() == L) { 7501 // Form the constant range. 7502 ConstantRange CompRange = 7503 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7504 7505 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7506 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7507 } 7508 7509 switch (Pred) { 7510 case ICmpInst::ICMP_NE: { // while (X != Y) 7511 // Convert to: while (X-Y != 0) 7512 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7513 AllowPredicates); 7514 if (EL.hasAnyInfo()) return EL; 7515 break; 7516 } 7517 case ICmpInst::ICMP_EQ: { // while (X == Y) 7518 // Convert to: while (X-Y == 0) 7519 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7520 if (EL.hasAnyInfo()) return EL; 7521 break; 7522 } 7523 case ICmpInst::ICMP_SLT: 7524 case ICmpInst::ICMP_ULT: { // while (X < Y) 7525 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7526 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7527 AllowPredicates); 7528 if (EL.hasAnyInfo()) return EL; 7529 break; 7530 } 7531 case ICmpInst::ICMP_SGT: 7532 case ICmpInst::ICMP_UGT: { // while (X > Y) 7533 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7534 ExitLimit EL = 7535 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7536 AllowPredicates); 7537 if (EL.hasAnyInfo()) return EL; 7538 break; 7539 } 7540 default: 7541 break; 7542 } 7543 7544 auto *ExhaustiveCount = 7545 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7546 7547 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7548 return ExhaustiveCount; 7549 7550 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7551 ExitCond->getOperand(1), L, OriginalPred); 7552 } 7553 7554 ScalarEvolution::ExitLimit 7555 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7556 SwitchInst *Switch, 7557 BasicBlock *ExitingBlock, 7558 bool ControlsExit) { 7559 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7560 7561 // Give up if the exit is the default dest of a switch. 7562 if (Switch->getDefaultDest() == ExitingBlock) 7563 return getCouldNotCompute(); 7564 7565 assert(L->contains(Switch->getDefaultDest()) && 7566 "Default case must not exit the loop!"); 7567 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7568 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7569 7570 // while (X != Y) --> while (X-Y != 0) 7571 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7572 if (EL.hasAnyInfo()) 7573 return EL; 7574 7575 return getCouldNotCompute(); 7576 } 7577 7578 static ConstantInt * 7579 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7580 ScalarEvolution &SE) { 7581 const SCEV *InVal = SE.getConstant(C); 7582 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7583 assert(isa<SCEVConstant>(Val) && 7584 "Evaluation of SCEV at constant didn't fold correctly?"); 7585 return cast<SCEVConstant>(Val)->getValue(); 7586 } 7587 7588 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7589 /// compute the backedge execution count. 7590 ScalarEvolution::ExitLimit 7591 ScalarEvolution::computeLoadConstantCompareExitLimit( 7592 LoadInst *LI, 7593 Constant *RHS, 7594 const Loop *L, 7595 ICmpInst::Predicate predicate) { 7596 if (LI->isVolatile()) return getCouldNotCompute(); 7597 7598 // Check to see if the loaded pointer is a getelementptr of a global. 7599 // TODO: Use SCEV instead of manually grubbing with GEPs. 7600 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7601 if (!GEP) return getCouldNotCompute(); 7602 7603 // Make sure that it is really a constant global we are gepping, with an 7604 // initializer, and make sure the first IDX is really 0. 7605 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7606 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7607 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7608 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7609 return getCouldNotCompute(); 7610 7611 // Okay, we allow one non-constant index into the GEP instruction. 7612 Value *VarIdx = nullptr; 7613 std::vector<Constant*> Indexes; 7614 unsigned VarIdxNum = 0; 7615 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7616 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7617 Indexes.push_back(CI); 7618 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7619 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7620 VarIdx = GEP->getOperand(i); 7621 VarIdxNum = i-2; 7622 Indexes.push_back(nullptr); 7623 } 7624 7625 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7626 if (!VarIdx) 7627 return getCouldNotCompute(); 7628 7629 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7630 // Check to see if X is a loop variant variable value now. 7631 const SCEV *Idx = getSCEV(VarIdx); 7632 Idx = getSCEVAtScope(Idx, L); 7633 7634 // We can only recognize very limited forms of loop index expressions, in 7635 // particular, only affine AddRec's like {C1,+,C2}. 7636 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7637 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7638 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7639 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7640 return getCouldNotCompute(); 7641 7642 unsigned MaxSteps = MaxBruteForceIterations; 7643 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7644 ConstantInt *ItCst = ConstantInt::get( 7645 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7646 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7647 7648 // Form the GEP offset. 7649 Indexes[VarIdxNum] = Val; 7650 7651 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7652 Indexes); 7653 if (!Result) break; // Cannot compute! 7654 7655 // Evaluate the condition for this iteration. 7656 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7657 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7658 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7659 ++NumArrayLenItCounts; 7660 return getConstant(ItCst); // Found terminating iteration! 7661 } 7662 } 7663 return getCouldNotCompute(); 7664 } 7665 7666 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7667 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7668 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7669 if (!RHS) 7670 return getCouldNotCompute(); 7671 7672 const BasicBlock *Latch = L->getLoopLatch(); 7673 if (!Latch) 7674 return getCouldNotCompute(); 7675 7676 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7677 if (!Predecessor) 7678 return getCouldNotCompute(); 7679 7680 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7681 // Return LHS in OutLHS and shift_opt in OutOpCode. 7682 auto MatchPositiveShift = 7683 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7684 7685 using namespace PatternMatch; 7686 7687 ConstantInt *ShiftAmt; 7688 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7689 OutOpCode = Instruction::LShr; 7690 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7691 OutOpCode = Instruction::AShr; 7692 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7693 OutOpCode = Instruction::Shl; 7694 else 7695 return false; 7696 7697 return ShiftAmt->getValue().isStrictlyPositive(); 7698 }; 7699 7700 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7701 // 7702 // loop: 7703 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7704 // %iv.shifted = lshr i32 %iv, <positive constant> 7705 // 7706 // Return true on a successful match. Return the corresponding PHI node (%iv 7707 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7708 auto MatchShiftRecurrence = 7709 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7710 Optional<Instruction::BinaryOps> PostShiftOpCode; 7711 7712 { 7713 Instruction::BinaryOps OpC; 7714 Value *V; 7715 7716 // If we encounter a shift instruction, "peel off" the shift operation, 7717 // and remember that we did so. Later when we inspect %iv's backedge 7718 // value, we will make sure that the backedge value uses the same 7719 // operation. 7720 // 7721 // Note: the peeled shift operation does not have to be the same 7722 // instruction as the one feeding into the PHI's backedge value. We only 7723 // really care about it being the same *kind* of shift instruction -- 7724 // that's all that is required for our later inferences to hold. 7725 if (MatchPositiveShift(LHS, V, OpC)) { 7726 PostShiftOpCode = OpC; 7727 LHS = V; 7728 } 7729 } 7730 7731 PNOut = dyn_cast<PHINode>(LHS); 7732 if (!PNOut || PNOut->getParent() != L->getHeader()) 7733 return false; 7734 7735 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7736 Value *OpLHS; 7737 7738 return 7739 // The backedge value for the PHI node must be a shift by a positive 7740 // amount 7741 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7742 7743 // of the PHI node itself 7744 OpLHS == PNOut && 7745 7746 // and the kind of shift should be match the kind of shift we peeled 7747 // off, if any. 7748 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7749 }; 7750 7751 PHINode *PN; 7752 Instruction::BinaryOps OpCode; 7753 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7754 return getCouldNotCompute(); 7755 7756 const DataLayout &DL = getDataLayout(); 7757 7758 // The key rationale for this optimization is that for some kinds of shift 7759 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7760 // within a finite number of iterations. If the condition guarding the 7761 // backedge (in the sense that the backedge is taken if the condition is true) 7762 // is false for the value the shift recurrence stabilizes to, then we know 7763 // that the backedge is taken only a finite number of times. 7764 7765 ConstantInt *StableValue = nullptr; 7766 switch (OpCode) { 7767 default: 7768 llvm_unreachable("Impossible case!"); 7769 7770 case Instruction::AShr: { 7771 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7772 // bitwidth(K) iterations. 7773 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7774 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7775 Predecessor->getTerminator(), &DT); 7776 auto *Ty = cast<IntegerType>(RHS->getType()); 7777 if (Known.isNonNegative()) 7778 StableValue = ConstantInt::get(Ty, 0); 7779 else if (Known.isNegative()) 7780 StableValue = ConstantInt::get(Ty, -1, true); 7781 else 7782 return getCouldNotCompute(); 7783 7784 break; 7785 } 7786 case Instruction::LShr: 7787 case Instruction::Shl: 7788 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7789 // stabilize to 0 in at most bitwidth(K) iterations. 7790 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7791 break; 7792 } 7793 7794 auto *Result = 7795 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7796 assert(Result->getType()->isIntegerTy(1) && 7797 "Otherwise cannot be an operand to a branch instruction"); 7798 7799 if (Result->isZeroValue()) { 7800 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7801 const SCEV *UpperBound = 7802 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7803 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7804 } 7805 7806 return getCouldNotCompute(); 7807 } 7808 7809 /// Return true if we can constant fold an instruction of the specified type, 7810 /// assuming that all operands were constants. 7811 static bool CanConstantFold(const Instruction *I) { 7812 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7813 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7814 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7815 return true; 7816 7817 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7818 if (const Function *F = CI->getCalledFunction()) 7819 return canConstantFoldCallTo(CI, F); 7820 return false; 7821 } 7822 7823 /// Determine whether this instruction can constant evolve within this loop 7824 /// assuming its operands can all constant evolve. 7825 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7826 // An instruction outside of the loop can't be derived from a loop PHI. 7827 if (!L->contains(I)) return false; 7828 7829 if (isa<PHINode>(I)) { 7830 // We don't currently keep track of the control flow needed to evaluate 7831 // PHIs, so we cannot handle PHIs inside of loops. 7832 return L->getHeader() == I->getParent(); 7833 } 7834 7835 // If we won't be able to constant fold this expression even if the operands 7836 // are constants, bail early. 7837 return CanConstantFold(I); 7838 } 7839 7840 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7841 /// recursing through each instruction operand until reaching a loop header phi. 7842 static PHINode * 7843 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7844 DenseMap<Instruction *, PHINode *> &PHIMap, 7845 unsigned Depth) { 7846 if (Depth > MaxConstantEvolvingDepth) 7847 return nullptr; 7848 7849 // Otherwise, we can evaluate this instruction if all of its operands are 7850 // constant or derived from a PHI node themselves. 7851 PHINode *PHI = nullptr; 7852 for (Value *Op : UseInst->operands()) { 7853 if (isa<Constant>(Op)) continue; 7854 7855 Instruction *OpInst = dyn_cast<Instruction>(Op); 7856 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7857 7858 PHINode *P = dyn_cast<PHINode>(OpInst); 7859 if (!P) 7860 // If this operand is already visited, reuse the prior result. 7861 // We may have P != PHI if this is the deepest point at which the 7862 // inconsistent paths meet. 7863 P = PHIMap.lookup(OpInst); 7864 if (!P) { 7865 // Recurse and memoize the results, whether a phi is found or not. 7866 // This recursive call invalidates pointers into PHIMap. 7867 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7868 PHIMap[OpInst] = P; 7869 } 7870 if (!P) 7871 return nullptr; // Not evolving from PHI 7872 if (PHI && PHI != P) 7873 return nullptr; // Evolving from multiple different PHIs. 7874 PHI = P; 7875 } 7876 // This is a expression evolving from a constant PHI! 7877 return PHI; 7878 } 7879 7880 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7881 /// in the loop that V is derived from. We allow arbitrary operations along the 7882 /// way, but the operands of an operation must either be constants or a value 7883 /// derived from a constant PHI. If this expression does not fit with these 7884 /// constraints, return null. 7885 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7886 Instruction *I = dyn_cast<Instruction>(V); 7887 if (!I || !canConstantEvolve(I, L)) return nullptr; 7888 7889 if (PHINode *PN = dyn_cast<PHINode>(I)) 7890 return PN; 7891 7892 // Record non-constant instructions contained by the loop. 7893 DenseMap<Instruction *, PHINode *> PHIMap; 7894 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7895 } 7896 7897 /// EvaluateExpression - Given an expression that passes the 7898 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7899 /// in the loop has the value PHIVal. If we can't fold this expression for some 7900 /// reason, return null. 7901 static Constant *EvaluateExpression(Value *V, const Loop *L, 7902 DenseMap<Instruction *, Constant *> &Vals, 7903 const DataLayout &DL, 7904 const TargetLibraryInfo *TLI) { 7905 // Convenient constant check, but redundant for recursive calls. 7906 if (Constant *C = dyn_cast<Constant>(V)) return C; 7907 Instruction *I = dyn_cast<Instruction>(V); 7908 if (!I) return nullptr; 7909 7910 if (Constant *C = Vals.lookup(I)) return C; 7911 7912 // An instruction inside the loop depends on a value outside the loop that we 7913 // weren't given a mapping for, or a value such as a call inside the loop. 7914 if (!canConstantEvolve(I, L)) return nullptr; 7915 7916 // An unmapped PHI can be due to a branch or another loop inside this loop, 7917 // or due to this not being the initial iteration through a loop where we 7918 // couldn't compute the evolution of this particular PHI last time. 7919 if (isa<PHINode>(I)) return nullptr; 7920 7921 std::vector<Constant*> Operands(I->getNumOperands()); 7922 7923 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 7924 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 7925 if (!Operand) { 7926 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 7927 if (!Operands[i]) return nullptr; 7928 continue; 7929 } 7930 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 7931 Vals[Operand] = C; 7932 if (!C) return nullptr; 7933 Operands[i] = C; 7934 } 7935 7936 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 7937 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 7938 Operands[1], DL, TLI); 7939 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 7940 if (!LI->isVolatile()) 7941 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 7942 } 7943 return ConstantFoldInstOperands(I, Operands, DL, TLI); 7944 } 7945 7946 7947 // If every incoming value to PN except the one for BB is a specific Constant, 7948 // return that, else return nullptr. 7949 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 7950 Constant *IncomingVal = nullptr; 7951 7952 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 7953 if (PN->getIncomingBlock(i) == BB) 7954 continue; 7955 7956 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 7957 if (!CurrentVal) 7958 return nullptr; 7959 7960 if (IncomingVal != CurrentVal) { 7961 if (IncomingVal) 7962 return nullptr; 7963 IncomingVal = CurrentVal; 7964 } 7965 } 7966 7967 return IncomingVal; 7968 } 7969 7970 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 7971 /// in the header of its containing loop, we know the loop executes a 7972 /// constant number of times, and the PHI node is just a recurrence 7973 /// involving constants, fold it. 7974 Constant * 7975 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 7976 const APInt &BEs, 7977 const Loop *L) { 7978 auto I = ConstantEvolutionLoopExitValue.find(PN); 7979 if (I != ConstantEvolutionLoopExitValue.end()) 7980 return I->second; 7981 7982 if (BEs.ugt(MaxBruteForceIterations)) 7983 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 7984 7985 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 7986 7987 DenseMap<Instruction *, Constant *> CurrentIterVals; 7988 BasicBlock *Header = L->getHeader(); 7989 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 7990 7991 BasicBlock *Latch = L->getLoopLatch(); 7992 if (!Latch) 7993 return nullptr; 7994 7995 for (PHINode &PHI : Header->phis()) { 7996 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 7997 CurrentIterVals[&PHI] = StartCST; 7998 } 7999 if (!CurrentIterVals.count(PN)) 8000 return RetVal = nullptr; 8001 8002 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8003 8004 // Execute the loop symbolically to determine the exit value. 8005 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8006 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8007 8008 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8009 unsigned IterationNum = 0; 8010 const DataLayout &DL = getDataLayout(); 8011 for (; ; ++IterationNum) { 8012 if (IterationNum == NumIterations) 8013 return RetVal = CurrentIterVals[PN]; // Got exit value! 8014 8015 // Compute the value of the PHIs for the next iteration. 8016 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8017 DenseMap<Instruction *, Constant *> NextIterVals; 8018 Constant *NextPHI = 8019 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8020 if (!NextPHI) 8021 return nullptr; // Couldn't evaluate! 8022 NextIterVals[PN] = NextPHI; 8023 8024 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8025 8026 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8027 // cease to be able to evaluate one of them or if they stop evolving, 8028 // because that doesn't necessarily prevent us from computing PN. 8029 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8030 for (const auto &I : CurrentIterVals) { 8031 PHINode *PHI = dyn_cast<PHINode>(I.first); 8032 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8033 PHIsToCompute.emplace_back(PHI, I.second); 8034 } 8035 // We use two distinct loops because EvaluateExpression may invalidate any 8036 // iterators into CurrentIterVals. 8037 for (const auto &I : PHIsToCompute) { 8038 PHINode *PHI = I.first; 8039 Constant *&NextPHI = NextIterVals[PHI]; 8040 if (!NextPHI) { // Not already computed. 8041 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8042 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8043 } 8044 if (NextPHI != I.second) 8045 StoppedEvolving = false; 8046 } 8047 8048 // If all entries in CurrentIterVals == NextIterVals then we can stop 8049 // iterating, the loop can't continue to change. 8050 if (StoppedEvolving) 8051 return RetVal = CurrentIterVals[PN]; 8052 8053 CurrentIterVals.swap(NextIterVals); 8054 } 8055 } 8056 8057 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8058 Value *Cond, 8059 bool ExitWhen) { 8060 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8061 if (!PN) return getCouldNotCompute(); 8062 8063 // If the loop is canonicalized, the PHI will have exactly two entries. 8064 // That's the only form we support here. 8065 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8066 8067 DenseMap<Instruction *, Constant *> CurrentIterVals; 8068 BasicBlock *Header = L->getHeader(); 8069 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8070 8071 BasicBlock *Latch = L->getLoopLatch(); 8072 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8073 8074 for (PHINode &PHI : Header->phis()) { 8075 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8076 CurrentIterVals[&PHI] = StartCST; 8077 } 8078 if (!CurrentIterVals.count(PN)) 8079 return getCouldNotCompute(); 8080 8081 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8082 // the loop symbolically to determine when the condition gets a value of 8083 // "ExitWhen". 8084 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8085 const DataLayout &DL = getDataLayout(); 8086 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8087 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8088 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8089 8090 // Couldn't symbolically evaluate. 8091 if (!CondVal) return getCouldNotCompute(); 8092 8093 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8094 ++NumBruteForceTripCountsComputed; 8095 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8096 } 8097 8098 // Update all the PHI nodes for the next iteration. 8099 DenseMap<Instruction *, Constant *> NextIterVals; 8100 8101 // Create a list of which PHIs we need to compute. We want to do this before 8102 // calling EvaluateExpression on them because that may invalidate iterators 8103 // into CurrentIterVals. 8104 SmallVector<PHINode *, 8> PHIsToCompute; 8105 for (const auto &I : CurrentIterVals) { 8106 PHINode *PHI = dyn_cast<PHINode>(I.first); 8107 if (!PHI || PHI->getParent() != Header) continue; 8108 PHIsToCompute.push_back(PHI); 8109 } 8110 for (PHINode *PHI : PHIsToCompute) { 8111 Constant *&NextPHI = NextIterVals[PHI]; 8112 if (NextPHI) continue; // Already computed! 8113 8114 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8115 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8116 } 8117 CurrentIterVals.swap(NextIterVals); 8118 } 8119 8120 // Too many iterations were needed to evaluate. 8121 return getCouldNotCompute(); 8122 } 8123 8124 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8125 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8126 ValuesAtScopes[V]; 8127 // Check to see if we've folded this expression at this loop before. 8128 for (auto &LS : Values) 8129 if (LS.first == L) 8130 return LS.second ? LS.second : V; 8131 8132 Values.emplace_back(L, nullptr); 8133 8134 // Otherwise compute it. 8135 const SCEV *C = computeSCEVAtScope(V, L); 8136 for (auto &LS : reverse(ValuesAtScopes[V])) 8137 if (LS.first == L) { 8138 LS.second = C; 8139 break; 8140 } 8141 return C; 8142 } 8143 8144 /// This builds up a Constant using the ConstantExpr interface. That way, we 8145 /// will return Constants for objects which aren't represented by a 8146 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8147 /// Returns NULL if the SCEV isn't representable as a Constant. 8148 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8149 switch (static_cast<SCEVTypes>(V->getSCEVType())) { 8150 case scCouldNotCompute: 8151 case scAddRecExpr: 8152 break; 8153 case scConstant: 8154 return cast<SCEVConstant>(V)->getValue(); 8155 case scUnknown: 8156 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8157 case scSignExtend: { 8158 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8159 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8160 return ConstantExpr::getSExt(CastOp, SS->getType()); 8161 break; 8162 } 8163 case scZeroExtend: { 8164 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8165 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8166 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8167 break; 8168 } 8169 case scTruncate: { 8170 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8171 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8172 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8173 break; 8174 } 8175 case scAddExpr: { 8176 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8177 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8178 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8179 unsigned AS = PTy->getAddressSpace(); 8180 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8181 C = ConstantExpr::getBitCast(C, DestPtrTy); 8182 } 8183 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8184 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8185 if (!C2) return nullptr; 8186 8187 // First pointer! 8188 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8189 unsigned AS = C2->getType()->getPointerAddressSpace(); 8190 std::swap(C, C2); 8191 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8192 // The offsets have been converted to bytes. We can add bytes to an 8193 // i8* by GEP with the byte count in the first index. 8194 C = ConstantExpr::getBitCast(C, DestPtrTy); 8195 } 8196 8197 // Don't bother trying to sum two pointers. We probably can't 8198 // statically compute a load that results from it anyway. 8199 if (C2->getType()->isPointerTy()) 8200 return nullptr; 8201 8202 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8203 if (PTy->getElementType()->isStructTy()) 8204 C2 = ConstantExpr::getIntegerCast( 8205 C2, Type::getInt32Ty(C->getContext()), true); 8206 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8207 } else 8208 C = ConstantExpr::getAdd(C, C2); 8209 } 8210 return C; 8211 } 8212 break; 8213 } 8214 case scMulExpr: { 8215 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8216 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8217 // Don't bother with pointers at all. 8218 if (C->getType()->isPointerTy()) return nullptr; 8219 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8220 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8221 if (!C2 || C2->getType()->isPointerTy()) return nullptr; 8222 C = ConstantExpr::getMul(C, C2); 8223 } 8224 return C; 8225 } 8226 break; 8227 } 8228 case scUDivExpr: { 8229 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8230 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8231 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8232 if (LHS->getType() == RHS->getType()) 8233 return ConstantExpr::getUDiv(LHS, RHS); 8234 break; 8235 } 8236 case scSMaxExpr: 8237 case scUMaxExpr: 8238 case scSMinExpr: 8239 case scUMinExpr: 8240 break; // TODO: smax, umax, smin, umax. 8241 } 8242 return nullptr; 8243 } 8244 8245 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8246 if (isa<SCEVConstant>(V)) return V; 8247 8248 // If this instruction is evolved from a constant-evolving PHI, compute the 8249 // exit value from the loop without using SCEVs. 8250 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8251 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8252 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8253 const Loop *LI = this->LI[I->getParent()]; 8254 // Looking for loop exit value. 8255 if (LI && LI->getParentLoop() == L && 8256 PN->getParent() == LI->getHeader()) { 8257 // Okay, there is no closed form solution for the PHI node. Check 8258 // to see if the loop that contains it has a known backedge-taken 8259 // count. If so, we may be able to force computation of the exit 8260 // value. 8261 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI); 8262 // This trivial case can show up in some degenerate cases where 8263 // the incoming IR has not yet been fully simplified. 8264 if (BackedgeTakenCount->isZero()) { 8265 Value *InitValue = nullptr; 8266 bool MultipleInitValues = false; 8267 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8268 if (!LI->contains(PN->getIncomingBlock(i))) { 8269 if (!InitValue) 8270 InitValue = PN->getIncomingValue(i); 8271 else if (InitValue != PN->getIncomingValue(i)) { 8272 MultipleInitValues = true; 8273 break; 8274 } 8275 } 8276 } 8277 if (!MultipleInitValues && InitValue) 8278 return getSCEV(InitValue); 8279 } 8280 // Do we have a loop invariant value flowing around the backedge 8281 // for a loop which must execute the backedge? 8282 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8283 isKnownPositive(BackedgeTakenCount) && 8284 PN->getNumIncomingValues() == 2) { 8285 8286 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8287 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8288 if (LI->isLoopInvariant(BackedgeVal)) 8289 return getSCEV(BackedgeVal); 8290 } 8291 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8292 // Okay, we know how many times the containing loop executes. If 8293 // this is a constant evolving PHI node, get the final value at 8294 // the specified iteration number. 8295 Constant *RV = 8296 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI); 8297 if (RV) return getSCEV(RV); 8298 } 8299 } 8300 8301 // If there is a single-input Phi, evaluate it at our scope. If we can 8302 // prove that this replacement does not break LCSSA form, use new value. 8303 if (PN->getNumOperands() == 1) { 8304 const SCEV *Input = getSCEV(PN->getOperand(0)); 8305 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8306 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8307 // for the simplest case just support constants. 8308 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8309 } 8310 } 8311 8312 // Okay, this is an expression that we cannot symbolically evaluate 8313 // into a SCEV. Check to see if it's possible to symbolically evaluate 8314 // the arguments into constants, and if so, try to constant propagate the 8315 // result. This is particularly useful for computing loop exit values. 8316 if (CanConstantFold(I)) { 8317 SmallVector<Constant *, 4> Operands; 8318 bool MadeImprovement = false; 8319 for (Value *Op : I->operands()) { 8320 if (Constant *C = dyn_cast<Constant>(Op)) { 8321 Operands.push_back(C); 8322 continue; 8323 } 8324 8325 // If any of the operands is non-constant and if they are 8326 // non-integer and non-pointer, don't even try to analyze them 8327 // with scev techniques. 8328 if (!isSCEVable(Op->getType())) 8329 return V; 8330 8331 const SCEV *OrigV = getSCEV(Op); 8332 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8333 MadeImprovement |= OrigV != OpV; 8334 8335 Constant *C = BuildConstantFromSCEV(OpV); 8336 if (!C) return V; 8337 if (C->getType() != Op->getType()) 8338 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8339 Op->getType(), 8340 false), 8341 C, Op->getType()); 8342 Operands.push_back(C); 8343 } 8344 8345 // Check to see if getSCEVAtScope actually made an improvement. 8346 if (MadeImprovement) { 8347 Constant *C = nullptr; 8348 const DataLayout &DL = getDataLayout(); 8349 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8350 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8351 Operands[1], DL, &TLI); 8352 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 8353 if (!LI->isVolatile()) 8354 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8355 } else 8356 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8357 if (!C) return V; 8358 return getSCEV(C); 8359 } 8360 } 8361 } 8362 8363 // This is some other type of SCEVUnknown, just return it. 8364 return V; 8365 } 8366 8367 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8368 // Avoid performing the look-up in the common case where the specified 8369 // expression has no loop-variant portions. 8370 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8371 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8372 if (OpAtScope != Comm->getOperand(i)) { 8373 // Okay, at least one of these operands is loop variant but might be 8374 // foldable. Build a new instance of the folded commutative expression. 8375 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8376 Comm->op_begin()+i); 8377 NewOps.push_back(OpAtScope); 8378 8379 for (++i; i != e; ++i) { 8380 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8381 NewOps.push_back(OpAtScope); 8382 } 8383 if (isa<SCEVAddExpr>(Comm)) 8384 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8385 if (isa<SCEVMulExpr>(Comm)) 8386 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8387 if (isa<SCEVMinMaxExpr>(Comm)) 8388 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8389 llvm_unreachable("Unknown commutative SCEV type!"); 8390 } 8391 } 8392 // If we got here, all operands are loop invariant. 8393 return Comm; 8394 } 8395 8396 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8397 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8398 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8399 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8400 return Div; // must be loop invariant 8401 return getUDivExpr(LHS, RHS); 8402 } 8403 8404 // If this is a loop recurrence for a loop that does not contain L, then we 8405 // are dealing with the final value computed by the loop. 8406 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8407 // First, attempt to evaluate each operand. 8408 // Avoid performing the look-up in the common case where the specified 8409 // expression has no loop-variant portions. 8410 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8411 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8412 if (OpAtScope == AddRec->getOperand(i)) 8413 continue; 8414 8415 // Okay, at least one of these operands is loop variant but might be 8416 // foldable. Build a new instance of the folded commutative expression. 8417 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8418 AddRec->op_begin()+i); 8419 NewOps.push_back(OpAtScope); 8420 for (++i; i != e; ++i) 8421 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8422 8423 const SCEV *FoldedRec = 8424 getAddRecExpr(NewOps, AddRec->getLoop(), 8425 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8426 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8427 // The addrec may be folded to a nonrecurrence, for example, if the 8428 // induction variable is multiplied by zero after constant folding. Go 8429 // ahead and return the folded value. 8430 if (!AddRec) 8431 return FoldedRec; 8432 break; 8433 } 8434 8435 // If the scope is outside the addrec's loop, evaluate it by using the 8436 // loop exit value of the addrec. 8437 if (!AddRec->getLoop()->contains(L)) { 8438 // To evaluate this recurrence, we need to know how many times the AddRec 8439 // loop iterates. Compute this now. 8440 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8441 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8442 8443 // Then, evaluate the AddRec. 8444 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8445 } 8446 8447 return AddRec; 8448 } 8449 8450 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8451 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8452 if (Op == Cast->getOperand()) 8453 return Cast; // must be loop invariant 8454 return getZeroExtendExpr(Op, Cast->getType()); 8455 } 8456 8457 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8458 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8459 if (Op == Cast->getOperand()) 8460 return Cast; // must be loop invariant 8461 return getSignExtendExpr(Op, Cast->getType()); 8462 } 8463 8464 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8465 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8466 if (Op == Cast->getOperand()) 8467 return Cast; // must be loop invariant 8468 return getTruncateExpr(Op, Cast->getType()); 8469 } 8470 8471 llvm_unreachable("Unknown SCEV type!"); 8472 } 8473 8474 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8475 return getSCEVAtScope(getSCEV(V), L); 8476 } 8477 8478 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8479 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8480 return stripInjectiveFunctions(ZExt->getOperand()); 8481 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8482 return stripInjectiveFunctions(SExt->getOperand()); 8483 return S; 8484 } 8485 8486 /// Finds the minimum unsigned root of the following equation: 8487 /// 8488 /// A * X = B (mod N) 8489 /// 8490 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8491 /// A and B isn't important. 8492 /// 8493 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8494 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8495 ScalarEvolution &SE) { 8496 uint32_t BW = A.getBitWidth(); 8497 assert(BW == SE.getTypeSizeInBits(B->getType())); 8498 assert(A != 0 && "A must be non-zero."); 8499 8500 // 1. D = gcd(A, N) 8501 // 8502 // The gcd of A and N may have only one prime factor: 2. The number of 8503 // trailing zeros in A is its multiplicity 8504 uint32_t Mult2 = A.countTrailingZeros(); 8505 // D = 2^Mult2 8506 8507 // 2. Check if B is divisible by D. 8508 // 8509 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8510 // is not less than multiplicity of this prime factor for D. 8511 if (SE.GetMinTrailingZeros(B) < Mult2) 8512 return SE.getCouldNotCompute(); 8513 8514 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8515 // modulo (N / D). 8516 // 8517 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8518 // (N / D) in general. The inverse itself always fits into BW bits, though, 8519 // so we immediately truncate it. 8520 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8521 APInt Mod(BW + 1, 0); 8522 Mod.setBit(BW - Mult2); // Mod = N / D 8523 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8524 8525 // 4. Compute the minimum unsigned root of the equation: 8526 // I * (B / D) mod (N / D) 8527 // To simplify the computation, we factor out the divide by D: 8528 // (I * B mod N) / D 8529 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8530 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8531 } 8532 8533 /// For a given quadratic addrec, generate coefficients of the corresponding 8534 /// quadratic equation, multiplied by a common value to ensure that they are 8535 /// integers. 8536 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8537 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8538 /// were multiplied by, and BitWidth is the bit width of the original addrec 8539 /// coefficients. 8540 /// This function returns None if the addrec coefficients are not compile- 8541 /// time constants. 8542 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8543 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8544 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8545 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8546 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8547 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8548 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8549 << *AddRec << '\n'); 8550 8551 // We currently can only solve this if the coefficients are constants. 8552 if (!LC || !MC || !NC) { 8553 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8554 return None; 8555 } 8556 8557 APInt L = LC->getAPInt(); 8558 APInt M = MC->getAPInt(); 8559 APInt N = NC->getAPInt(); 8560 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8561 8562 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8563 unsigned NewWidth = BitWidth + 1; 8564 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8565 << BitWidth << '\n'); 8566 // The sign-extension (as opposed to a zero-extension) here matches the 8567 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8568 N = N.sext(NewWidth); 8569 M = M.sext(NewWidth); 8570 L = L.sext(NewWidth); 8571 8572 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8573 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8574 // L+M, L+2M+N, L+3M+3N, ... 8575 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8576 // 8577 // The equation Acc = 0 is then 8578 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8579 // In a quadratic form it becomes: 8580 // N n^2 + (2M-N) n + 2L = 0. 8581 8582 APInt A = N; 8583 APInt B = 2 * M - A; 8584 APInt C = 2 * L; 8585 APInt T = APInt(NewWidth, 2); 8586 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8587 << "x + " << C << ", coeff bw: " << NewWidth 8588 << ", multiplied by " << T << '\n'); 8589 return std::make_tuple(A, B, C, T, BitWidth); 8590 } 8591 8592 /// Helper function to compare optional APInts: 8593 /// (a) if X and Y both exist, return min(X, Y), 8594 /// (b) if neither X nor Y exist, return None, 8595 /// (c) if exactly one of X and Y exists, return that value. 8596 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8597 if (X.hasValue() && Y.hasValue()) { 8598 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8599 APInt XW = X->sextOrSelf(W); 8600 APInt YW = Y->sextOrSelf(W); 8601 return XW.slt(YW) ? *X : *Y; 8602 } 8603 if (!X.hasValue() && !Y.hasValue()) 8604 return None; 8605 return X.hasValue() ? *X : *Y; 8606 } 8607 8608 /// Helper function to truncate an optional APInt to a given BitWidth. 8609 /// When solving addrec-related equations, it is preferable to return a value 8610 /// that has the same bit width as the original addrec's coefficients. If the 8611 /// solution fits in the original bit width, truncate it (except for i1). 8612 /// Returning a value of a different bit width may inhibit some optimizations. 8613 /// 8614 /// In general, a solution to a quadratic equation generated from an addrec 8615 /// may require BW+1 bits, where BW is the bit width of the addrec's 8616 /// coefficients. The reason is that the coefficients of the quadratic 8617 /// equation are BW+1 bits wide (to avoid truncation when converting from 8618 /// the addrec to the equation). 8619 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8620 if (!X.hasValue()) 8621 return None; 8622 unsigned W = X->getBitWidth(); 8623 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8624 return X->trunc(BitWidth); 8625 return X; 8626 } 8627 8628 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8629 /// iterations. The values L, M, N are assumed to be signed, and they 8630 /// should all have the same bit widths. 8631 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8632 /// where BW is the bit width of the addrec's coefficients. 8633 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8634 /// returned as such, otherwise the bit width of the returned value may 8635 /// be greater than BW. 8636 /// 8637 /// This function returns None if 8638 /// (a) the addrec coefficients are not constant, or 8639 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8640 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8641 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8642 static Optional<APInt> 8643 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8644 APInt A, B, C, M; 8645 unsigned BitWidth; 8646 auto T = GetQuadraticEquation(AddRec); 8647 if (!T.hasValue()) 8648 return None; 8649 8650 std::tie(A, B, C, M, BitWidth) = *T; 8651 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8652 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8653 if (!X.hasValue()) 8654 return None; 8655 8656 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8657 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8658 if (!V->isZero()) 8659 return None; 8660 8661 return TruncIfPossible(X, BitWidth); 8662 } 8663 8664 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8665 /// iterations. The values M, N are assumed to be signed, and they 8666 /// should all have the same bit widths. 8667 /// Find the least n such that c(n) does not belong to the given range, 8668 /// while c(n-1) does. 8669 /// 8670 /// This function returns None if 8671 /// (a) the addrec coefficients are not constant, or 8672 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8673 /// bounds of the range. 8674 static Optional<APInt> 8675 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8676 const ConstantRange &Range, ScalarEvolution &SE) { 8677 assert(AddRec->getOperand(0)->isZero() && 8678 "Starting value of addrec should be 0"); 8679 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8680 << Range << ", addrec " << *AddRec << '\n'); 8681 // This case is handled in getNumIterationsInRange. Here we can assume that 8682 // we start in the range. 8683 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8684 "Addrec's initial value should be in range"); 8685 8686 APInt A, B, C, M; 8687 unsigned BitWidth; 8688 auto T = GetQuadraticEquation(AddRec); 8689 if (!T.hasValue()) 8690 return None; 8691 8692 // Be careful about the return value: there can be two reasons for not 8693 // returning an actual number. First, if no solutions to the equations 8694 // were found, and second, if the solutions don't leave the given range. 8695 // The first case means that the actual solution is "unknown", the second 8696 // means that it's known, but not valid. If the solution is unknown, we 8697 // cannot make any conclusions. 8698 // Return a pair: the optional solution and a flag indicating if the 8699 // solution was found. 8700 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8701 // Solve for signed overflow and unsigned overflow, pick the lower 8702 // solution. 8703 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8704 << Bound << " (before multiplying by " << M << ")\n"); 8705 Bound *= M; // The quadratic equation multiplier. 8706 8707 Optional<APInt> SO = None; 8708 if (BitWidth > 1) { 8709 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8710 "signed overflow\n"); 8711 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8712 } 8713 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8714 "unsigned overflow\n"); 8715 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8716 BitWidth+1); 8717 8718 auto LeavesRange = [&] (const APInt &X) { 8719 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8720 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8721 if (Range.contains(V0->getValue())) 8722 return false; 8723 // X should be at least 1, so X-1 is non-negative. 8724 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8725 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8726 if (Range.contains(V1->getValue())) 8727 return true; 8728 return false; 8729 }; 8730 8731 // If SolveQuadraticEquationWrap returns None, it means that there can 8732 // be a solution, but the function failed to find it. We cannot treat it 8733 // as "no solution". 8734 if (!SO.hasValue() || !UO.hasValue()) 8735 return { None, false }; 8736 8737 // Check the smaller value first to see if it leaves the range. 8738 // At this point, both SO and UO must have values. 8739 Optional<APInt> Min = MinOptional(SO, UO); 8740 if (LeavesRange(*Min)) 8741 return { Min, true }; 8742 Optional<APInt> Max = Min == SO ? UO : SO; 8743 if (LeavesRange(*Max)) 8744 return { Max, true }; 8745 8746 // Solutions were found, but were eliminated, hence the "true". 8747 return { None, true }; 8748 }; 8749 8750 std::tie(A, B, C, M, BitWidth) = *T; 8751 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8752 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8753 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8754 auto SL = SolveForBoundary(Lower); 8755 auto SU = SolveForBoundary(Upper); 8756 // If any of the solutions was unknown, no meaninigful conclusions can 8757 // be made. 8758 if (!SL.second || !SU.second) 8759 return None; 8760 8761 // Claim: The correct solution is not some value between Min and Max. 8762 // 8763 // Justification: Assuming that Min and Max are different values, one of 8764 // them is when the first signed overflow happens, the other is when the 8765 // first unsigned overflow happens. Crossing the range boundary is only 8766 // possible via an overflow (treating 0 as a special case of it, modeling 8767 // an overflow as crossing k*2^W for some k). 8768 // 8769 // The interesting case here is when Min was eliminated as an invalid 8770 // solution, but Max was not. The argument is that if there was another 8771 // overflow between Min and Max, it would also have been eliminated if 8772 // it was considered. 8773 // 8774 // For a given boundary, it is possible to have two overflows of the same 8775 // type (signed/unsigned) without having the other type in between: this 8776 // can happen when the vertex of the parabola is between the iterations 8777 // corresponding to the overflows. This is only possible when the two 8778 // overflows cross k*2^W for the same k. In such case, if the second one 8779 // left the range (and was the first one to do so), the first overflow 8780 // would have to enter the range, which would mean that either we had left 8781 // the range before or that we started outside of it. Both of these cases 8782 // are contradictions. 8783 // 8784 // Claim: In the case where SolveForBoundary returns None, the correct 8785 // solution is not some value between the Max for this boundary and the 8786 // Min of the other boundary. 8787 // 8788 // Justification: Assume that we had such Max_A and Min_B corresponding 8789 // to range boundaries A and B and such that Max_A < Min_B. If there was 8790 // a solution between Max_A and Min_B, it would have to be caused by an 8791 // overflow corresponding to either A or B. It cannot correspond to B, 8792 // since Min_B is the first occurrence of such an overflow. If it 8793 // corresponded to A, it would have to be either a signed or an unsigned 8794 // overflow that is larger than both eliminated overflows for A. But 8795 // between the eliminated overflows and this overflow, the values would 8796 // cover the entire value space, thus crossing the other boundary, which 8797 // is a contradiction. 8798 8799 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8800 } 8801 8802 ScalarEvolution::ExitLimit 8803 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8804 bool AllowPredicates) { 8805 8806 // This is only used for loops with a "x != y" exit test. The exit condition 8807 // is now expressed as a single expression, V = x-y. So the exit test is 8808 // effectively V != 0. We know and take advantage of the fact that this 8809 // expression only being used in a comparison by zero context. 8810 8811 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8812 // If the value is a constant 8813 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8814 // If the value is already zero, the branch will execute zero times. 8815 if (C->getValue()->isZero()) return C; 8816 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8817 } 8818 8819 const SCEVAddRecExpr *AddRec = 8820 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8821 8822 if (!AddRec && AllowPredicates) 8823 // Try to make this an AddRec using runtime tests, in the first X 8824 // iterations of this loop, where X is the SCEV expression found by the 8825 // algorithm below. 8826 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8827 8828 if (!AddRec || AddRec->getLoop() != L) 8829 return getCouldNotCompute(); 8830 8831 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8832 // the quadratic equation to solve it. 8833 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8834 // We can only use this value if the chrec ends up with an exact zero 8835 // value at this index. When solving for "X*X != 5", for example, we 8836 // should not accept a root of 2. 8837 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8838 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8839 return ExitLimit(R, R, false, Predicates); 8840 } 8841 return getCouldNotCompute(); 8842 } 8843 8844 // Otherwise we can only handle this if it is affine. 8845 if (!AddRec->isAffine()) 8846 return getCouldNotCompute(); 8847 8848 // If this is an affine expression, the execution count of this branch is 8849 // the minimum unsigned root of the following equation: 8850 // 8851 // Start + Step*N = 0 (mod 2^BW) 8852 // 8853 // equivalent to: 8854 // 8855 // Step*N = -Start (mod 2^BW) 8856 // 8857 // where BW is the common bit width of Start and Step. 8858 8859 // Get the initial value for the loop. 8860 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8861 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8862 8863 // For now we handle only constant steps. 8864 // 8865 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8866 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8867 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8868 // We have not yet seen any such cases. 8869 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8870 if (!StepC || StepC->getValue()->isZero()) 8871 return getCouldNotCompute(); 8872 8873 // For positive steps (counting up until unsigned overflow): 8874 // N = -Start/Step (as unsigned) 8875 // For negative steps (counting down to zero): 8876 // N = Start/-Step 8877 // First compute the unsigned distance from zero in the direction of Step. 8878 bool CountDown = StepC->getAPInt().isNegative(); 8879 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8880 8881 // Handle unitary steps, which cannot wraparound. 8882 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8883 // N = Distance (as unsigned) 8884 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8885 APInt MaxBECount = getUnsignedRangeMax(Distance); 8886 8887 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 8888 // we end up with a loop whose backedge-taken count is n - 1. Detect this 8889 // case, and see if we can improve the bound. 8890 // 8891 // Explicitly handling this here is necessary because getUnsignedRange 8892 // isn't context-sensitive; it doesn't know that we only care about the 8893 // range inside the loop. 8894 const SCEV *Zero = getZero(Distance->getType()); 8895 const SCEV *One = getOne(Distance->getType()); 8896 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 8897 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 8898 // If Distance + 1 doesn't overflow, we can compute the maximum distance 8899 // as "unsigned_max(Distance + 1) - 1". 8900 ConstantRange CR = getUnsignedRange(DistancePlusOne); 8901 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 8902 } 8903 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 8904 } 8905 8906 // If the condition controls loop exit (the loop exits only if the expression 8907 // is true) and the addition is no-wrap we can use unsigned divide to 8908 // compute the backedge count. In this case, the step may not divide the 8909 // distance, but we don't care because if the condition is "missed" the loop 8910 // will have undefined behavior due to wrapping. 8911 if (ControlsExit && AddRec->hasNoSelfWrap() && 8912 loopHasNoAbnormalExits(AddRec->getLoop())) { 8913 const SCEV *Exact = 8914 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 8915 const SCEV *Max = 8916 Exact == getCouldNotCompute() 8917 ? Exact 8918 : getConstant(getUnsignedRangeMax(Exact)); 8919 return ExitLimit(Exact, Max, false, Predicates); 8920 } 8921 8922 // Solve the general equation. 8923 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 8924 getNegativeSCEV(Start), *this); 8925 const SCEV *M = E == getCouldNotCompute() 8926 ? E 8927 : getConstant(getUnsignedRangeMax(E)); 8928 return ExitLimit(E, M, false, Predicates); 8929 } 8930 8931 ScalarEvolution::ExitLimit 8932 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 8933 // Loops that look like: while (X == 0) are very strange indeed. We don't 8934 // handle them yet except for the trivial case. This could be expanded in the 8935 // future as needed. 8936 8937 // If the value is a constant, check to see if it is known to be non-zero 8938 // already. If so, the backedge will execute zero times. 8939 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8940 if (!C->getValue()->isZero()) 8941 return getZero(C->getType()); 8942 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8943 } 8944 8945 // We could implement others, but I really doubt anyone writes loops like 8946 // this, and if they did, they would already be constant folded. 8947 return getCouldNotCompute(); 8948 } 8949 8950 std::pair<BasicBlock *, BasicBlock *> 8951 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) { 8952 // If the block has a unique predecessor, then there is no path from the 8953 // predecessor to the block that does not go through the direct edge 8954 // from the predecessor to the block. 8955 if (BasicBlock *Pred = BB->getSinglePredecessor()) 8956 return {Pred, BB}; 8957 8958 // A loop's header is defined to be a block that dominates the loop. 8959 // If the header has a unique predecessor outside the loop, it must be 8960 // a block that has exactly one successor that can reach the loop. 8961 if (Loop *L = LI.getLoopFor(BB)) 8962 return {L->getLoopPredecessor(), L->getHeader()}; 8963 8964 return {nullptr, nullptr}; 8965 } 8966 8967 /// SCEV structural equivalence is usually sufficient for testing whether two 8968 /// expressions are equal, however for the purposes of looking for a condition 8969 /// guarding a loop, it can be useful to be a little more general, since a 8970 /// front-end may have replicated the controlling expression. 8971 static bool HasSameValue(const SCEV *A, const SCEV *B) { 8972 // Quick check to see if they are the same SCEV. 8973 if (A == B) return true; 8974 8975 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 8976 // Not all instructions that are "identical" compute the same value. For 8977 // instance, two distinct alloca instructions allocating the same type are 8978 // identical and do not read memory; but compute distinct values. 8979 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 8980 }; 8981 8982 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 8983 // two different instructions with the same value. Check for this case. 8984 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 8985 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 8986 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 8987 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 8988 if (ComputesEqualValues(AI, BI)) 8989 return true; 8990 8991 // Otherwise assume they may have a different value. 8992 return false; 8993 } 8994 8995 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 8996 const SCEV *&LHS, const SCEV *&RHS, 8997 unsigned Depth) { 8998 bool Changed = false; 8999 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9000 // '0 != 0'. 9001 auto TrivialCase = [&](bool TriviallyTrue) { 9002 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9003 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9004 return true; 9005 }; 9006 // If we hit the max recursion limit bail out. 9007 if (Depth >= 3) 9008 return false; 9009 9010 // Canonicalize a constant to the right side. 9011 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9012 // Check for both operands constant. 9013 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9014 if (ConstantExpr::getICmp(Pred, 9015 LHSC->getValue(), 9016 RHSC->getValue())->isNullValue()) 9017 return TrivialCase(false); 9018 else 9019 return TrivialCase(true); 9020 } 9021 // Otherwise swap the operands to put the constant on the right. 9022 std::swap(LHS, RHS); 9023 Pred = ICmpInst::getSwappedPredicate(Pred); 9024 Changed = true; 9025 } 9026 9027 // If we're comparing an addrec with a value which is loop-invariant in the 9028 // addrec's loop, put the addrec on the left. Also make a dominance check, 9029 // as both operands could be addrecs loop-invariant in each other's loop. 9030 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9031 const Loop *L = AR->getLoop(); 9032 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9033 std::swap(LHS, RHS); 9034 Pred = ICmpInst::getSwappedPredicate(Pred); 9035 Changed = true; 9036 } 9037 } 9038 9039 // If there's a constant operand, canonicalize comparisons with boundary 9040 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9041 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9042 const APInt &RA = RC->getAPInt(); 9043 9044 bool SimplifiedByConstantRange = false; 9045 9046 if (!ICmpInst::isEquality(Pred)) { 9047 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9048 if (ExactCR.isFullSet()) 9049 return TrivialCase(true); 9050 else if (ExactCR.isEmptySet()) 9051 return TrivialCase(false); 9052 9053 APInt NewRHS; 9054 CmpInst::Predicate NewPred; 9055 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9056 ICmpInst::isEquality(NewPred)) { 9057 // We were able to convert an inequality to an equality. 9058 Pred = NewPred; 9059 RHS = getConstant(NewRHS); 9060 Changed = SimplifiedByConstantRange = true; 9061 } 9062 } 9063 9064 if (!SimplifiedByConstantRange) { 9065 switch (Pred) { 9066 default: 9067 break; 9068 case ICmpInst::ICMP_EQ: 9069 case ICmpInst::ICMP_NE: 9070 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9071 if (!RA) 9072 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9073 if (const SCEVMulExpr *ME = 9074 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9075 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9076 ME->getOperand(0)->isAllOnesValue()) { 9077 RHS = AE->getOperand(1); 9078 LHS = ME->getOperand(1); 9079 Changed = true; 9080 } 9081 break; 9082 9083 9084 // The "Should have been caught earlier!" messages refer to the fact 9085 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9086 // should have fired on the corresponding cases, and canonicalized the 9087 // check to trivial case. 9088 9089 case ICmpInst::ICMP_UGE: 9090 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9091 Pred = ICmpInst::ICMP_UGT; 9092 RHS = getConstant(RA - 1); 9093 Changed = true; 9094 break; 9095 case ICmpInst::ICMP_ULE: 9096 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9097 Pred = ICmpInst::ICMP_ULT; 9098 RHS = getConstant(RA + 1); 9099 Changed = true; 9100 break; 9101 case ICmpInst::ICMP_SGE: 9102 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9103 Pred = ICmpInst::ICMP_SGT; 9104 RHS = getConstant(RA - 1); 9105 Changed = true; 9106 break; 9107 case ICmpInst::ICMP_SLE: 9108 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9109 Pred = ICmpInst::ICMP_SLT; 9110 RHS = getConstant(RA + 1); 9111 Changed = true; 9112 break; 9113 } 9114 } 9115 } 9116 9117 // Check for obvious equality. 9118 if (HasSameValue(LHS, RHS)) { 9119 if (ICmpInst::isTrueWhenEqual(Pred)) 9120 return TrivialCase(true); 9121 if (ICmpInst::isFalseWhenEqual(Pred)) 9122 return TrivialCase(false); 9123 } 9124 9125 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9126 // adding or subtracting 1 from one of the operands. 9127 switch (Pred) { 9128 case ICmpInst::ICMP_SLE: 9129 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9130 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9131 SCEV::FlagNSW); 9132 Pred = ICmpInst::ICMP_SLT; 9133 Changed = true; 9134 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9135 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9136 SCEV::FlagNSW); 9137 Pred = ICmpInst::ICMP_SLT; 9138 Changed = true; 9139 } 9140 break; 9141 case ICmpInst::ICMP_SGE: 9142 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9143 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9144 SCEV::FlagNSW); 9145 Pred = ICmpInst::ICMP_SGT; 9146 Changed = true; 9147 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9148 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9149 SCEV::FlagNSW); 9150 Pred = ICmpInst::ICMP_SGT; 9151 Changed = true; 9152 } 9153 break; 9154 case ICmpInst::ICMP_ULE: 9155 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9156 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9157 SCEV::FlagNUW); 9158 Pred = ICmpInst::ICMP_ULT; 9159 Changed = true; 9160 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9161 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9162 Pred = ICmpInst::ICMP_ULT; 9163 Changed = true; 9164 } 9165 break; 9166 case ICmpInst::ICMP_UGE: 9167 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9168 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9169 Pred = ICmpInst::ICMP_UGT; 9170 Changed = true; 9171 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9172 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9173 SCEV::FlagNUW); 9174 Pred = ICmpInst::ICMP_UGT; 9175 Changed = true; 9176 } 9177 break; 9178 default: 9179 break; 9180 } 9181 9182 // TODO: More simplifications are possible here. 9183 9184 // Recursively simplify until we either hit a recursion limit or nothing 9185 // changes. 9186 if (Changed) 9187 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9188 9189 return Changed; 9190 } 9191 9192 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9193 return getSignedRangeMax(S).isNegative(); 9194 } 9195 9196 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9197 return getSignedRangeMin(S).isStrictlyPositive(); 9198 } 9199 9200 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9201 return !getSignedRangeMin(S).isNegative(); 9202 } 9203 9204 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9205 return !getSignedRangeMax(S).isStrictlyPositive(); 9206 } 9207 9208 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9209 return isKnownNegative(S) || isKnownPositive(S); 9210 } 9211 9212 std::pair<const SCEV *, const SCEV *> 9213 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9214 // Compute SCEV on entry of loop L. 9215 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9216 if (Start == getCouldNotCompute()) 9217 return { Start, Start }; 9218 // Compute post increment SCEV for loop L. 9219 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9220 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9221 return { Start, PostInc }; 9222 } 9223 9224 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9225 const SCEV *LHS, const SCEV *RHS) { 9226 // First collect all loops. 9227 SmallPtrSet<const Loop *, 8> LoopsUsed; 9228 getUsedLoops(LHS, LoopsUsed); 9229 getUsedLoops(RHS, LoopsUsed); 9230 9231 if (LoopsUsed.empty()) 9232 return false; 9233 9234 // Domination relationship must be a linear order on collected loops. 9235 #ifndef NDEBUG 9236 for (auto *L1 : LoopsUsed) 9237 for (auto *L2 : LoopsUsed) 9238 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9239 DT.dominates(L2->getHeader(), L1->getHeader())) && 9240 "Domination relationship is not a linear order"); 9241 #endif 9242 9243 const Loop *MDL = 9244 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9245 [&](const Loop *L1, const Loop *L2) { 9246 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9247 }); 9248 9249 // Get init and post increment value for LHS. 9250 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9251 // if LHS contains unknown non-invariant SCEV then bail out. 9252 if (SplitLHS.first == getCouldNotCompute()) 9253 return false; 9254 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9255 // Get init and post increment value for RHS. 9256 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9257 // if RHS contains unknown non-invariant SCEV then bail out. 9258 if (SplitRHS.first == getCouldNotCompute()) 9259 return false; 9260 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9261 // It is possible that init SCEV contains an invariant load but it does 9262 // not dominate MDL and is not available at MDL loop entry, so we should 9263 // check it here. 9264 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9265 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9266 return false; 9267 9268 // It seems backedge guard check is faster than entry one so in some cases 9269 // it can speed up whole estimation by short circuit 9270 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9271 SplitRHS.second) && 9272 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9273 } 9274 9275 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9276 const SCEV *LHS, const SCEV *RHS) { 9277 // Canonicalize the inputs first. 9278 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9279 9280 if (isKnownViaInduction(Pred, LHS, RHS)) 9281 return true; 9282 9283 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9284 return true; 9285 9286 // Otherwise see what can be done with some simple reasoning. 9287 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9288 } 9289 9290 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9291 const SCEVAddRecExpr *LHS, 9292 const SCEV *RHS) { 9293 const Loop *L = LHS->getLoop(); 9294 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9295 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9296 } 9297 9298 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS, 9299 ICmpInst::Predicate Pred, 9300 bool &Increasing) { 9301 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing); 9302 9303 #ifndef NDEBUG 9304 // Verify an invariant: inverting the predicate should turn a monotonically 9305 // increasing change to a monotonically decreasing one, and vice versa. 9306 bool IncreasingSwapped; 9307 bool ResultSwapped = isMonotonicPredicateImpl( 9308 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped); 9309 9310 assert(Result == ResultSwapped && "should be able to analyze both!"); 9311 if (ResultSwapped) 9312 assert(Increasing == !IncreasingSwapped && 9313 "monotonicity should flip as we flip the predicate"); 9314 #endif 9315 9316 return Result; 9317 } 9318 9319 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS, 9320 ICmpInst::Predicate Pred, 9321 bool &Increasing) { 9322 9323 // A zero step value for LHS means the induction variable is essentially a 9324 // loop invariant value. We don't really depend on the predicate actually 9325 // flipping from false to true (for increasing predicates, and the other way 9326 // around for decreasing predicates), all we care about is that *if* the 9327 // predicate changes then it only changes from false to true. 9328 // 9329 // A zero step value in itself is not very useful, but there may be places 9330 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9331 // as general as possible. 9332 9333 switch (Pred) { 9334 default: 9335 return false; // Conservative answer 9336 9337 case ICmpInst::ICMP_UGT: 9338 case ICmpInst::ICMP_UGE: 9339 case ICmpInst::ICMP_ULT: 9340 case ICmpInst::ICMP_ULE: 9341 if (!LHS->hasNoUnsignedWrap()) 9342 return false; 9343 9344 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE; 9345 return true; 9346 9347 case ICmpInst::ICMP_SGT: 9348 case ICmpInst::ICMP_SGE: 9349 case ICmpInst::ICMP_SLT: 9350 case ICmpInst::ICMP_SLE: { 9351 if (!LHS->hasNoSignedWrap()) 9352 return false; 9353 9354 const SCEV *Step = LHS->getStepRecurrence(*this); 9355 9356 if (isKnownNonNegative(Step)) { 9357 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE; 9358 return true; 9359 } 9360 9361 if (isKnownNonPositive(Step)) { 9362 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE; 9363 return true; 9364 } 9365 9366 return false; 9367 } 9368 9369 } 9370 9371 llvm_unreachable("switch has default clause!"); 9372 } 9373 9374 bool ScalarEvolution::isLoopInvariantPredicate( 9375 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9376 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9377 const SCEV *&InvariantRHS) { 9378 9379 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9380 if (!isLoopInvariant(RHS, L)) { 9381 if (!isLoopInvariant(LHS, L)) 9382 return false; 9383 9384 std::swap(LHS, RHS); 9385 Pred = ICmpInst::getSwappedPredicate(Pred); 9386 } 9387 9388 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9389 if (!ArLHS || ArLHS->getLoop() != L) 9390 return false; 9391 9392 bool Increasing; 9393 if (!isMonotonicPredicate(ArLHS, Pred, Increasing)) 9394 return false; 9395 9396 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9397 // true as the loop iterates, and the backedge is control dependent on 9398 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9399 // 9400 // * if the predicate was false in the first iteration then the predicate 9401 // is never evaluated again, since the loop exits without taking the 9402 // backedge. 9403 // * if the predicate was true in the first iteration then it will 9404 // continue to be true for all future iterations since it is 9405 // monotonically increasing. 9406 // 9407 // For both the above possibilities, we can replace the loop varying 9408 // predicate with its value on the first iteration of the loop (which is 9409 // loop invariant). 9410 // 9411 // A similar reasoning applies for a monotonically decreasing predicate, by 9412 // replacing true with false and false with true in the above two bullets. 9413 9414 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9415 9416 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9417 return false; 9418 9419 InvariantPred = Pred; 9420 InvariantLHS = ArLHS->getStart(); 9421 InvariantRHS = RHS; 9422 return true; 9423 } 9424 9425 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9426 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9427 if (HasSameValue(LHS, RHS)) 9428 return ICmpInst::isTrueWhenEqual(Pred); 9429 9430 // This code is split out from isKnownPredicate because it is called from 9431 // within isLoopEntryGuardedByCond. 9432 9433 auto CheckRanges = 9434 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9435 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9436 .contains(RangeLHS); 9437 }; 9438 9439 // The check at the top of the function catches the case where the values are 9440 // known to be equal. 9441 if (Pred == CmpInst::ICMP_EQ) 9442 return false; 9443 9444 if (Pred == CmpInst::ICMP_NE) 9445 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9446 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9447 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9448 9449 if (CmpInst::isSigned(Pred)) 9450 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9451 9452 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9453 } 9454 9455 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9456 const SCEV *LHS, 9457 const SCEV *RHS) { 9458 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9459 // Return Y via OutY. 9460 auto MatchBinaryAddToConst = 9461 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9462 SCEV::NoWrapFlags ExpectedFlags) { 9463 const SCEV *NonConstOp, *ConstOp; 9464 SCEV::NoWrapFlags FlagsPresent; 9465 9466 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9467 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9468 return false; 9469 9470 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9471 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9472 }; 9473 9474 APInt C; 9475 9476 switch (Pred) { 9477 default: 9478 break; 9479 9480 case ICmpInst::ICMP_SGE: 9481 std::swap(LHS, RHS); 9482 LLVM_FALLTHROUGH; 9483 case ICmpInst::ICMP_SLE: 9484 // X s<= (X + C)<nsw> if C >= 0 9485 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9486 return true; 9487 9488 // (X + C)<nsw> s<= X if C <= 0 9489 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9490 !C.isStrictlyPositive()) 9491 return true; 9492 break; 9493 9494 case ICmpInst::ICMP_SGT: 9495 std::swap(LHS, RHS); 9496 LLVM_FALLTHROUGH; 9497 case ICmpInst::ICMP_SLT: 9498 // X s< (X + C)<nsw> if C > 0 9499 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9500 C.isStrictlyPositive()) 9501 return true; 9502 9503 // (X + C)<nsw> s< X if C < 0 9504 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9505 return true; 9506 break; 9507 } 9508 9509 return false; 9510 } 9511 9512 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9513 const SCEV *LHS, 9514 const SCEV *RHS) { 9515 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9516 return false; 9517 9518 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9519 // the stack can result in exponential time complexity. 9520 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9521 9522 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9523 // 9524 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9525 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9526 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9527 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9528 // use isKnownPredicate later if needed. 9529 return isKnownNonNegative(RHS) && 9530 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9531 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9532 } 9533 9534 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB, 9535 ICmpInst::Predicate Pred, 9536 const SCEV *LHS, const SCEV *RHS) { 9537 // No need to even try if we know the module has no guards. 9538 if (!HasGuards) 9539 return false; 9540 9541 return any_of(*BB, [&](Instruction &I) { 9542 using namespace llvm::PatternMatch; 9543 9544 Value *Condition; 9545 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9546 m_Value(Condition))) && 9547 isImpliedCond(Pred, LHS, RHS, Condition, false); 9548 }); 9549 } 9550 9551 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9552 /// protected by a conditional between LHS and RHS. This is used to 9553 /// to eliminate casts. 9554 bool 9555 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9556 ICmpInst::Predicate Pred, 9557 const SCEV *LHS, const SCEV *RHS) { 9558 // Interpret a null as meaning no loop, where there is obviously no guard 9559 // (interprocedural conditions notwithstanding). 9560 if (!L) return true; 9561 9562 if (VerifyIR) 9563 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9564 "This cannot be done on broken IR!"); 9565 9566 9567 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9568 return true; 9569 9570 BasicBlock *Latch = L->getLoopLatch(); 9571 if (!Latch) 9572 return false; 9573 9574 BranchInst *LoopContinuePredicate = 9575 dyn_cast<BranchInst>(Latch->getTerminator()); 9576 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9577 isImpliedCond(Pred, LHS, RHS, 9578 LoopContinuePredicate->getCondition(), 9579 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9580 return true; 9581 9582 // We don't want more than one activation of the following loops on the stack 9583 // -- that can lead to O(n!) time complexity. 9584 if (WalkingBEDominatingConds) 9585 return false; 9586 9587 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9588 9589 // See if we can exploit a trip count to prove the predicate. 9590 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9591 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9592 if (LatchBECount != getCouldNotCompute()) { 9593 // We know that Latch branches back to the loop header exactly 9594 // LatchBECount times. This means the backdege condition at Latch is 9595 // equivalent to "{0,+,1} u< LatchBECount". 9596 Type *Ty = LatchBECount->getType(); 9597 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9598 const SCEV *LoopCounter = 9599 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9600 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9601 LatchBECount)) 9602 return true; 9603 } 9604 9605 // Check conditions due to any @llvm.assume intrinsics. 9606 for (auto &AssumeVH : AC.assumptions()) { 9607 if (!AssumeVH) 9608 continue; 9609 auto *CI = cast<CallInst>(AssumeVH); 9610 if (!DT.dominates(CI, Latch->getTerminator())) 9611 continue; 9612 9613 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9614 return true; 9615 } 9616 9617 // If the loop is not reachable from the entry block, we risk running into an 9618 // infinite loop as we walk up into the dom tree. These loops do not matter 9619 // anyway, so we just return a conservative answer when we see them. 9620 if (!DT.isReachableFromEntry(L->getHeader())) 9621 return false; 9622 9623 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9624 return true; 9625 9626 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9627 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9628 assert(DTN && "should reach the loop header before reaching the root!"); 9629 9630 BasicBlock *BB = DTN->getBlock(); 9631 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9632 return true; 9633 9634 BasicBlock *PBB = BB->getSinglePredecessor(); 9635 if (!PBB) 9636 continue; 9637 9638 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9639 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9640 continue; 9641 9642 Value *Condition = ContinuePredicate->getCondition(); 9643 9644 // If we have an edge `E` within the loop body that dominates the only 9645 // latch, the condition guarding `E` also guards the backedge. This 9646 // reasoning works only for loops with a single latch. 9647 9648 BasicBlockEdge DominatingEdge(PBB, BB); 9649 if (DominatingEdge.isSingleEdge()) { 9650 // We're constructively (and conservatively) enumerating edges within the 9651 // loop body that dominate the latch. The dominator tree better agree 9652 // with us on this: 9653 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9654 9655 if (isImpliedCond(Pred, LHS, RHS, Condition, 9656 BB != ContinuePredicate->getSuccessor(0))) 9657 return true; 9658 } 9659 } 9660 9661 return false; 9662 } 9663 9664 bool 9665 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9666 ICmpInst::Predicate Pred, 9667 const SCEV *LHS, const SCEV *RHS) { 9668 // Interpret a null as meaning no loop, where there is obviously no guard 9669 // (interprocedural conditions notwithstanding). 9670 if (!L) return false; 9671 9672 if (VerifyIR) 9673 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9674 "This cannot be done on broken IR!"); 9675 9676 // Both LHS and RHS must be available at loop entry. 9677 assert(isAvailableAtLoopEntry(LHS, L) && 9678 "LHS is not available at Loop Entry"); 9679 assert(isAvailableAtLoopEntry(RHS, L) && 9680 "RHS is not available at Loop Entry"); 9681 9682 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9683 return true; 9684 9685 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9686 // the facts (a >= b && a != b) separately. A typical situation is when the 9687 // non-strict comparison is known from ranges and non-equality is known from 9688 // dominating predicates. If we are proving strict comparison, we always try 9689 // to prove non-equality and non-strict comparison separately. 9690 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9691 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9692 bool ProvedNonStrictComparison = false; 9693 bool ProvedNonEquality = false; 9694 9695 if (ProvingStrictComparison) { 9696 ProvedNonStrictComparison = 9697 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9698 ProvedNonEquality = 9699 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9700 if (ProvedNonStrictComparison && ProvedNonEquality) 9701 return true; 9702 } 9703 9704 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9705 auto ProveViaGuard = [&](BasicBlock *Block) { 9706 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9707 return true; 9708 if (ProvingStrictComparison) { 9709 if (!ProvedNonStrictComparison) 9710 ProvedNonStrictComparison = 9711 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9712 if (!ProvedNonEquality) 9713 ProvedNonEquality = 9714 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9715 if (ProvedNonStrictComparison && ProvedNonEquality) 9716 return true; 9717 } 9718 return false; 9719 }; 9720 9721 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9722 auto ProveViaCond = [&](Value *Condition, bool Inverse) { 9723 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse)) 9724 return true; 9725 if (ProvingStrictComparison) { 9726 if (!ProvedNonStrictComparison) 9727 ProvedNonStrictComparison = 9728 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse); 9729 if (!ProvedNonEquality) 9730 ProvedNonEquality = 9731 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse); 9732 if (ProvedNonStrictComparison && ProvedNonEquality) 9733 return true; 9734 } 9735 return false; 9736 }; 9737 9738 // Starting at the loop predecessor, climb up the predecessor chain, as long 9739 // as there are predecessors that can be found that have unique successors 9740 // leading to the original header. 9741 for (std::pair<BasicBlock *, BasicBlock *> 9742 Pair(L->getLoopPredecessor(), L->getHeader()); 9743 Pair.first; 9744 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9745 9746 if (ProveViaGuard(Pair.first)) 9747 return true; 9748 9749 BranchInst *LoopEntryPredicate = 9750 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9751 if (!LoopEntryPredicate || 9752 LoopEntryPredicate->isUnconditional()) 9753 continue; 9754 9755 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9756 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9757 return true; 9758 } 9759 9760 // Check conditions due to any @llvm.assume intrinsics. 9761 for (auto &AssumeVH : AC.assumptions()) { 9762 if (!AssumeVH) 9763 continue; 9764 auto *CI = cast<CallInst>(AssumeVH); 9765 if (!DT.dominates(CI, L->getHeader())) 9766 continue; 9767 9768 if (ProveViaCond(CI->getArgOperand(0), false)) 9769 return true; 9770 } 9771 9772 return false; 9773 } 9774 9775 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, 9776 const SCEV *LHS, const SCEV *RHS, 9777 Value *FoundCondValue, 9778 bool Inverse) { 9779 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9780 return false; 9781 9782 auto ClearOnExit = 9783 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9784 9785 // Recursively handle And and Or conditions. 9786 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9787 if (BO->getOpcode() == Instruction::And) { 9788 if (!Inverse) 9789 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9790 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9791 } else if (BO->getOpcode() == Instruction::Or) { 9792 if (Inverse) 9793 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) || 9794 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse); 9795 } 9796 } 9797 9798 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 9799 if (!ICI) return false; 9800 9801 // Now that we found a conditional branch that dominates the loop or controls 9802 // the loop latch. Check to see if it is the comparison we are looking for. 9803 ICmpInst::Predicate FoundPred; 9804 if (Inverse) 9805 FoundPred = ICI->getInversePredicate(); 9806 else 9807 FoundPred = ICI->getPredicate(); 9808 9809 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 9810 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 9811 9812 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS); 9813 } 9814 9815 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9816 const SCEV *RHS, 9817 ICmpInst::Predicate FoundPred, 9818 const SCEV *FoundLHS, 9819 const SCEV *FoundRHS) { 9820 // Balance the types. 9821 if (getTypeSizeInBits(LHS->getType()) < 9822 getTypeSizeInBits(FoundLHS->getType())) { 9823 if (CmpInst::isSigned(Pred)) { 9824 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 9825 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 9826 } else { 9827 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 9828 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 9829 } 9830 } else if (getTypeSizeInBits(LHS->getType()) > 9831 getTypeSizeInBits(FoundLHS->getType())) { 9832 if (CmpInst::isSigned(FoundPred)) { 9833 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 9834 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 9835 } else { 9836 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 9837 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 9838 } 9839 } 9840 9841 // Canonicalize the query to match the way instcombine will have 9842 // canonicalized the comparison. 9843 if (SimplifyICmpOperands(Pred, LHS, RHS)) 9844 if (LHS == RHS) 9845 return CmpInst::isTrueWhenEqual(Pred); 9846 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 9847 if (FoundLHS == FoundRHS) 9848 return CmpInst::isFalseWhenEqual(FoundPred); 9849 9850 // Check to see if we can make the LHS or RHS match. 9851 if (LHS == FoundRHS || RHS == FoundLHS) { 9852 if (isa<SCEVConstant>(RHS)) { 9853 std::swap(FoundLHS, FoundRHS); 9854 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 9855 } else { 9856 std::swap(LHS, RHS); 9857 Pred = ICmpInst::getSwappedPredicate(Pred); 9858 } 9859 } 9860 9861 // Check whether the found predicate is the same as the desired predicate. 9862 if (FoundPred == Pred) 9863 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9864 9865 // Check whether swapping the found predicate makes it the same as the 9866 // desired predicate. 9867 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 9868 if (isa<SCEVConstant>(RHS)) 9869 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS); 9870 else 9871 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), 9872 RHS, LHS, FoundLHS, FoundRHS); 9873 } 9874 9875 // Unsigned comparison is the same as signed comparison when both the operands 9876 // are non-negative. 9877 if (CmpInst::isUnsigned(FoundPred) && 9878 CmpInst::getSignedPredicate(FoundPred) == Pred && 9879 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 9880 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS); 9881 9882 // Check if we can make progress by sharpening ranges. 9883 if (FoundPred == ICmpInst::ICMP_NE && 9884 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 9885 9886 const SCEVConstant *C = nullptr; 9887 const SCEV *V = nullptr; 9888 9889 if (isa<SCEVConstant>(FoundLHS)) { 9890 C = cast<SCEVConstant>(FoundLHS); 9891 V = FoundRHS; 9892 } else { 9893 C = cast<SCEVConstant>(FoundRHS); 9894 V = FoundLHS; 9895 } 9896 9897 // The guarding predicate tells us that C != V. If the known range 9898 // of V is [C, t), we can sharpen the range to [C + 1, t). The 9899 // range we consider has to correspond to same signedness as the 9900 // predicate we're interested in folding. 9901 9902 APInt Min = ICmpInst::isSigned(Pred) ? 9903 getSignedRangeMin(V) : getUnsignedRangeMin(V); 9904 9905 if (Min == C->getAPInt()) { 9906 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 9907 // This is true even if (Min + 1) wraps around -- in case of 9908 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 9909 9910 APInt SharperMin = Min + 1; 9911 9912 switch (Pred) { 9913 case ICmpInst::ICMP_SGE: 9914 case ICmpInst::ICMP_UGE: 9915 // We know V `Pred` SharperMin. If this implies LHS `Pred` 9916 // RHS, we're done. 9917 if (isImpliedCondOperands(Pred, LHS, RHS, V, 9918 getConstant(SharperMin))) 9919 return true; 9920 LLVM_FALLTHROUGH; 9921 9922 case ICmpInst::ICMP_SGT: 9923 case ICmpInst::ICMP_UGT: 9924 // We know from the range information that (V `Pred` Min || 9925 // V == Min). We know from the guarding condition that !(V 9926 // == Min). This gives us 9927 // 9928 // V `Pred` Min || V == Min && !(V == Min) 9929 // => V `Pred` Min 9930 // 9931 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 9932 9933 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min))) 9934 return true; 9935 LLVM_FALLTHROUGH; 9936 9937 default: 9938 // No change 9939 break; 9940 } 9941 } 9942 } 9943 9944 // Check whether the actual condition is beyond sufficient. 9945 if (FoundPred == ICmpInst::ICMP_EQ) 9946 if (ICmpInst::isTrueWhenEqual(Pred)) 9947 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS)) 9948 return true; 9949 if (Pred == ICmpInst::ICMP_NE) 9950 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 9951 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS)) 9952 return true; 9953 9954 // Otherwise assume the worst. 9955 return false; 9956 } 9957 9958 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 9959 const SCEV *&L, const SCEV *&R, 9960 SCEV::NoWrapFlags &Flags) { 9961 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 9962 if (!AE || AE->getNumOperands() != 2) 9963 return false; 9964 9965 L = AE->getOperand(0); 9966 R = AE->getOperand(1); 9967 Flags = AE->getNoWrapFlags(); 9968 return true; 9969 } 9970 9971 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 9972 const SCEV *Less) { 9973 // We avoid subtracting expressions here because this function is usually 9974 // fairly deep in the call stack (i.e. is called many times). 9975 9976 // X - X = 0. 9977 if (More == Less) 9978 return APInt(getTypeSizeInBits(More->getType()), 0); 9979 9980 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 9981 const auto *LAR = cast<SCEVAddRecExpr>(Less); 9982 const auto *MAR = cast<SCEVAddRecExpr>(More); 9983 9984 if (LAR->getLoop() != MAR->getLoop()) 9985 return None; 9986 9987 // We look at affine expressions only; not for correctness but to keep 9988 // getStepRecurrence cheap. 9989 if (!LAR->isAffine() || !MAR->isAffine()) 9990 return None; 9991 9992 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 9993 return None; 9994 9995 Less = LAR->getStart(); 9996 More = MAR->getStart(); 9997 9998 // fall through 9999 } 10000 10001 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10002 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10003 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10004 return M - L; 10005 } 10006 10007 SCEV::NoWrapFlags Flags; 10008 const SCEV *LLess = nullptr, *RLess = nullptr; 10009 const SCEV *LMore = nullptr, *RMore = nullptr; 10010 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10011 // Compare (X + C1) vs X. 10012 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10013 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10014 if (RLess == More) 10015 return -(C1->getAPInt()); 10016 10017 // Compare X vs (X + C2). 10018 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10019 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10020 if (RMore == Less) 10021 return C2->getAPInt(); 10022 10023 // Compare (X + C1) vs (X + C2). 10024 if (C1 && C2 && RLess == RMore) 10025 return C2->getAPInt() - C1->getAPInt(); 10026 10027 return None; 10028 } 10029 10030 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10031 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10032 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10033 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10034 return false; 10035 10036 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10037 if (!AddRecLHS) 10038 return false; 10039 10040 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10041 if (!AddRecFoundLHS) 10042 return false; 10043 10044 // We'd like to let SCEV reason about control dependencies, so we constrain 10045 // both the inequalities to be about add recurrences on the same loop. This 10046 // way we can use isLoopEntryGuardedByCond later. 10047 10048 const Loop *L = AddRecFoundLHS->getLoop(); 10049 if (L != AddRecLHS->getLoop()) 10050 return false; 10051 10052 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10053 // 10054 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10055 // ... (2) 10056 // 10057 // Informal proof for (2), assuming (1) [*]: 10058 // 10059 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10060 // 10061 // Then 10062 // 10063 // FoundLHS s< FoundRHS s< INT_MIN - C 10064 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10065 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10066 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10067 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10068 // <=> FoundLHS + C s< FoundRHS + C 10069 // 10070 // [*]: (1) can be proved by ruling out overflow. 10071 // 10072 // [**]: This can be proved by analyzing all the four possibilities: 10073 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10074 // (A s>= 0, B s>= 0). 10075 // 10076 // Note: 10077 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10078 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10079 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10080 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10081 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10082 // C)". 10083 10084 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10085 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10086 if (!LDiff || !RDiff || *LDiff != *RDiff) 10087 return false; 10088 10089 if (LDiff->isMinValue()) 10090 return true; 10091 10092 APInt FoundRHSLimit; 10093 10094 if (Pred == CmpInst::ICMP_ULT) { 10095 FoundRHSLimit = -(*RDiff); 10096 } else { 10097 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10098 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10099 } 10100 10101 // Try to prove (1) or (2), as needed. 10102 return isAvailableAtLoopEntry(FoundRHS, L) && 10103 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10104 getConstant(FoundRHSLimit)); 10105 } 10106 10107 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10108 const SCEV *LHS, const SCEV *RHS, 10109 const SCEV *FoundLHS, 10110 const SCEV *FoundRHS, unsigned Depth) { 10111 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10112 10113 auto ClearOnExit = make_scope_exit([&]() { 10114 if (LPhi) { 10115 bool Erased = PendingMerges.erase(LPhi); 10116 assert(Erased && "Failed to erase LPhi!"); 10117 (void)Erased; 10118 } 10119 if (RPhi) { 10120 bool Erased = PendingMerges.erase(RPhi); 10121 assert(Erased && "Failed to erase RPhi!"); 10122 (void)Erased; 10123 } 10124 }); 10125 10126 // Find respective Phis and check that they are not being pending. 10127 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10128 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10129 if (!PendingMerges.insert(Phi).second) 10130 return false; 10131 LPhi = Phi; 10132 } 10133 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10134 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10135 // If we detect a loop of Phi nodes being processed by this method, for 10136 // example: 10137 // 10138 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10139 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10140 // 10141 // we don't want to deal with a case that complex, so return conservative 10142 // answer false. 10143 if (!PendingMerges.insert(Phi).second) 10144 return false; 10145 RPhi = Phi; 10146 } 10147 10148 // If none of LHS, RHS is a Phi, nothing to do here. 10149 if (!LPhi && !RPhi) 10150 return false; 10151 10152 // If there is a SCEVUnknown Phi we are interested in, make it left. 10153 if (!LPhi) { 10154 std::swap(LHS, RHS); 10155 std::swap(FoundLHS, FoundRHS); 10156 std::swap(LPhi, RPhi); 10157 Pred = ICmpInst::getSwappedPredicate(Pred); 10158 } 10159 10160 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10161 const BasicBlock *LBB = LPhi->getParent(); 10162 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10163 10164 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10165 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10166 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10167 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10168 }; 10169 10170 if (RPhi && RPhi->getParent() == LBB) { 10171 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10172 // If we compare two Phis from the same block, and for each entry block 10173 // the predicate is true for incoming values from this block, then the 10174 // predicate is also true for the Phis. 10175 for (const BasicBlock *IncBB : predecessors(LBB)) { 10176 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10177 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10178 if (!ProvedEasily(L, R)) 10179 return false; 10180 } 10181 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10182 // Case two: RHS is also a Phi from the same basic block, and it is an 10183 // AddRec. It means that there is a loop which has both AddRec and Unknown 10184 // PHIs, for it we can compare incoming values of AddRec from above the loop 10185 // and latch with their respective incoming values of LPhi. 10186 // TODO: Generalize to handle loops with many inputs in a header. 10187 if (LPhi->getNumIncomingValues() != 2) return false; 10188 10189 auto *RLoop = RAR->getLoop(); 10190 auto *Predecessor = RLoop->getLoopPredecessor(); 10191 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10192 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10193 if (!ProvedEasily(L1, RAR->getStart())) 10194 return false; 10195 auto *Latch = RLoop->getLoopLatch(); 10196 assert(Latch && "Loop with AddRec with no latch?"); 10197 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10198 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10199 return false; 10200 } else { 10201 // In all other cases go over inputs of LHS and compare each of them to RHS, 10202 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10203 // At this point RHS is either a non-Phi, or it is a Phi from some block 10204 // different from LBB. 10205 for (const BasicBlock *IncBB : predecessors(LBB)) { 10206 // Check that RHS is available in this block. 10207 if (!dominates(RHS, IncBB)) 10208 return false; 10209 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10210 if (!ProvedEasily(L, RHS)) 10211 return false; 10212 } 10213 } 10214 return true; 10215 } 10216 10217 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10218 const SCEV *LHS, const SCEV *RHS, 10219 const SCEV *FoundLHS, 10220 const SCEV *FoundRHS) { 10221 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10222 return true; 10223 10224 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10225 return true; 10226 10227 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10228 FoundLHS, FoundRHS) || 10229 // ~x < ~y --> x > y 10230 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10231 getNotSCEV(FoundRHS), 10232 getNotSCEV(FoundLHS)); 10233 } 10234 10235 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10236 template <typename MinMaxExprType> 10237 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10238 const SCEV *Candidate) { 10239 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10240 if (!MinMaxExpr) 10241 return false; 10242 10243 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10244 } 10245 10246 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10247 ICmpInst::Predicate Pred, 10248 const SCEV *LHS, const SCEV *RHS) { 10249 // If both sides are affine addrecs for the same loop, with equal 10250 // steps, and we know the recurrences don't wrap, then we only 10251 // need to check the predicate on the starting values. 10252 10253 if (!ICmpInst::isRelational(Pred)) 10254 return false; 10255 10256 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10257 if (!LAR) 10258 return false; 10259 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10260 if (!RAR) 10261 return false; 10262 if (LAR->getLoop() != RAR->getLoop()) 10263 return false; 10264 if (!LAR->isAffine() || !RAR->isAffine()) 10265 return false; 10266 10267 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10268 return false; 10269 10270 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10271 SCEV::FlagNSW : SCEV::FlagNUW; 10272 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10273 return false; 10274 10275 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10276 } 10277 10278 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10279 /// expression? 10280 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10281 ICmpInst::Predicate Pred, 10282 const SCEV *LHS, const SCEV *RHS) { 10283 switch (Pred) { 10284 default: 10285 return false; 10286 10287 case ICmpInst::ICMP_SGE: 10288 std::swap(LHS, RHS); 10289 LLVM_FALLTHROUGH; 10290 case ICmpInst::ICMP_SLE: 10291 return 10292 // min(A, ...) <= A 10293 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10294 // A <= max(A, ...) 10295 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10296 10297 case ICmpInst::ICMP_UGE: 10298 std::swap(LHS, RHS); 10299 LLVM_FALLTHROUGH; 10300 case ICmpInst::ICMP_ULE: 10301 return 10302 // min(A, ...) <= A 10303 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10304 // A <= max(A, ...) 10305 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10306 } 10307 10308 llvm_unreachable("covered switch fell through?!"); 10309 } 10310 10311 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10312 const SCEV *LHS, const SCEV *RHS, 10313 const SCEV *FoundLHS, 10314 const SCEV *FoundRHS, 10315 unsigned Depth) { 10316 assert(getTypeSizeInBits(LHS->getType()) == 10317 getTypeSizeInBits(RHS->getType()) && 10318 "LHS and RHS have different sizes?"); 10319 assert(getTypeSizeInBits(FoundLHS->getType()) == 10320 getTypeSizeInBits(FoundRHS->getType()) && 10321 "FoundLHS and FoundRHS have different sizes?"); 10322 // We want to avoid hurting the compile time with analysis of too big trees. 10323 if (Depth > MaxSCEVOperationsImplicationDepth) 10324 return false; 10325 // We only want to work with ICMP_SGT comparison so far. 10326 // TODO: Extend to ICMP_UGT? 10327 if (Pred == ICmpInst::ICMP_SLT) { 10328 Pred = ICmpInst::ICMP_SGT; 10329 std::swap(LHS, RHS); 10330 std::swap(FoundLHS, FoundRHS); 10331 } 10332 if (Pred != ICmpInst::ICMP_SGT) 10333 return false; 10334 10335 auto GetOpFromSExt = [&](const SCEV *S) { 10336 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10337 return Ext->getOperand(); 10338 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10339 // the constant in some cases. 10340 return S; 10341 }; 10342 10343 // Acquire values from extensions. 10344 auto *OrigLHS = LHS; 10345 auto *OrigFoundLHS = FoundLHS; 10346 LHS = GetOpFromSExt(LHS); 10347 FoundLHS = GetOpFromSExt(FoundLHS); 10348 10349 // Is the SGT predicate can be proved trivially or using the found context. 10350 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10351 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10352 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10353 FoundRHS, Depth + 1); 10354 }; 10355 10356 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10357 // We want to avoid creation of any new non-constant SCEV. Since we are 10358 // going to compare the operands to RHS, we should be certain that we don't 10359 // need any size extensions for this. So let's decline all cases when the 10360 // sizes of types of LHS and RHS do not match. 10361 // TODO: Maybe try to get RHS from sext to catch more cases? 10362 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10363 return false; 10364 10365 // Should not overflow. 10366 if (!LHSAddExpr->hasNoSignedWrap()) 10367 return false; 10368 10369 auto *LL = LHSAddExpr->getOperand(0); 10370 auto *LR = LHSAddExpr->getOperand(1); 10371 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType())); 10372 10373 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10374 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10375 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10376 }; 10377 // Try to prove the following rule: 10378 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10379 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10380 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10381 return true; 10382 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10383 Value *LL, *LR; 10384 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10385 10386 using namespace llvm::PatternMatch; 10387 10388 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10389 // Rules for division. 10390 // We are going to perform some comparisons with Denominator and its 10391 // derivative expressions. In general case, creating a SCEV for it may 10392 // lead to a complex analysis of the entire graph, and in particular it 10393 // can request trip count recalculation for the same loop. This would 10394 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10395 // this, we only want to create SCEVs that are constants in this section. 10396 // So we bail if Denominator is not a constant. 10397 if (!isa<ConstantInt>(LR)) 10398 return false; 10399 10400 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10401 10402 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10403 // then a SCEV for the numerator already exists and matches with FoundLHS. 10404 auto *Numerator = getExistingSCEV(LL); 10405 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10406 return false; 10407 10408 // Make sure that the numerator matches with FoundLHS and the denominator 10409 // is positive. 10410 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10411 return false; 10412 10413 auto *DTy = Denominator->getType(); 10414 auto *FRHSTy = FoundRHS->getType(); 10415 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10416 // One of types is a pointer and another one is not. We cannot extend 10417 // them properly to a wider type, so let us just reject this case. 10418 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10419 // to avoid this check. 10420 return false; 10421 10422 // Given that: 10423 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10424 auto *WTy = getWiderType(DTy, FRHSTy); 10425 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10426 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10427 10428 // Try to prove the following rule: 10429 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10430 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10431 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10432 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10433 if (isKnownNonPositive(RHS) && 10434 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10435 return true; 10436 10437 // Try to prove the following rule: 10438 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10439 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10440 // If we divide it by Denominator > 2, then: 10441 // 1. If FoundLHS is negative, then the result is 0. 10442 // 2. If FoundLHS is non-negative, then the result is non-negative. 10443 // Anyways, the result is non-negative. 10444 auto *MinusOne = getNegativeSCEV(getOne(WTy)); 10445 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10446 if (isKnownNegative(RHS) && 10447 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10448 return true; 10449 } 10450 } 10451 10452 // If our expression contained SCEVUnknown Phis, and we split it down and now 10453 // need to prove something for them, try to prove the predicate for every 10454 // possible incoming values of those Phis. 10455 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10456 return true; 10457 10458 return false; 10459 } 10460 10461 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10462 const SCEV *LHS, const SCEV *RHS) { 10463 // zext x u<= sext x, sext x s<= zext x 10464 switch (Pred) { 10465 case ICmpInst::ICMP_SGE: 10466 std::swap(LHS, RHS); 10467 LLVM_FALLTHROUGH; 10468 case ICmpInst::ICMP_SLE: { 10469 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10470 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10471 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10472 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10473 return true; 10474 break; 10475 } 10476 case ICmpInst::ICMP_UGE: 10477 std::swap(LHS, RHS); 10478 LLVM_FALLTHROUGH; 10479 case ICmpInst::ICMP_ULE: { 10480 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10481 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10482 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10483 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10484 return true; 10485 break; 10486 } 10487 default: 10488 break; 10489 }; 10490 return false; 10491 } 10492 10493 bool 10494 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10495 const SCEV *LHS, const SCEV *RHS) { 10496 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10497 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10498 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10499 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10500 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10501 } 10502 10503 bool 10504 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10505 const SCEV *LHS, const SCEV *RHS, 10506 const SCEV *FoundLHS, 10507 const SCEV *FoundRHS) { 10508 switch (Pred) { 10509 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10510 case ICmpInst::ICMP_EQ: 10511 case ICmpInst::ICMP_NE: 10512 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10513 return true; 10514 break; 10515 case ICmpInst::ICMP_SLT: 10516 case ICmpInst::ICMP_SLE: 10517 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10518 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10519 return true; 10520 break; 10521 case ICmpInst::ICMP_SGT: 10522 case ICmpInst::ICMP_SGE: 10523 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10524 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10525 return true; 10526 break; 10527 case ICmpInst::ICMP_ULT: 10528 case ICmpInst::ICMP_ULE: 10529 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10530 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10531 return true; 10532 break; 10533 case ICmpInst::ICMP_UGT: 10534 case ICmpInst::ICMP_UGE: 10535 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10536 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10537 return true; 10538 break; 10539 } 10540 10541 // Maybe it can be proved via operations? 10542 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10543 return true; 10544 10545 return false; 10546 } 10547 10548 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10549 const SCEV *LHS, 10550 const SCEV *RHS, 10551 const SCEV *FoundLHS, 10552 const SCEV *FoundRHS) { 10553 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10554 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10555 // reduce the compile time impact of this optimization. 10556 return false; 10557 10558 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10559 if (!Addend) 10560 return false; 10561 10562 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10563 10564 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10565 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10566 ConstantRange FoundLHSRange = 10567 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10568 10569 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10570 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10571 10572 // We can also compute the range of values for `LHS` that satisfy the 10573 // consequent, "`LHS` `Pred` `RHS`": 10574 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10575 ConstantRange SatisfyingLHSRange = 10576 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10577 10578 // The antecedent implies the consequent if every value of `LHS` that 10579 // satisfies the antecedent also satisfies the consequent. 10580 return SatisfyingLHSRange.contains(LHSRange); 10581 } 10582 10583 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10584 bool IsSigned, bool NoWrap) { 10585 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10586 10587 if (NoWrap) return false; 10588 10589 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10590 const SCEV *One = getOne(Stride->getType()); 10591 10592 if (IsSigned) { 10593 APInt MaxRHS = getSignedRangeMax(RHS); 10594 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10595 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10596 10597 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10598 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10599 } 10600 10601 APInt MaxRHS = getUnsignedRangeMax(RHS); 10602 APInt MaxValue = APInt::getMaxValue(BitWidth); 10603 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10604 10605 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10606 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10607 } 10608 10609 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10610 bool IsSigned, bool NoWrap) { 10611 if (NoWrap) return false; 10612 10613 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10614 const SCEV *One = getOne(Stride->getType()); 10615 10616 if (IsSigned) { 10617 APInt MinRHS = getSignedRangeMin(RHS); 10618 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10619 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10620 10621 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10622 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10623 } 10624 10625 APInt MinRHS = getUnsignedRangeMin(RHS); 10626 APInt MinValue = APInt::getMinValue(BitWidth); 10627 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10628 10629 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10630 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10631 } 10632 10633 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10634 bool Equality) { 10635 const SCEV *One = getOne(Step->getType()); 10636 Delta = Equality ? getAddExpr(Delta, Step) 10637 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10638 return getUDivExpr(Delta, Step); 10639 } 10640 10641 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10642 const SCEV *Stride, 10643 const SCEV *End, 10644 unsigned BitWidth, 10645 bool IsSigned) { 10646 10647 assert(!isKnownNonPositive(Stride) && 10648 "Stride is expected strictly positive!"); 10649 // Calculate the maximum backedge count based on the range of values 10650 // permitted by Start, End, and Stride. 10651 const SCEV *MaxBECount; 10652 APInt MinStart = 10653 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10654 10655 APInt StrideForMaxBECount = 10656 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10657 10658 // We already know that the stride is positive, so we paper over conservatism 10659 // in our range computation by forcing StrideForMaxBECount to be at least one. 10660 // In theory this is unnecessary, but we expect MaxBECount to be a 10661 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10662 // is nothing to constant fold it to). 10663 APInt One(BitWidth, 1, IsSigned); 10664 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10665 10666 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10667 : APInt::getMaxValue(BitWidth); 10668 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10669 10670 // Although End can be a MAX expression we estimate MaxEnd considering only 10671 // the case End = RHS of the loop termination condition. This is safe because 10672 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10673 // taken count. 10674 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 10675 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 10676 10677 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 10678 getConstant(StrideForMaxBECount) /* Step */, 10679 false /* Equality */); 10680 10681 return MaxBECount; 10682 } 10683 10684 ScalarEvolution::ExitLimit 10685 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 10686 const Loop *L, bool IsSigned, 10687 bool ControlsExit, bool AllowPredicates) { 10688 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10689 10690 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10691 bool PredicatedIV = false; 10692 10693 if (!IV && AllowPredicates) { 10694 // Try to make this an AddRec using runtime tests, in the first X 10695 // iterations of this loop, where X is the SCEV expression found by the 10696 // algorithm below. 10697 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10698 PredicatedIV = true; 10699 } 10700 10701 // Avoid weird loops 10702 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10703 return getCouldNotCompute(); 10704 10705 bool NoWrap = ControlsExit && 10706 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10707 10708 const SCEV *Stride = IV->getStepRecurrence(*this); 10709 10710 bool PositiveStride = isKnownPositive(Stride); 10711 10712 // Avoid negative or zero stride values. 10713 if (!PositiveStride) { 10714 // We can compute the correct backedge taken count for loops with unknown 10715 // strides if we can prove that the loop is not an infinite loop with side 10716 // effects. Here's the loop structure we are trying to handle - 10717 // 10718 // i = start 10719 // do { 10720 // A[i] = i; 10721 // i += s; 10722 // } while (i < end); 10723 // 10724 // The backedge taken count for such loops is evaluated as - 10725 // (max(end, start + stride) - start - 1) /u stride 10726 // 10727 // The additional preconditions that we need to check to prove correctness 10728 // of the above formula is as follows - 10729 // 10730 // a) IV is either nuw or nsw depending upon signedness (indicated by the 10731 // NoWrap flag). 10732 // b) loop is single exit with no side effects. 10733 // 10734 // 10735 // Precondition a) implies that if the stride is negative, this is a single 10736 // trip loop. The backedge taken count formula reduces to zero in this case. 10737 // 10738 // Precondition b) implies that the unknown stride cannot be zero otherwise 10739 // we have UB. 10740 // 10741 // The positive stride case is the same as isKnownPositive(Stride) returning 10742 // true (original behavior of the function). 10743 // 10744 // We want to make sure that the stride is truly unknown as there are edge 10745 // cases where ScalarEvolution propagates no wrap flags to the 10746 // post-increment/decrement IV even though the increment/decrement operation 10747 // itself is wrapping. The computed backedge taken count may be wrong in 10748 // such cases. This is prevented by checking that the stride is not known to 10749 // be either positive or non-positive. For example, no wrap flags are 10750 // propagated to the post-increment IV of this loop with a trip count of 2 - 10751 // 10752 // unsigned char i; 10753 // for(i=127; i<128; i+=129) 10754 // A[i] = i; 10755 // 10756 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 10757 !loopHasNoSideEffects(L)) 10758 return getCouldNotCompute(); 10759 } else if (!Stride->isOne() && 10760 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 10761 // Avoid proven overflow cases: this will ensure that the backedge taken 10762 // count will not generate any unsigned overflow. Relaxed no-overflow 10763 // conditions exploit NoWrapFlags, allowing to optimize in presence of 10764 // undefined behaviors like the case of C language. 10765 return getCouldNotCompute(); 10766 10767 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 10768 : ICmpInst::ICMP_ULT; 10769 const SCEV *Start = IV->getStart(); 10770 const SCEV *End = RHS; 10771 // When the RHS is not invariant, we do not know the end bound of the loop and 10772 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 10773 // calculate the MaxBECount, given the start, stride and max value for the end 10774 // bound of the loop (RHS), and the fact that IV does not overflow (which is 10775 // checked above). 10776 if (!isLoopInvariant(RHS, L)) { 10777 const SCEV *MaxBECount = computeMaxBECountForLT( 10778 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10779 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 10780 false /*MaxOrZero*/, Predicates); 10781 } 10782 // If the backedge is taken at least once, then it will be taken 10783 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 10784 // is the LHS value of the less-than comparison the first time it is evaluated 10785 // and End is the RHS. 10786 const SCEV *BECountIfBackedgeTaken = 10787 computeBECount(getMinusSCEV(End, Start), Stride, false); 10788 // If the loop entry is guarded by the result of the backedge test of the 10789 // first loop iteration, then we know the backedge will be taken at least 10790 // once and so the backedge taken count is as above. If not then we use the 10791 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 10792 // as if the backedge is taken at least once max(End,Start) is End and so the 10793 // result is as above, and if not max(End,Start) is Start so we get a backedge 10794 // count of zero. 10795 const SCEV *BECount; 10796 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 10797 BECount = BECountIfBackedgeTaken; 10798 else { 10799 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 10800 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 10801 } 10802 10803 const SCEV *MaxBECount; 10804 bool MaxOrZero = false; 10805 if (isa<SCEVConstant>(BECount)) 10806 MaxBECount = BECount; 10807 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 10808 // If we know exactly how many times the backedge will be taken if it's 10809 // taken at least once, then the backedge count will either be that or 10810 // zero. 10811 MaxBECount = BECountIfBackedgeTaken; 10812 MaxOrZero = true; 10813 } else { 10814 MaxBECount = computeMaxBECountForLT( 10815 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 10816 } 10817 10818 if (isa<SCEVCouldNotCompute>(MaxBECount) && 10819 !isa<SCEVCouldNotCompute>(BECount)) 10820 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 10821 10822 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 10823 } 10824 10825 ScalarEvolution::ExitLimit 10826 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 10827 const Loop *L, bool IsSigned, 10828 bool ControlsExit, bool AllowPredicates) { 10829 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 10830 // We handle only IV > Invariant 10831 if (!isLoopInvariant(RHS, L)) 10832 return getCouldNotCompute(); 10833 10834 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 10835 if (!IV && AllowPredicates) 10836 // Try to make this an AddRec using runtime tests, in the first X 10837 // iterations of this loop, where X is the SCEV expression found by the 10838 // algorithm below. 10839 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 10840 10841 // Avoid weird loops 10842 if (!IV || IV->getLoop() != L || !IV->isAffine()) 10843 return getCouldNotCompute(); 10844 10845 bool NoWrap = ControlsExit && 10846 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 10847 10848 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 10849 10850 // Avoid negative or zero stride values 10851 if (!isKnownPositive(Stride)) 10852 return getCouldNotCompute(); 10853 10854 // Avoid proven overflow cases: this will ensure that the backedge taken count 10855 // will not generate any unsigned overflow. Relaxed no-overflow conditions 10856 // exploit NoWrapFlags, allowing to optimize in presence of undefined 10857 // behaviors like the case of C language. 10858 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 10859 return getCouldNotCompute(); 10860 10861 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 10862 : ICmpInst::ICMP_UGT; 10863 10864 const SCEV *Start = IV->getStart(); 10865 const SCEV *End = RHS; 10866 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) 10867 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 10868 10869 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 10870 10871 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 10872 : getUnsignedRangeMax(Start); 10873 10874 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 10875 : getUnsignedRangeMin(Stride); 10876 10877 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 10878 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 10879 : APInt::getMinValue(BitWidth) + (MinStride - 1); 10880 10881 // Although End can be a MIN expression we estimate MinEnd considering only 10882 // the case End = RHS. This is safe because in the other case (Start - End) 10883 // is zero, leading to a zero maximum backedge taken count. 10884 APInt MinEnd = 10885 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 10886 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 10887 10888 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 10889 ? BECount 10890 : computeBECount(getConstant(MaxStart - MinEnd), 10891 getConstant(MinStride), false); 10892 10893 if (isa<SCEVCouldNotCompute>(MaxBECount)) 10894 MaxBECount = BECount; 10895 10896 return ExitLimit(BECount, MaxBECount, false, Predicates); 10897 } 10898 10899 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 10900 ScalarEvolution &SE) const { 10901 if (Range.isFullSet()) // Infinite loop. 10902 return SE.getCouldNotCompute(); 10903 10904 // If the start is a non-zero constant, shift the range to simplify things. 10905 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 10906 if (!SC->getValue()->isZero()) { 10907 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 10908 Operands[0] = SE.getZero(SC->getType()); 10909 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 10910 getNoWrapFlags(FlagNW)); 10911 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 10912 return ShiftedAddRec->getNumIterationsInRange( 10913 Range.subtract(SC->getAPInt()), SE); 10914 // This is strange and shouldn't happen. 10915 return SE.getCouldNotCompute(); 10916 } 10917 10918 // The only time we can solve this is when we have all constant indices. 10919 // Otherwise, we cannot determine the overflow conditions. 10920 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 10921 return SE.getCouldNotCompute(); 10922 10923 // Okay at this point we know that all elements of the chrec are constants and 10924 // that the start element is zero. 10925 10926 // First check to see if the range contains zero. If not, the first 10927 // iteration exits. 10928 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 10929 if (!Range.contains(APInt(BitWidth, 0))) 10930 return SE.getZero(getType()); 10931 10932 if (isAffine()) { 10933 // If this is an affine expression then we have this situation: 10934 // Solve {0,+,A} in Range === Ax in Range 10935 10936 // We know that zero is in the range. If A is positive then we know that 10937 // the upper value of the range must be the first possible exit value. 10938 // If A is negative then the lower of the range is the last possible loop 10939 // value. Also note that we already checked for a full range. 10940 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 10941 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 10942 10943 // The exit value should be (End+A)/A. 10944 APInt ExitVal = (End + A).udiv(A); 10945 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 10946 10947 // Evaluate at the exit value. If we really did fall out of the valid 10948 // range, then we computed our trip count, otherwise wrap around or other 10949 // things must have happened. 10950 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 10951 if (Range.contains(Val->getValue())) 10952 return SE.getCouldNotCompute(); // Something strange happened 10953 10954 // Ensure that the previous value is in the range. This is a sanity check. 10955 assert(Range.contains( 10956 EvaluateConstantChrecAtConstant(this, 10957 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 10958 "Linear scev computation is off in a bad way!"); 10959 return SE.getConstant(ExitValue); 10960 } 10961 10962 if (isQuadratic()) { 10963 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 10964 return SE.getConstant(S.getValue()); 10965 } 10966 10967 return SE.getCouldNotCompute(); 10968 } 10969 10970 const SCEVAddRecExpr * 10971 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 10972 assert(getNumOperands() > 1 && "AddRec with zero step?"); 10973 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 10974 // but in this case we cannot guarantee that the value returned will be an 10975 // AddRec because SCEV does not have a fixed point where it stops 10976 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 10977 // may happen if we reach arithmetic depth limit while simplifying. So we 10978 // construct the returned value explicitly. 10979 SmallVector<const SCEV *, 3> Ops; 10980 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 10981 // (this + Step) is {A+B,+,B+C,+...,+,N}. 10982 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 10983 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 10984 // We know that the last operand is not a constant zero (otherwise it would 10985 // have been popped out earlier). This guarantees us that if the result has 10986 // the same last operand, then it will also not be popped out, meaning that 10987 // the returned value will be an AddRec. 10988 const SCEV *Last = getOperand(getNumOperands() - 1); 10989 assert(!Last->isZero() && "Recurrency with zero step?"); 10990 Ops.push_back(Last); 10991 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 10992 SCEV::FlagAnyWrap)); 10993 } 10994 10995 // Return true when S contains at least an undef value. 10996 static inline bool containsUndefs(const SCEV *S) { 10997 return SCEVExprContains(S, [](const SCEV *S) { 10998 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 10999 return isa<UndefValue>(SU->getValue()); 11000 return false; 11001 }); 11002 } 11003 11004 namespace { 11005 11006 // Collect all steps of SCEV expressions. 11007 struct SCEVCollectStrides { 11008 ScalarEvolution &SE; 11009 SmallVectorImpl<const SCEV *> &Strides; 11010 11011 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11012 : SE(SE), Strides(S) {} 11013 11014 bool follow(const SCEV *S) { 11015 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11016 Strides.push_back(AR->getStepRecurrence(SE)); 11017 return true; 11018 } 11019 11020 bool isDone() const { return false; } 11021 }; 11022 11023 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11024 struct SCEVCollectTerms { 11025 SmallVectorImpl<const SCEV *> &Terms; 11026 11027 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11028 11029 bool follow(const SCEV *S) { 11030 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11031 isa<SCEVSignExtendExpr>(S)) { 11032 if (!containsUndefs(S)) 11033 Terms.push_back(S); 11034 11035 // Stop recursion: once we collected a term, do not walk its operands. 11036 return false; 11037 } 11038 11039 // Keep looking. 11040 return true; 11041 } 11042 11043 bool isDone() const { return false; } 11044 }; 11045 11046 // Check if a SCEV contains an AddRecExpr. 11047 struct SCEVHasAddRec { 11048 bool &ContainsAddRec; 11049 11050 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11051 ContainsAddRec = false; 11052 } 11053 11054 bool follow(const SCEV *S) { 11055 if (isa<SCEVAddRecExpr>(S)) { 11056 ContainsAddRec = true; 11057 11058 // Stop recursion: once we collected a term, do not walk its operands. 11059 return false; 11060 } 11061 11062 // Keep looking. 11063 return true; 11064 } 11065 11066 bool isDone() const { return false; } 11067 }; 11068 11069 // Find factors that are multiplied with an expression that (possibly as a 11070 // subexpression) contains an AddRecExpr. In the expression: 11071 // 11072 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11073 // 11074 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11075 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11076 // parameters as they form a product with an induction variable. 11077 // 11078 // This collector expects all array size parameters to be in the same MulExpr. 11079 // It might be necessary to later add support for collecting parameters that are 11080 // spread over different nested MulExpr. 11081 struct SCEVCollectAddRecMultiplies { 11082 SmallVectorImpl<const SCEV *> &Terms; 11083 ScalarEvolution &SE; 11084 11085 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11086 : Terms(T), SE(SE) {} 11087 11088 bool follow(const SCEV *S) { 11089 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11090 bool HasAddRec = false; 11091 SmallVector<const SCEV *, 0> Operands; 11092 for (auto Op : Mul->operands()) { 11093 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11094 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11095 Operands.push_back(Op); 11096 } else if (Unknown) { 11097 HasAddRec = true; 11098 } else { 11099 bool ContainsAddRec = false; 11100 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11101 visitAll(Op, ContiansAddRec); 11102 HasAddRec |= ContainsAddRec; 11103 } 11104 } 11105 if (Operands.size() == 0) 11106 return true; 11107 11108 if (!HasAddRec) 11109 return false; 11110 11111 Terms.push_back(SE.getMulExpr(Operands)); 11112 // Stop recursion: once we collected a term, do not walk its operands. 11113 return false; 11114 } 11115 11116 // Keep looking. 11117 return true; 11118 } 11119 11120 bool isDone() const { return false; } 11121 }; 11122 11123 } // end anonymous namespace 11124 11125 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11126 /// two places: 11127 /// 1) The strides of AddRec expressions. 11128 /// 2) Unknowns that are multiplied with AddRec expressions. 11129 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11130 SmallVectorImpl<const SCEV *> &Terms) { 11131 SmallVector<const SCEV *, 4> Strides; 11132 SCEVCollectStrides StrideCollector(*this, Strides); 11133 visitAll(Expr, StrideCollector); 11134 11135 LLVM_DEBUG({ 11136 dbgs() << "Strides:\n"; 11137 for (const SCEV *S : Strides) 11138 dbgs() << *S << "\n"; 11139 }); 11140 11141 for (const SCEV *S : Strides) { 11142 SCEVCollectTerms TermCollector(Terms); 11143 visitAll(S, TermCollector); 11144 } 11145 11146 LLVM_DEBUG({ 11147 dbgs() << "Terms:\n"; 11148 for (const SCEV *T : Terms) 11149 dbgs() << *T << "\n"; 11150 }); 11151 11152 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11153 visitAll(Expr, MulCollector); 11154 } 11155 11156 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11157 SmallVectorImpl<const SCEV *> &Terms, 11158 SmallVectorImpl<const SCEV *> &Sizes) { 11159 int Last = Terms.size() - 1; 11160 const SCEV *Step = Terms[Last]; 11161 11162 // End of recursion. 11163 if (Last == 0) { 11164 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11165 SmallVector<const SCEV *, 2> Qs; 11166 for (const SCEV *Op : M->operands()) 11167 if (!isa<SCEVConstant>(Op)) 11168 Qs.push_back(Op); 11169 11170 Step = SE.getMulExpr(Qs); 11171 } 11172 11173 Sizes.push_back(Step); 11174 return true; 11175 } 11176 11177 for (const SCEV *&Term : Terms) { 11178 // Normalize the terms before the next call to findArrayDimensionsRec. 11179 const SCEV *Q, *R; 11180 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11181 11182 // Bail out when GCD does not evenly divide one of the terms. 11183 if (!R->isZero()) 11184 return false; 11185 11186 Term = Q; 11187 } 11188 11189 // Remove all SCEVConstants. 11190 Terms.erase( 11191 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11192 Terms.end()); 11193 11194 if (Terms.size() > 0) 11195 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11196 return false; 11197 11198 Sizes.push_back(Step); 11199 return true; 11200 } 11201 11202 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11203 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11204 for (const SCEV *T : Terms) 11205 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>)) 11206 return true; 11207 return false; 11208 } 11209 11210 // Return the number of product terms in S. 11211 static inline int numberOfTerms(const SCEV *S) { 11212 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11213 return Expr->getNumOperands(); 11214 return 1; 11215 } 11216 11217 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11218 if (isa<SCEVConstant>(T)) 11219 return nullptr; 11220 11221 if (isa<SCEVUnknown>(T)) 11222 return T; 11223 11224 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11225 SmallVector<const SCEV *, 2> Factors; 11226 for (const SCEV *Op : M->operands()) 11227 if (!isa<SCEVConstant>(Op)) 11228 Factors.push_back(Op); 11229 11230 return SE.getMulExpr(Factors); 11231 } 11232 11233 return T; 11234 } 11235 11236 /// Return the size of an element read or written by Inst. 11237 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11238 Type *Ty; 11239 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11240 Ty = Store->getValueOperand()->getType(); 11241 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11242 Ty = Load->getType(); 11243 else 11244 return nullptr; 11245 11246 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11247 return getSizeOfExpr(ETy, Ty); 11248 } 11249 11250 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11251 SmallVectorImpl<const SCEV *> &Sizes, 11252 const SCEV *ElementSize) { 11253 if (Terms.size() < 1 || !ElementSize) 11254 return; 11255 11256 // Early return when Terms do not contain parameters: we do not delinearize 11257 // non parametric SCEVs. 11258 if (!containsParameters(Terms)) 11259 return; 11260 11261 LLVM_DEBUG({ 11262 dbgs() << "Terms:\n"; 11263 for (const SCEV *T : Terms) 11264 dbgs() << *T << "\n"; 11265 }); 11266 11267 // Remove duplicates. 11268 array_pod_sort(Terms.begin(), Terms.end()); 11269 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11270 11271 // Put larger terms first. 11272 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11273 return numberOfTerms(LHS) > numberOfTerms(RHS); 11274 }); 11275 11276 // Try to divide all terms by the element size. If term is not divisible by 11277 // element size, proceed with the original term. 11278 for (const SCEV *&Term : Terms) { 11279 const SCEV *Q, *R; 11280 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11281 if (!Q->isZero()) 11282 Term = Q; 11283 } 11284 11285 SmallVector<const SCEV *, 4> NewTerms; 11286 11287 // Remove constant factors. 11288 for (const SCEV *T : Terms) 11289 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11290 NewTerms.push_back(NewT); 11291 11292 LLVM_DEBUG({ 11293 dbgs() << "Terms after sorting:\n"; 11294 for (const SCEV *T : NewTerms) 11295 dbgs() << *T << "\n"; 11296 }); 11297 11298 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11299 Sizes.clear(); 11300 return; 11301 } 11302 11303 // The last element to be pushed into Sizes is the size of an element. 11304 Sizes.push_back(ElementSize); 11305 11306 LLVM_DEBUG({ 11307 dbgs() << "Sizes:\n"; 11308 for (const SCEV *S : Sizes) 11309 dbgs() << *S << "\n"; 11310 }); 11311 } 11312 11313 void ScalarEvolution::computeAccessFunctions( 11314 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11315 SmallVectorImpl<const SCEV *> &Sizes) { 11316 // Early exit in case this SCEV is not an affine multivariate function. 11317 if (Sizes.empty()) 11318 return; 11319 11320 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11321 if (!AR->isAffine()) 11322 return; 11323 11324 const SCEV *Res = Expr; 11325 int Last = Sizes.size() - 1; 11326 for (int i = Last; i >= 0; i--) { 11327 const SCEV *Q, *R; 11328 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11329 11330 LLVM_DEBUG({ 11331 dbgs() << "Res: " << *Res << "\n"; 11332 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11333 dbgs() << "Res divided by Sizes[i]:\n"; 11334 dbgs() << "Quotient: " << *Q << "\n"; 11335 dbgs() << "Remainder: " << *R << "\n"; 11336 }); 11337 11338 Res = Q; 11339 11340 // Do not record the last subscript corresponding to the size of elements in 11341 // the array. 11342 if (i == Last) { 11343 11344 // Bail out if the remainder is too complex. 11345 if (isa<SCEVAddRecExpr>(R)) { 11346 Subscripts.clear(); 11347 Sizes.clear(); 11348 return; 11349 } 11350 11351 continue; 11352 } 11353 11354 // Record the access function for the current subscript. 11355 Subscripts.push_back(R); 11356 } 11357 11358 // Also push in last position the remainder of the last division: it will be 11359 // the access function of the innermost dimension. 11360 Subscripts.push_back(Res); 11361 11362 std::reverse(Subscripts.begin(), Subscripts.end()); 11363 11364 LLVM_DEBUG({ 11365 dbgs() << "Subscripts:\n"; 11366 for (const SCEV *S : Subscripts) 11367 dbgs() << *S << "\n"; 11368 }); 11369 } 11370 11371 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11372 /// sizes of an array access. Returns the remainder of the delinearization that 11373 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11374 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11375 /// expressions in the stride and base of a SCEV corresponding to the 11376 /// computation of a GCD (greatest common divisor) of base and stride. When 11377 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11378 /// 11379 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11380 /// 11381 /// void foo(long n, long m, long o, double A[n][m][o]) { 11382 /// 11383 /// for (long i = 0; i < n; i++) 11384 /// for (long j = 0; j < m; j++) 11385 /// for (long k = 0; k < o; k++) 11386 /// A[i][j][k] = 1.0; 11387 /// } 11388 /// 11389 /// the delinearization input is the following AddRec SCEV: 11390 /// 11391 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11392 /// 11393 /// From this SCEV, we are able to say that the base offset of the access is %A 11394 /// because it appears as an offset that does not divide any of the strides in 11395 /// the loops: 11396 /// 11397 /// CHECK: Base offset: %A 11398 /// 11399 /// and then SCEV->delinearize determines the size of some of the dimensions of 11400 /// the array as these are the multiples by which the strides are happening: 11401 /// 11402 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11403 /// 11404 /// Note that the outermost dimension remains of UnknownSize because there are 11405 /// no strides that would help identifying the size of the last dimension: when 11406 /// the array has been statically allocated, one could compute the size of that 11407 /// dimension by dividing the overall size of the array by the size of the known 11408 /// dimensions: %m * %o * 8. 11409 /// 11410 /// Finally delinearize provides the access functions for the array reference 11411 /// that does correspond to A[i][j][k] of the above C testcase: 11412 /// 11413 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11414 /// 11415 /// The testcases are checking the output of a function pass: 11416 /// DelinearizationPass that walks through all loads and stores of a function 11417 /// asking for the SCEV of the memory access with respect to all enclosing 11418 /// loops, calling SCEV->delinearize on that and printing the results. 11419 void ScalarEvolution::delinearize(const SCEV *Expr, 11420 SmallVectorImpl<const SCEV *> &Subscripts, 11421 SmallVectorImpl<const SCEV *> &Sizes, 11422 const SCEV *ElementSize) { 11423 // First step: collect parametric terms. 11424 SmallVector<const SCEV *, 4> Terms; 11425 collectParametricTerms(Expr, Terms); 11426 11427 if (Terms.empty()) 11428 return; 11429 11430 // Second step: find subscript sizes. 11431 findArrayDimensions(Terms, Sizes, ElementSize); 11432 11433 if (Sizes.empty()) 11434 return; 11435 11436 // Third step: compute the access functions for each subscript. 11437 computeAccessFunctions(Expr, Subscripts, Sizes); 11438 11439 if (Subscripts.empty()) 11440 return; 11441 11442 LLVM_DEBUG({ 11443 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11444 dbgs() << "ArrayDecl[UnknownSize]"; 11445 for (const SCEV *S : Sizes) 11446 dbgs() << "[" << *S << "]"; 11447 11448 dbgs() << "\nArrayRef"; 11449 for (const SCEV *S : Subscripts) 11450 dbgs() << "[" << *S << "]"; 11451 dbgs() << "\n"; 11452 }); 11453 } 11454 11455 bool ScalarEvolution::getIndexExpressionsFromGEP( 11456 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11457 SmallVectorImpl<int> &Sizes) { 11458 assert(Subscripts.empty() && Sizes.empty() && 11459 "Expected output lists to be empty on entry to this function."); 11460 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11461 Type *Ty = GEP->getPointerOperandType(); 11462 bool DroppedFirstDim = false; 11463 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11464 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11465 if (i == 1) { 11466 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11467 Ty = PtrTy->getElementType(); 11468 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11469 Ty = ArrayTy->getElementType(); 11470 } else { 11471 Subscripts.clear(); 11472 Sizes.clear(); 11473 return false; 11474 } 11475 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11476 if (Const->getValue()->isZero()) { 11477 DroppedFirstDim = true; 11478 continue; 11479 } 11480 Subscripts.push_back(Expr); 11481 continue; 11482 } 11483 11484 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11485 if (!ArrayTy) { 11486 Subscripts.clear(); 11487 Sizes.clear(); 11488 return false; 11489 } 11490 11491 Subscripts.push_back(Expr); 11492 if (!(DroppedFirstDim && i == 2)) 11493 Sizes.push_back(ArrayTy->getNumElements()); 11494 11495 Ty = ArrayTy->getElementType(); 11496 } 11497 return !Subscripts.empty(); 11498 } 11499 11500 //===----------------------------------------------------------------------===// 11501 // SCEVCallbackVH Class Implementation 11502 //===----------------------------------------------------------------------===// 11503 11504 void ScalarEvolution::SCEVCallbackVH::deleted() { 11505 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11506 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11507 SE->ConstantEvolutionLoopExitValue.erase(PN); 11508 SE->eraseValueFromMap(getValPtr()); 11509 // this now dangles! 11510 } 11511 11512 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11513 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11514 11515 // Forget all the expressions associated with users of the old value, 11516 // so that future queries will recompute the expressions using the new 11517 // value. 11518 Value *Old = getValPtr(); 11519 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11520 SmallPtrSet<User *, 8> Visited; 11521 while (!Worklist.empty()) { 11522 User *U = Worklist.pop_back_val(); 11523 // Deleting the Old value will cause this to dangle. Postpone 11524 // that until everything else is done. 11525 if (U == Old) 11526 continue; 11527 if (!Visited.insert(U).second) 11528 continue; 11529 if (PHINode *PN = dyn_cast<PHINode>(U)) 11530 SE->ConstantEvolutionLoopExitValue.erase(PN); 11531 SE->eraseValueFromMap(U); 11532 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11533 } 11534 // Delete the Old value. 11535 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11536 SE->ConstantEvolutionLoopExitValue.erase(PN); 11537 SE->eraseValueFromMap(Old); 11538 // this now dangles! 11539 } 11540 11541 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11542 : CallbackVH(V), SE(se) {} 11543 11544 //===----------------------------------------------------------------------===// 11545 // ScalarEvolution Class Implementation 11546 //===----------------------------------------------------------------------===// 11547 11548 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11549 AssumptionCache &AC, DominatorTree &DT, 11550 LoopInfo &LI) 11551 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11552 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11553 LoopDispositions(64), BlockDispositions(64) { 11554 // To use guards for proving predicates, we need to scan every instruction in 11555 // relevant basic blocks, and not just terminators. Doing this is a waste of 11556 // time if the IR does not actually contain any calls to 11557 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11558 // 11559 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11560 // to _add_ guards to the module when there weren't any before, and wants 11561 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11562 // efficient in lieu of being smart in that rather obscure case. 11563 11564 auto *GuardDecl = F.getParent()->getFunction( 11565 Intrinsic::getName(Intrinsic::experimental_guard)); 11566 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11567 } 11568 11569 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11570 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11571 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11572 ValueExprMap(std::move(Arg.ValueExprMap)), 11573 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11574 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11575 PendingMerges(std::move(Arg.PendingMerges)), 11576 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11577 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11578 PredicatedBackedgeTakenCounts( 11579 std::move(Arg.PredicatedBackedgeTakenCounts)), 11580 ConstantEvolutionLoopExitValue( 11581 std::move(Arg.ConstantEvolutionLoopExitValue)), 11582 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11583 LoopDispositions(std::move(Arg.LoopDispositions)), 11584 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11585 BlockDispositions(std::move(Arg.BlockDispositions)), 11586 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11587 SignedRanges(std::move(Arg.SignedRanges)), 11588 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11589 UniquePreds(std::move(Arg.UniquePreds)), 11590 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11591 LoopUsers(std::move(Arg.LoopUsers)), 11592 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11593 FirstUnknown(Arg.FirstUnknown) { 11594 Arg.FirstUnknown = nullptr; 11595 } 11596 11597 ScalarEvolution::~ScalarEvolution() { 11598 // Iterate through all the SCEVUnknown instances and call their 11599 // destructors, so that they release their references to their values. 11600 for (SCEVUnknown *U = FirstUnknown; U;) { 11601 SCEVUnknown *Tmp = U; 11602 U = U->Next; 11603 Tmp->~SCEVUnknown(); 11604 } 11605 FirstUnknown = nullptr; 11606 11607 ExprValueMap.clear(); 11608 ValueExprMap.clear(); 11609 HasRecMap.clear(); 11610 11611 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11612 // that a loop had multiple computable exits. 11613 for (auto &BTCI : BackedgeTakenCounts) 11614 BTCI.second.clear(); 11615 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11616 BTCI.second.clear(); 11617 11618 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11619 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11620 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11621 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11622 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11623 } 11624 11625 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11626 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11627 } 11628 11629 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11630 const Loop *L) { 11631 // Print all inner loops first 11632 for (Loop *I : *L) 11633 PrintLoopInfo(OS, SE, I); 11634 11635 OS << "Loop "; 11636 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11637 OS << ": "; 11638 11639 SmallVector<BasicBlock *, 8> ExitingBlocks; 11640 L->getExitingBlocks(ExitingBlocks); 11641 if (ExitingBlocks.size() != 1) 11642 OS << "<multiple exits> "; 11643 11644 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11645 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11646 else 11647 OS << "Unpredictable backedge-taken count.\n"; 11648 11649 if (ExitingBlocks.size() > 1) 11650 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11651 OS << " exit count for " << ExitingBlock->getName() << ": " 11652 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11653 } 11654 11655 OS << "Loop "; 11656 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11657 OS << ": "; 11658 11659 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11660 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 11661 if (SE->isBackedgeTakenCountMaxOrZero(L)) 11662 OS << ", actual taken count either this or zero."; 11663 } else { 11664 OS << "Unpredictable max backedge-taken count. "; 11665 } 11666 11667 OS << "\n" 11668 "Loop "; 11669 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11670 OS << ": "; 11671 11672 SCEVUnionPredicate Pred; 11673 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 11674 if (!isa<SCEVCouldNotCompute>(PBT)) { 11675 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 11676 OS << " Predicates:\n"; 11677 Pred.print(OS, 4); 11678 } else { 11679 OS << "Unpredictable predicated backedge-taken count. "; 11680 } 11681 OS << "\n"; 11682 11683 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 11684 OS << "Loop "; 11685 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11686 OS << ": "; 11687 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 11688 } 11689 } 11690 11691 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 11692 switch (LD) { 11693 case ScalarEvolution::LoopVariant: 11694 return "Variant"; 11695 case ScalarEvolution::LoopInvariant: 11696 return "Invariant"; 11697 case ScalarEvolution::LoopComputable: 11698 return "Computable"; 11699 } 11700 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 11701 } 11702 11703 void ScalarEvolution::print(raw_ostream &OS) const { 11704 // ScalarEvolution's implementation of the print method is to print 11705 // out SCEV values of all instructions that are interesting. Doing 11706 // this potentially causes it to create new SCEV objects though, 11707 // which technically conflicts with the const qualifier. This isn't 11708 // observable from outside the class though, so casting away the 11709 // const isn't dangerous. 11710 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 11711 11712 if (ClassifyExpressions) { 11713 OS << "Classifying expressions for: "; 11714 F.printAsOperand(OS, /*PrintType=*/false); 11715 OS << "\n"; 11716 for (Instruction &I : instructions(F)) 11717 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 11718 OS << I << '\n'; 11719 OS << " --> "; 11720 const SCEV *SV = SE.getSCEV(&I); 11721 SV->print(OS); 11722 if (!isa<SCEVCouldNotCompute>(SV)) { 11723 OS << " U: "; 11724 SE.getUnsignedRange(SV).print(OS); 11725 OS << " S: "; 11726 SE.getSignedRange(SV).print(OS); 11727 } 11728 11729 const Loop *L = LI.getLoopFor(I.getParent()); 11730 11731 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 11732 if (AtUse != SV) { 11733 OS << " --> "; 11734 AtUse->print(OS); 11735 if (!isa<SCEVCouldNotCompute>(AtUse)) { 11736 OS << " U: "; 11737 SE.getUnsignedRange(AtUse).print(OS); 11738 OS << " S: "; 11739 SE.getSignedRange(AtUse).print(OS); 11740 } 11741 } 11742 11743 if (L) { 11744 OS << "\t\t" "Exits: "; 11745 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 11746 if (!SE.isLoopInvariant(ExitValue, L)) { 11747 OS << "<<Unknown>>"; 11748 } else { 11749 OS << *ExitValue; 11750 } 11751 11752 bool First = true; 11753 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 11754 if (First) { 11755 OS << "\t\t" "LoopDispositions: { "; 11756 First = false; 11757 } else { 11758 OS << ", "; 11759 } 11760 11761 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11762 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 11763 } 11764 11765 for (auto *InnerL : depth_first(L)) { 11766 if (InnerL == L) 11767 continue; 11768 if (First) { 11769 OS << "\t\t" "LoopDispositions: { "; 11770 First = false; 11771 } else { 11772 OS << ", "; 11773 } 11774 11775 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11776 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 11777 } 11778 11779 OS << " }"; 11780 } 11781 11782 OS << "\n"; 11783 } 11784 } 11785 11786 OS << "Determining loop execution counts for: "; 11787 F.printAsOperand(OS, /*PrintType=*/false); 11788 OS << "\n"; 11789 for (Loop *I : LI) 11790 PrintLoopInfo(OS, &SE, I); 11791 } 11792 11793 ScalarEvolution::LoopDisposition 11794 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 11795 auto &Values = LoopDispositions[S]; 11796 for (auto &V : Values) { 11797 if (V.getPointer() == L) 11798 return V.getInt(); 11799 } 11800 Values.emplace_back(L, LoopVariant); 11801 LoopDisposition D = computeLoopDisposition(S, L); 11802 auto &Values2 = LoopDispositions[S]; 11803 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11804 if (V.getPointer() == L) { 11805 V.setInt(D); 11806 break; 11807 } 11808 } 11809 return D; 11810 } 11811 11812 ScalarEvolution::LoopDisposition 11813 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 11814 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11815 case scConstant: 11816 return LoopInvariant; 11817 case scTruncate: 11818 case scZeroExtend: 11819 case scSignExtend: 11820 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 11821 case scAddRecExpr: { 11822 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11823 11824 // If L is the addrec's loop, it's computable. 11825 if (AR->getLoop() == L) 11826 return LoopComputable; 11827 11828 // Add recurrences are never invariant in the function-body (null loop). 11829 if (!L) 11830 return LoopVariant; 11831 11832 // Everything that is not defined at loop entry is variant. 11833 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 11834 return LoopVariant; 11835 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 11836 " dominate the contained loop's header?"); 11837 11838 // This recurrence is invariant w.r.t. L if AR's loop contains L. 11839 if (AR->getLoop()->contains(L)) 11840 return LoopInvariant; 11841 11842 // This recurrence is variant w.r.t. L if any of its operands 11843 // are variant. 11844 for (auto *Op : AR->operands()) 11845 if (!isLoopInvariant(Op, L)) 11846 return LoopVariant; 11847 11848 // Otherwise it's loop-invariant. 11849 return LoopInvariant; 11850 } 11851 case scAddExpr: 11852 case scMulExpr: 11853 case scUMaxExpr: 11854 case scSMaxExpr: 11855 case scUMinExpr: 11856 case scSMinExpr: { 11857 bool HasVarying = false; 11858 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 11859 LoopDisposition D = getLoopDisposition(Op, L); 11860 if (D == LoopVariant) 11861 return LoopVariant; 11862 if (D == LoopComputable) 11863 HasVarying = true; 11864 } 11865 return HasVarying ? LoopComputable : LoopInvariant; 11866 } 11867 case scUDivExpr: { 11868 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11869 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 11870 if (LD == LoopVariant) 11871 return LoopVariant; 11872 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 11873 if (RD == LoopVariant) 11874 return LoopVariant; 11875 return (LD == LoopInvariant && RD == LoopInvariant) ? 11876 LoopInvariant : LoopComputable; 11877 } 11878 case scUnknown: 11879 // All non-instruction values are loop invariant. All instructions are loop 11880 // invariant if they are not contained in the specified loop. 11881 // Instructions are never considered invariant in the function body 11882 // (null loop) because they are defined within the "loop". 11883 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 11884 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 11885 return LoopInvariant; 11886 case scCouldNotCompute: 11887 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11888 } 11889 llvm_unreachable("Unknown SCEV kind!"); 11890 } 11891 11892 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 11893 return getLoopDisposition(S, L) == LoopInvariant; 11894 } 11895 11896 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 11897 return getLoopDisposition(S, L) == LoopComputable; 11898 } 11899 11900 ScalarEvolution::BlockDisposition 11901 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11902 auto &Values = BlockDispositions[S]; 11903 for (auto &V : Values) { 11904 if (V.getPointer() == BB) 11905 return V.getInt(); 11906 } 11907 Values.emplace_back(BB, DoesNotDominateBlock); 11908 BlockDisposition D = computeBlockDisposition(S, BB); 11909 auto &Values2 = BlockDispositions[S]; 11910 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 11911 if (V.getPointer() == BB) { 11912 V.setInt(D); 11913 break; 11914 } 11915 } 11916 return D; 11917 } 11918 11919 ScalarEvolution::BlockDisposition 11920 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 11921 switch (static_cast<SCEVTypes>(S->getSCEVType())) { 11922 case scConstant: 11923 return ProperlyDominatesBlock; 11924 case scTruncate: 11925 case scZeroExtend: 11926 case scSignExtend: 11927 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 11928 case scAddRecExpr: { 11929 // This uses a "dominates" query instead of "properly dominates" query 11930 // to test for proper dominance too, because the instruction which 11931 // produces the addrec's value is a PHI, and a PHI effectively properly 11932 // dominates its entire containing block. 11933 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 11934 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 11935 return DoesNotDominateBlock; 11936 11937 // Fall through into SCEVNAryExpr handling. 11938 LLVM_FALLTHROUGH; 11939 } 11940 case scAddExpr: 11941 case scMulExpr: 11942 case scUMaxExpr: 11943 case scSMaxExpr: 11944 case scUMinExpr: 11945 case scSMinExpr: { 11946 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 11947 bool Proper = true; 11948 for (const SCEV *NAryOp : NAry->operands()) { 11949 BlockDisposition D = getBlockDisposition(NAryOp, BB); 11950 if (D == DoesNotDominateBlock) 11951 return DoesNotDominateBlock; 11952 if (D == DominatesBlock) 11953 Proper = false; 11954 } 11955 return Proper ? ProperlyDominatesBlock : DominatesBlock; 11956 } 11957 case scUDivExpr: { 11958 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 11959 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 11960 BlockDisposition LD = getBlockDisposition(LHS, BB); 11961 if (LD == DoesNotDominateBlock) 11962 return DoesNotDominateBlock; 11963 BlockDisposition RD = getBlockDisposition(RHS, BB); 11964 if (RD == DoesNotDominateBlock) 11965 return DoesNotDominateBlock; 11966 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 11967 ProperlyDominatesBlock : DominatesBlock; 11968 } 11969 case scUnknown: 11970 if (Instruction *I = 11971 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 11972 if (I->getParent() == BB) 11973 return DominatesBlock; 11974 if (DT.properlyDominates(I->getParent(), BB)) 11975 return ProperlyDominatesBlock; 11976 return DoesNotDominateBlock; 11977 } 11978 return ProperlyDominatesBlock; 11979 case scCouldNotCompute: 11980 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 11981 } 11982 llvm_unreachable("Unknown SCEV kind!"); 11983 } 11984 11985 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 11986 return getBlockDisposition(S, BB) >= DominatesBlock; 11987 } 11988 11989 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 11990 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 11991 } 11992 11993 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 11994 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 11995 } 11996 11997 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 11998 auto IsS = [&](const SCEV *X) { return S == X; }; 11999 auto ContainsS = [&](const SCEV *X) { 12000 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 12001 }; 12002 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 12003 } 12004 12005 void 12006 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12007 ValuesAtScopes.erase(S); 12008 LoopDispositions.erase(S); 12009 BlockDispositions.erase(S); 12010 UnsignedRanges.erase(S); 12011 SignedRanges.erase(S); 12012 ExprValueMap.erase(S); 12013 HasRecMap.erase(S); 12014 MinTrailingZerosCache.erase(S); 12015 12016 for (auto I = PredicatedSCEVRewrites.begin(); 12017 I != PredicatedSCEVRewrites.end();) { 12018 std::pair<const SCEV *, const Loop *> Entry = I->first; 12019 if (Entry.first == S) 12020 PredicatedSCEVRewrites.erase(I++); 12021 else 12022 ++I; 12023 } 12024 12025 auto RemoveSCEVFromBackedgeMap = 12026 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12027 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12028 BackedgeTakenInfo &BEInfo = I->second; 12029 if (BEInfo.hasOperand(S, this)) { 12030 BEInfo.clear(); 12031 Map.erase(I++); 12032 } else 12033 ++I; 12034 } 12035 }; 12036 12037 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12038 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12039 } 12040 12041 void 12042 ScalarEvolution::getUsedLoops(const SCEV *S, 12043 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12044 struct FindUsedLoops { 12045 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12046 : LoopsUsed(LoopsUsed) {} 12047 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12048 bool follow(const SCEV *S) { 12049 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12050 LoopsUsed.insert(AR->getLoop()); 12051 return true; 12052 } 12053 12054 bool isDone() const { return false; } 12055 }; 12056 12057 FindUsedLoops F(LoopsUsed); 12058 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12059 } 12060 12061 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12062 SmallPtrSet<const Loop *, 8> LoopsUsed; 12063 getUsedLoops(S, LoopsUsed); 12064 for (auto *L : LoopsUsed) 12065 LoopUsers[L].push_back(S); 12066 } 12067 12068 void ScalarEvolution::verify() const { 12069 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12070 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12071 12072 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12073 12074 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12075 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12076 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12077 12078 const SCEV *visitConstant(const SCEVConstant *Constant) { 12079 return SE.getConstant(Constant->getAPInt()); 12080 } 12081 12082 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12083 return SE.getUnknown(Expr->getValue()); 12084 } 12085 12086 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12087 return SE.getCouldNotCompute(); 12088 } 12089 }; 12090 12091 SCEVMapper SCM(SE2); 12092 12093 while (!LoopStack.empty()) { 12094 auto *L = LoopStack.pop_back_val(); 12095 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12096 12097 auto *CurBECount = SCM.visit( 12098 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12099 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12100 12101 if (CurBECount == SE2.getCouldNotCompute() || 12102 NewBECount == SE2.getCouldNotCompute()) { 12103 // NB! This situation is legal, but is very suspicious -- whatever pass 12104 // change the loop to make a trip count go from could not compute to 12105 // computable or vice-versa *should have* invalidated SCEV. However, we 12106 // choose not to assert here (for now) since we don't want false 12107 // positives. 12108 continue; 12109 } 12110 12111 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12112 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12113 // not propagate undef aggressively). This means we can (and do) fail 12114 // verification in cases where a transform makes the trip count of a loop 12115 // go from "undef" to "undef+1" (say). The transform is fine, since in 12116 // both cases the loop iterates "undef" times, but SCEV thinks we 12117 // increased the trip count of the loop by 1 incorrectly. 12118 continue; 12119 } 12120 12121 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12122 SE.getTypeSizeInBits(NewBECount->getType())) 12123 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12124 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12125 SE.getTypeSizeInBits(NewBECount->getType())) 12126 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12127 12128 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12129 12130 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12131 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12132 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12133 dbgs() << "Old: " << *CurBECount << "\n"; 12134 dbgs() << "New: " << *NewBECount << "\n"; 12135 dbgs() << "Delta: " << *Delta << "\n"; 12136 std::abort(); 12137 } 12138 } 12139 } 12140 12141 bool ScalarEvolution::invalidate( 12142 Function &F, const PreservedAnalyses &PA, 12143 FunctionAnalysisManager::Invalidator &Inv) { 12144 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12145 // of its dependencies is invalidated. 12146 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12147 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12148 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12149 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12150 Inv.invalidate<LoopAnalysis>(F, PA); 12151 } 12152 12153 AnalysisKey ScalarEvolutionAnalysis::Key; 12154 12155 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12156 FunctionAnalysisManager &AM) { 12157 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12158 AM.getResult<AssumptionAnalysis>(F), 12159 AM.getResult<DominatorTreeAnalysis>(F), 12160 AM.getResult<LoopAnalysis>(F)); 12161 } 12162 12163 PreservedAnalyses 12164 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12165 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12166 return PreservedAnalyses::all(); 12167 } 12168 12169 PreservedAnalyses 12170 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12171 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12172 return PreservedAnalyses::all(); 12173 } 12174 12175 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12176 "Scalar Evolution Analysis", false, true) 12177 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12178 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12179 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12180 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12181 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12182 "Scalar Evolution Analysis", false, true) 12183 12184 char ScalarEvolutionWrapperPass::ID = 0; 12185 12186 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12187 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12188 } 12189 12190 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12191 SE.reset(new ScalarEvolution( 12192 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12193 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12194 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12195 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12196 return false; 12197 } 12198 12199 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12200 12201 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12202 SE->print(OS); 12203 } 12204 12205 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12206 if (!VerifySCEV) 12207 return; 12208 12209 SE->verify(); 12210 } 12211 12212 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12213 AU.setPreservesAll(); 12214 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12215 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12216 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12217 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12218 } 12219 12220 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12221 const SCEV *RHS) { 12222 FoldingSetNodeID ID; 12223 assert(LHS->getType() == RHS->getType() && 12224 "Type mismatch between LHS and RHS"); 12225 // Unique this node based on the arguments 12226 ID.AddInteger(SCEVPredicate::P_Equal); 12227 ID.AddPointer(LHS); 12228 ID.AddPointer(RHS); 12229 void *IP = nullptr; 12230 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12231 return S; 12232 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12233 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12234 UniquePreds.InsertNode(Eq, IP); 12235 return Eq; 12236 } 12237 12238 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12239 const SCEVAddRecExpr *AR, 12240 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12241 FoldingSetNodeID ID; 12242 // Unique this node based on the arguments 12243 ID.AddInteger(SCEVPredicate::P_Wrap); 12244 ID.AddPointer(AR); 12245 ID.AddInteger(AddedFlags); 12246 void *IP = nullptr; 12247 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12248 return S; 12249 auto *OF = new (SCEVAllocator) 12250 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12251 UniquePreds.InsertNode(OF, IP); 12252 return OF; 12253 } 12254 12255 namespace { 12256 12257 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12258 public: 12259 12260 /// Rewrites \p S in the context of a loop L and the SCEV predication 12261 /// infrastructure. 12262 /// 12263 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12264 /// equivalences present in \p Pred. 12265 /// 12266 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12267 /// \p NewPreds such that the result will be an AddRecExpr. 12268 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12269 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12270 SCEVUnionPredicate *Pred) { 12271 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12272 return Rewriter.visit(S); 12273 } 12274 12275 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12276 if (Pred) { 12277 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12278 for (auto *Pred : ExprPreds) 12279 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12280 if (IPred->getLHS() == Expr) 12281 return IPred->getRHS(); 12282 } 12283 return convertToAddRecWithPreds(Expr); 12284 } 12285 12286 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12287 const SCEV *Operand = visit(Expr->getOperand()); 12288 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12289 if (AR && AR->getLoop() == L && AR->isAffine()) { 12290 // This couldn't be folded because the operand didn't have the nuw 12291 // flag. Add the nusw flag as an assumption that we could make. 12292 const SCEV *Step = AR->getStepRecurrence(SE); 12293 Type *Ty = Expr->getType(); 12294 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12295 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12296 SE.getSignExtendExpr(Step, Ty), L, 12297 AR->getNoWrapFlags()); 12298 } 12299 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12300 } 12301 12302 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12303 const SCEV *Operand = visit(Expr->getOperand()); 12304 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12305 if (AR && AR->getLoop() == L && AR->isAffine()) { 12306 // This couldn't be folded because the operand didn't have the nsw 12307 // flag. Add the nssw flag as an assumption that we could make. 12308 const SCEV *Step = AR->getStepRecurrence(SE); 12309 Type *Ty = Expr->getType(); 12310 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12311 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12312 SE.getSignExtendExpr(Step, Ty), L, 12313 AR->getNoWrapFlags()); 12314 } 12315 return SE.getSignExtendExpr(Operand, Expr->getType()); 12316 } 12317 12318 private: 12319 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12320 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12321 SCEVUnionPredicate *Pred) 12322 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12323 12324 bool addOverflowAssumption(const SCEVPredicate *P) { 12325 if (!NewPreds) { 12326 // Check if we've already made this assumption. 12327 return Pred && Pred->implies(P); 12328 } 12329 NewPreds->insert(P); 12330 return true; 12331 } 12332 12333 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12334 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12335 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12336 return addOverflowAssumption(A); 12337 } 12338 12339 // If \p Expr represents a PHINode, we try to see if it can be represented 12340 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12341 // to add this predicate as a runtime overflow check, we return the AddRec. 12342 // If \p Expr does not meet these conditions (is not a PHI node, or we 12343 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12344 // return \p Expr. 12345 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12346 if (!isa<PHINode>(Expr->getValue())) 12347 return Expr; 12348 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12349 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12350 if (!PredicatedRewrite) 12351 return Expr; 12352 for (auto *P : PredicatedRewrite->second){ 12353 // Wrap predicates from outer loops are not supported. 12354 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12355 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12356 if (L != AR->getLoop()) 12357 return Expr; 12358 } 12359 if (!addOverflowAssumption(P)) 12360 return Expr; 12361 } 12362 return PredicatedRewrite->first; 12363 } 12364 12365 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12366 SCEVUnionPredicate *Pred; 12367 const Loop *L; 12368 }; 12369 12370 } // end anonymous namespace 12371 12372 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12373 SCEVUnionPredicate &Preds) { 12374 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12375 } 12376 12377 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12378 const SCEV *S, const Loop *L, 12379 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12380 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12381 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12382 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12383 12384 if (!AddRec) 12385 return nullptr; 12386 12387 // Since the transformation was successful, we can now transfer the SCEV 12388 // predicates. 12389 for (auto *P : TransformPreds) 12390 Preds.insert(P); 12391 12392 return AddRec; 12393 } 12394 12395 /// SCEV predicates 12396 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12397 SCEVPredicateKind Kind) 12398 : FastID(ID), Kind(Kind) {} 12399 12400 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12401 const SCEV *LHS, const SCEV *RHS) 12402 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12403 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12404 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12405 } 12406 12407 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12408 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12409 12410 if (!Op) 12411 return false; 12412 12413 return Op->LHS == LHS && Op->RHS == RHS; 12414 } 12415 12416 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12417 12418 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12419 12420 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12421 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12422 } 12423 12424 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12425 const SCEVAddRecExpr *AR, 12426 IncrementWrapFlags Flags) 12427 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12428 12429 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12430 12431 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12432 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12433 12434 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12435 } 12436 12437 bool SCEVWrapPredicate::isAlwaysTrue() const { 12438 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12439 IncrementWrapFlags IFlags = Flags; 12440 12441 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12442 IFlags = clearFlags(IFlags, IncrementNSSW); 12443 12444 return IFlags == IncrementAnyWrap; 12445 } 12446 12447 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12448 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12449 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12450 OS << "<nusw>"; 12451 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12452 OS << "<nssw>"; 12453 OS << "\n"; 12454 } 12455 12456 SCEVWrapPredicate::IncrementWrapFlags 12457 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12458 ScalarEvolution &SE) { 12459 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12460 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12461 12462 // We can safely transfer the NSW flag as NSSW. 12463 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12464 ImpliedFlags = IncrementNSSW; 12465 12466 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12467 // If the increment is positive, the SCEV NUW flag will also imply the 12468 // WrapPredicate NUSW flag. 12469 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12470 if (Step->getValue()->getValue().isNonNegative()) 12471 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12472 } 12473 12474 return ImpliedFlags; 12475 } 12476 12477 /// Union predicates don't get cached so create a dummy set ID for it. 12478 SCEVUnionPredicate::SCEVUnionPredicate() 12479 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12480 12481 bool SCEVUnionPredicate::isAlwaysTrue() const { 12482 return all_of(Preds, 12483 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12484 } 12485 12486 ArrayRef<const SCEVPredicate *> 12487 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12488 auto I = SCEVToPreds.find(Expr); 12489 if (I == SCEVToPreds.end()) 12490 return ArrayRef<const SCEVPredicate *>(); 12491 return I->second; 12492 } 12493 12494 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12495 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12496 return all_of(Set->Preds, 12497 [this](const SCEVPredicate *I) { return this->implies(I); }); 12498 12499 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12500 if (ScevPredsIt == SCEVToPreds.end()) 12501 return false; 12502 auto &SCEVPreds = ScevPredsIt->second; 12503 12504 return any_of(SCEVPreds, 12505 [N](const SCEVPredicate *I) { return I->implies(N); }); 12506 } 12507 12508 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12509 12510 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12511 for (auto Pred : Preds) 12512 Pred->print(OS, Depth); 12513 } 12514 12515 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12516 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12517 for (auto Pred : Set->Preds) 12518 add(Pred); 12519 return; 12520 } 12521 12522 if (implies(N)) 12523 return; 12524 12525 const SCEV *Key = N->getExpr(); 12526 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12527 " associated expression!"); 12528 12529 SCEVToPreds[Key].push_back(N); 12530 Preds.push_back(N); 12531 } 12532 12533 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12534 Loop &L) 12535 : SE(SE), L(L) {} 12536 12537 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12538 const SCEV *Expr = SE.getSCEV(V); 12539 RewriteEntry &Entry = RewriteMap[Expr]; 12540 12541 // If we already have an entry and the version matches, return it. 12542 if (Entry.second && Generation == Entry.first) 12543 return Entry.second; 12544 12545 // We found an entry but it's stale. Rewrite the stale entry 12546 // according to the current predicate. 12547 if (Entry.second) 12548 Expr = Entry.second; 12549 12550 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12551 Entry = {Generation, NewSCEV}; 12552 12553 return NewSCEV; 12554 } 12555 12556 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12557 if (!BackedgeCount) { 12558 SCEVUnionPredicate BackedgePred; 12559 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12560 addPredicate(BackedgePred); 12561 } 12562 return BackedgeCount; 12563 } 12564 12565 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12566 if (Preds.implies(&Pred)) 12567 return; 12568 Preds.add(&Pred); 12569 updateGeneration(); 12570 } 12571 12572 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12573 return Preds; 12574 } 12575 12576 void PredicatedScalarEvolution::updateGeneration() { 12577 // If the generation number wrapped recompute everything. 12578 if (++Generation == 0) { 12579 for (auto &II : RewriteMap) { 12580 const SCEV *Rewritten = II.second.second; 12581 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12582 } 12583 } 12584 } 12585 12586 void PredicatedScalarEvolution::setNoOverflow( 12587 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12588 const SCEV *Expr = getSCEV(V); 12589 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12590 12591 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12592 12593 // Clear the statically implied flags. 12594 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12595 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12596 12597 auto II = FlagsMap.insert({V, Flags}); 12598 if (!II.second) 12599 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12600 } 12601 12602 bool PredicatedScalarEvolution::hasNoOverflow( 12603 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12604 const SCEV *Expr = getSCEV(V); 12605 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12606 12607 Flags = SCEVWrapPredicate::clearFlags( 12608 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12609 12610 auto II = FlagsMap.find(V); 12611 12612 if (II != FlagsMap.end()) 12613 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12614 12615 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12616 } 12617 12618 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12619 const SCEV *Expr = this->getSCEV(V); 12620 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12621 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12622 12623 if (!New) 12624 return nullptr; 12625 12626 for (auto *P : NewPreds) 12627 Preds.add(P); 12628 12629 updateGeneration(); 12630 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12631 return New; 12632 } 12633 12634 PredicatedScalarEvolution::PredicatedScalarEvolution( 12635 const PredicatedScalarEvolution &Init) 12636 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 12637 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 12638 for (auto I : Init.FlagsMap) 12639 FlagsMap.insert(I); 12640 } 12641 12642 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 12643 // For each block. 12644 for (auto *BB : L.getBlocks()) 12645 for (auto &I : *BB) { 12646 if (!SE.isSCEVable(I.getType())) 12647 continue; 12648 12649 auto *Expr = SE.getSCEV(&I); 12650 auto II = RewriteMap.find(Expr); 12651 12652 if (II == RewriteMap.end()) 12653 continue; 12654 12655 // Don't print things that are not interesting. 12656 if (II->second.second == Expr) 12657 continue; 12658 12659 OS.indent(Depth) << "[PSE]" << I << ":\n"; 12660 OS.indent(Depth + 2) << *Expr << "\n"; 12661 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 12662 } 12663 } 12664 12665 // Match the mathematical pattern A - (A / B) * B, where A and B can be 12666 // arbitrary expressions. 12667 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 12668 // 4, A / B becomes X / 8). 12669 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 12670 const SCEV *&RHS) { 12671 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 12672 if (Add == nullptr || Add->getNumOperands() != 2) 12673 return false; 12674 12675 const SCEV *A = Add->getOperand(1); 12676 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 12677 12678 if (Mul == nullptr) 12679 return false; 12680 12681 const auto MatchURemWithDivisor = [&](const SCEV *B) { 12682 // (SomeExpr + (-(SomeExpr / B) * B)). 12683 if (Expr == getURemExpr(A, B)) { 12684 LHS = A; 12685 RHS = B; 12686 return true; 12687 } 12688 return false; 12689 }; 12690 12691 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 12692 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 12693 return MatchURemWithDivisor(Mul->getOperand(1)) || 12694 MatchURemWithDivisor(Mul->getOperand(2)); 12695 12696 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 12697 if (Mul->getNumOperands() == 2) 12698 return MatchURemWithDivisor(Mul->getOperand(1)) || 12699 MatchURemWithDivisor(Mul->getOperand(0)) || 12700 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 12701 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 12702 return false; 12703 } 12704