1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the implementation of the scalar evolution analysis 10 // engine, which is used primarily to analyze expressions involving induction 11 // variables in loops. 12 // 13 // There are several aspects to this library. First is the representation of 14 // scalar expressions, which are represented as subclasses of the SCEV class. 15 // These classes are used to represent certain types of subexpressions that we 16 // can handle. We only create one SCEV of a particular shape, so 17 // pointer-comparisons for equality are legal. 18 // 19 // One important aspect of the SCEV objects is that they are never cyclic, even 20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If 21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial 22 // recurrence) then we represent it directly as a recurrence node, otherwise we 23 // represent it as a SCEVUnknown node. 24 // 25 // In addition to being able to represent expressions of various types, we also 26 // have folders that are used to build the *canonical* representation for a 27 // particular expression. These folders are capable of using a variety of 28 // rewrite rules to simplify the expressions. 29 // 30 // Once the folders are defined, we can implement the more interesting 31 // higher-level code, such as the code that recognizes PHI nodes of various 32 // types, computes the execution count of a loop, etc. 33 // 34 // TODO: We should use these routines and value representations to implement 35 // dependence analysis! 36 // 37 //===----------------------------------------------------------------------===// 38 // 39 // There are several good references for the techniques used in this analysis. 40 // 41 // Chains of recurrences -- a method to expedite the evaluation 42 // of closed-form functions 43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima 44 // 45 // On computational properties of chains of recurrences 46 // Eugene V. Zima 47 // 48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization 49 // Robert A. van Engelen 50 // 51 // Efficient Symbolic Analysis for Optimizing Compilers 52 // Robert A. van Engelen 53 // 54 // Using the chains of recurrences algebra for data dependence testing and 55 // induction variable substitution 56 // MS Thesis, Johnie Birch 57 // 58 //===----------------------------------------------------------------------===// 59 60 #include "llvm/Analysis/ScalarEvolution.h" 61 #include "llvm/ADT/APInt.h" 62 #include "llvm/ADT/ArrayRef.h" 63 #include "llvm/ADT/DenseMap.h" 64 #include "llvm/ADT/DepthFirstIterator.h" 65 #include "llvm/ADT/EquivalenceClasses.h" 66 #include "llvm/ADT/FoldingSet.h" 67 #include "llvm/ADT/None.h" 68 #include "llvm/ADT/Optional.h" 69 #include "llvm/ADT/STLExtras.h" 70 #include "llvm/ADT/ScopeExit.h" 71 #include "llvm/ADT/Sequence.h" 72 #include "llvm/ADT/SetVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallSet.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/Statistic.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/Analysis/AssumptionCache.h" 79 #include "llvm/Analysis/ConstantFolding.h" 80 #include "llvm/Analysis/InstructionSimplify.h" 81 #include "llvm/Analysis/LoopInfo.h" 82 #include "llvm/Analysis/ScalarEvolutionDivision.h" 83 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 84 #include "llvm/Analysis/TargetLibraryInfo.h" 85 #include "llvm/Analysis/ValueTracking.h" 86 #include "llvm/Config/llvm-config.h" 87 #include "llvm/IR/Argument.h" 88 #include "llvm/IR/BasicBlock.h" 89 #include "llvm/IR/CFG.h" 90 #include "llvm/IR/Constant.h" 91 #include "llvm/IR/ConstantRange.h" 92 #include "llvm/IR/Constants.h" 93 #include "llvm/IR/DataLayout.h" 94 #include "llvm/IR/DerivedTypes.h" 95 #include "llvm/IR/Dominators.h" 96 #include "llvm/IR/Function.h" 97 #include "llvm/IR/GlobalAlias.h" 98 #include "llvm/IR/GlobalValue.h" 99 #include "llvm/IR/GlobalVariable.h" 100 #include "llvm/IR/InstIterator.h" 101 #include "llvm/IR/InstrTypes.h" 102 #include "llvm/IR/Instruction.h" 103 #include "llvm/IR/Instructions.h" 104 #include "llvm/IR/IntrinsicInst.h" 105 #include "llvm/IR/Intrinsics.h" 106 #include "llvm/IR/LLVMContext.h" 107 #include "llvm/IR/Metadata.h" 108 #include "llvm/IR/Operator.h" 109 #include "llvm/IR/PatternMatch.h" 110 #include "llvm/IR/Type.h" 111 #include "llvm/IR/Use.h" 112 #include "llvm/IR/User.h" 113 #include "llvm/IR/Value.h" 114 #include "llvm/IR/Verifier.h" 115 #include "llvm/InitializePasses.h" 116 #include "llvm/Pass.h" 117 #include "llvm/Support/Casting.h" 118 #include "llvm/Support/CommandLine.h" 119 #include "llvm/Support/Compiler.h" 120 #include "llvm/Support/Debug.h" 121 #include "llvm/Support/ErrorHandling.h" 122 #include "llvm/Support/KnownBits.h" 123 #include "llvm/Support/SaveAndRestore.h" 124 #include "llvm/Support/raw_ostream.h" 125 #include <algorithm> 126 #include <cassert> 127 #include <climits> 128 #include <cstddef> 129 #include <cstdint> 130 #include <cstdlib> 131 #include <map> 132 #include <memory> 133 #include <tuple> 134 #include <utility> 135 #include <vector> 136 137 using namespace llvm; 138 139 #define DEBUG_TYPE "scalar-evolution" 140 141 STATISTIC(NumArrayLenItCounts, 142 "Number of trip counts computed with array length"); 143 STATISTIC(NumTripCountsComputed, 144 "Number of loops with predictable loop counts"); 145 STATISTIC(NumTripCountsNotComputed, 146 "Number of loops without predictable loop counts"); 147 STATISTIC(NumBruteForceTripCountsComputed, 148 "Number of loops with trip counts computed by force"); 149 150 static cl::opt<unsigned> 151 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden, 152 cl::ZeroOrMore, 153 cl::desc("Maximum number of iterations SCEV will " 154 "symbolically execute a constant " 155 "derived loop"), 156 cl::init(100)); 157 158 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean. 159 static cl::opt<bool> VerifySCEV( 160 "verify-scev", cl::Hidden, 161 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)")); 162 static cl::opt<bool> VerifySCEVStrict( 163 "verify-scev-strict", cl::Hidden, 164 cl::desc("Enable stricter verification with -verify-scev is passed")); 165 static cl::opt<bool> 166 VerifySCEVMap("verify-scev-maps", cl::Hidden, 167 cl::desc("Verify no dangling value in ScalarEvolution's " 168 "ExprValueMap (slow)")); 169 170 static cl::opt<bool> VerifyIR( 171 "scev-verify-ir", cl::Hidden, 172 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"), 173 cl::init(false)); 174 175 static cl::opt<unsigned> MulOpsInlineThreshold( 176 "scev-mulops-inline-threshold", cl::Hidden, 177 cl::desc("Threshold for inlining multiplication operands into a SCEV"), 178 cl::init(32)); 179 180 static cl::opt<unsigned> AddOpsInlineThreshold( 181 "scev-addops-inline-threshold", cl::Hidden, 182 cl::desc("Threshold for inlining addition operands into a SCEV"), 183 cl::init(500)); 184 185 static cl::opt<unsigned> MaxSCEVCompareDepth( 186 "scalar-evolution-max-scev-compare-depth", cl::Hidden, 187 cl::desc("Maximum depth of recursive SCEV complexity comparisons"), 188 cl::init(32)); 189 190 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth( 191 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden, 192 cl::desc("Maximum depth of recursive SCEV operations implication analysis"), 193 cl::init(2)); 194 195 static cl::opt<unsigned> MaxValueCompareDepth( 196 "scalar-evolution-max-value-compare-depth", cl::Hidden, 197 cl::desc("Maximum depth of recursive value complexity comparisons"), 198 cl::init(2)); 199 200 static cl::opt<unsigned> 201 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden, 202 cl::desc("Maximum depth of recursive arithmetics"), 203 cl::init(32)); 204 205 static cl::opt<unsigned> MaxConstantEvolvingDepth( 206 "scalar-evolution-max-constant-evolving-depth", cl::Hidden, 207 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32)); 208 209 static cl::opt<unsigned> 210 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden, 211 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"), 212 cl::init(8)); 213 214 static cl::opt<unsigned> 215 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden, 216 cl::desc("Max coefficients in AddRec during evolving"), 217 cl::init(8)); 218 219 static cl::opt<unsigned> 220 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden, 221 cl::desc("Size of the expression which is considered huge"), 222 cl::init(4096)); 223 224 static cl::opt<bool> 225 ClassifyExpressions("scalar-evolution-classify-expressions", 226 cl::Hidden, cl::init(true), 227 cl::desc("When printing analysis, include information on every instruction")); 228 229 static cl::opt<bool> UseExpensiveRangeSharpening( 230 "scalar-evolution-use-expensive-range-sharpening", cl::Hidden, 231 cl::init(false), 232 cl::desc("Use more powerful methods of sharpening expression ranges. May " 233 "be costly in terms of compile time")); 234 235 //===----------------------------------------------------------------------===// 236 // SCEV class definitions 237 //===----------------------------------------------------------------------===// 238 239 //===----------------------------------------------------------------------===// 240 // Implementation of the SCEV class. 241 // 242 243 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 244 LLVM_DUMP_METHOD void SCEV::dump() const { 245 print(dbgs()); 246 dbgs() << '\n'; 247 } 248 #endif 249 250 void SCEV::print(raw_ostream &OS) const { 251 switch (getSCEVType()) { 252 case scConstant: 253 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false); 254 return; 255 case scPtrToInt: { 256 const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this); 257 const SCEV *Op = PtrToInt->getOperand(); 258 OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to " 259 << *PtrToInt->getType() << ")"; 260 return; 261 } 262 case scTruncate: { 263 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this); 264 const SCEV *Op = Trunc->getOperand(); 265 OS << "(trunc " << *Op->getType() << " " << *Op << " to " 266 << *Trunc->getType() << ")"; 267 return; 268 } 269 case scZeroExtend: { 270 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this); 271 const SCEV *Op = ZExt->getOperand(); 272 OS << "(zext " << *Op->getType() << " " << *Op << " to " 273 << *ZExt->getType() << ")"; 274 return; 275 } 276 case scSignExtend: { 277 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this); 278 const SCEV *Op = SExt->getOperand(); 279 OS << "(sext " << *Op->getType() << " " << *Op << " to " 280 << *SExt->getType() << ")"; 281 return; 282 } 283 case scAddRecExpr: { 284 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this); 285 OS << "{" << *AR->getOperand(0); 286 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i) 287 OS << ",+," << *AR->getOperand(i); 288 OS << "}<"; 289 if (AR->hasNoUnsignedWrap()) 290 OS << "nuw><"; 291 if (AR->hasNoSignedWrap()) 292 OS << "nsw><"; 293 if (AR->hasNoSelfWrap() && 294 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW))) 295 OS << "nw><"; 296 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false); 297 OS << ">"; 298 return; 299 } 300 case scAddExpr: 301 case scMulExpr: 302 case scUMaxExpr: 303 case scSMaxExpr: 304 case scUMinExpr: 305 case scSMinExpr: { 306 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this); 307 const char *OpStr = nullptr; 308 switch (NAry->getSCEVType()) { 309 case scAddExpr: OpStr = " + "; break; 310 case scMulExpr: OpStr = " * "; break; 311 case scUMaxExpr: OpStr = " umax "; break; 312 case scSMaxExpr: OpStr = " smax "; break; 313 case scUMinExpr: 314 OpStr = " umin "; 315 break; 316 case scSMinExpr: 317 OpStr = " smin "; 318 break; 319 default: 320 llvm_unreachable("There are no other nary expression types."); 321 } 322 OS << "("; 323 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end(); 324 I != E; ++I) { 325 OS << **I; 326 if (std::next(I) != E) 327 OS << OpStr; 328 } 329 OS << ")"; 330 switch (NAry->getSCEVType()) { 331 case scAddExpr: 332 case scMulExpr: 333 if (NAry->hasNoUnsignedWrap()) 334 OS << "<nuw>"; 335 if (NAry->hasNoSignedWrap()) 336 OS << "<nsw>"; 337 break; 338 default: 339 // Nothing to print for other nary expressions. 340 break; 341 } 342 return; 343 } 344 case scUDivExpr: { 345 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this); 346 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")"; 347 return; 348 } 349 case scUnknown: { 350 const SCEVUnknown *U = cast<SCEVUnknown>(this); 351 Type *AllocTy; 352 if (U->isSizeOf(AllocTy)) { 353 OS << "sizeof(" << *AllocTy << ")"; 354 return; 355 } 356 if (U->isAlignOf(AllocTy)) { 357 OS << "alignof(" << *AllocTy << ")"; 358 return; 359 } 360 361 Type *CTy; 362 Constant *FieldNo; 363 if (U->isOffsetOf(CTy, FieldNo)) { 364 OS << "offsetof(" << *CTy << ", "; 365 FieldNo->printAsOperand(OS, false); 366 OS << ")"; 367 return; 368 } 369 370 // Otherwise just print it normally. 371 U->getValue()->printAsOperand(OS, false); 372 return; 373 } 374 case scCouldNotCompute: 375 OS << "***COULDNOTCOMPUTE***"; 376 return; 377 } 378 llvm_unreachable("Unknown SCEV kind!"); 379 } 380 381 Type *SCEV::getType() const { 382 switch (getSCEVType()) { 383 case scConstant: 384 return cast<SCEVConstant>(this)->getType(); 385 case scPtrToInt: 386 case scTruncate: 387 case scZeroExtend: 388 case scSignExtend: 389 return cast<SCEVCastExpr>(this)->getType(); 390 case scAddRecExpr: 391 case scMulExpr: 392 case scUMaxExpr: 393 case scSMaxExpr: 394 case scUMinExpr: 395 case scSMinExpr: 396 return cast<SCEVNAryExpr>(this)->getType(); 397 case scAddExpr: 398 return cast<SCEVAddExpr>(this)->getType(); 399 case scUDivExpr: 400 return cast<SCEVUDivExpr>(this)->getType(); 401 case scUnknown: 402 return cast<SCEVUnknown>(this)->getType(); 403 case scCouldNotCompute: 404 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 405 } 406 llvm_unreachable("Unknown SCEV kind!"); 407 } 408 409 bool SCEV::isZero() const { 410 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 411 return SC->getValue()->isZero(); 412 return false; 413 } 414 415 bool SCEV::isOne() const { 416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 417 return SC->getValue()->isOne(); 418 return false; 419 } 420 421 bool SCEV::isAllOnesValue() const { 422 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this)) 423 return SC->getValue()->isMinusOne(); 424 return false; 425 } 426 427 bool SCEV::isNonConstantNegative() const { 428 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this); 429 if (!Mul) return false; 430 431 // If there is a constant factor, it will be first. 432 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); 433 if (!SC) return false; 434 435 // Return true if the value is negative, this matches things like (-42 * V). 436 return SC->getAPInt().isNegative(); 437 } 438 439 SCEVCouldNotCompute::SCEVCouldNotCompute() : 440 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {} 441 442 bool SCEVCouldNotCompute::classof(const SCEV *S) { 443 return S->getSCEVType() == scCouldNotCompute; 444 } 445 446 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) { 447 FoldingSetNodeID ID; 448 ID.AddInteger(scConstant); 449 ID.AddPointer(V); 450 void *IP = nullptr; 451 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 452 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V); 453 UniqueSCEVs.InsertNode(S, IP); 454 return S; 455 } 456 457 const SCEV *ScalarEvolution::getConstant(const APInt &Val) { 458 return getConstant(ConstantInt::get(getContext(), Val)); 459 } 460 461 const SCEV * 462 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) { 463 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty)); 464 return getConstant(ConstantInt::get(ITy, V, isSigned)); 465 } 466 467 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, 468 const SCEV *op, Type *ty) 469 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Ty(ty) { 470 Operands[0] = op; 471 } 472 473 SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op, 474 Type *ITy) 475 : SCEVCastExpr(ID, scPtrToInt, Op, ITy) { 476 assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() && 477 "Must be a non-bit-width-changing pointer-to-integer cast!"); 478 } 479 480 SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID, 481 SCEVTypes SCEVTy, const SCEV *op, 482 Type *ty) 483 : SCEVCastExpr(ID, SCEVTy, op, ty) {} 484 485 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op, 486 Type *ty) 487 : SCEVIntegralCastExpr(ID, scTruncate, op, ty) { 488 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 489 "Cannot truncate non-integer value!"); 490 } 491 492 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID, 493 const SCEV *op, Type *ty) 494 : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) { 495 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 496 "Cannot zero extend non-integer value!"); 497 } 498 499 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID, 500 const SCEV *op, Type *ty) 501 : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) { 502 assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 503 "Cannot sign extend non-integer value!"); 504 } 505 506 void SCEVUnknown::deleted() { 507 // Clear this SCEVUnknown from various maps. 508 SE->forgetMemoizedResults(this); 509 510 // Remove this SCEVUnknown from the uniquing map. 511 SE->UniqueSCEVs.RemoveNode(this); 512 513 // Release the value. 514 setValPtr(nullptr); 515 } 516 517 void SCEVUnknown::allUsesReplacedWith(Value *New) { 518 // Remove this SCEVUnknown from the uniquing map. 519 SE->UniqueSCEVs.RemoveNode(this); 520 521 // Update this SCEVUnknown to point to the new value. This is needed 522 // because there may still be outstanding SCEVs which still point to 523 // this SCEVUnknown. 524 setValPtr(New); 525 } 526 527 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const { 528 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 529 if (VCE->getOpcode() == Instruction::PtrToInt) 530 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 531 if (CE->getOpcode() == Instruction::GetElementPtr && 532 CE->getOperand(0)->isNullValue() && 533 CE->getNumOperands() == 2) 534 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1))) 535 if (CI->isOne()) { 536 AllocTy = cast<PointerType>(CE->getOperand(0)->getType()) 537 ->getElementType(); 538 return true; 539 } 540 541 return false; 542 } 543 544 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const { 545 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 546 if (VCE->getOpcode() == Instruction::PtrToInt) 547 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 548 if (CE->getOpcode() == Instruction::GetElementPtr && 549 CE->getOperand(0)->isNullValue()) { 550 Type *Ty = 551 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 552 if (StructType *STy = dyn_cast<StructType>(Ty)) 553 if (!STy->isPacked() && 554 CE->getNumOperands() == 3 && 555 CE->getOperand(1)->isNullValue()) { 556 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2))) 557 if (CI->isOne() && 558 STy->getNumElements() == 2 && 559 STy->getElementType(0)->isIntegerTy(1)) { 560 AllocTy = STy->getElementType(1); 561 return true; 562 } 563 } 564 } 565 566 return false; 567 } 568 569 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const { 570 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue())) 571 if (VCE->getOpcode() == Instruction::PtrToInt) 572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0))) 573 if (CE->getOpcode() == Instruction::GetElementPtr && 574 CE->getNumOperands() == 3 && 575 CE->getOperand(0)->isNullValue() && 576 CE->getOperand(1)->isNullValue()) { 577 Type *Ty = 578 cast<PointerType>(CE->getOperand(0)->getType())->getElementType(); 579 // Ignore vector types here so that ScalarEvolutionExpander doesn't 580 // emit getelementptrs that index into vectors. 581 if (Ty->isStructTy() || Ty->isArrayTy()) { 582 CTy = Ty; 583 FieldNo = CE->getOperand(2); 584 return true; 585 } 586 } 587 588 return false; 589 } 590 591 //===----------------------------------------------------------------------===// 592 // SCEV Utilities 593 //===----------------------------------------------------------------------===// 594 595 /// Compare the two values \p LV and \p RV in terms of their "complexity" where 596 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order 597 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that 598 /// have been previously deemed to be "equally complex" by this routine. It is 599 /// intended to avoid exponential time complexity in cases like: 600 /// 601 /// %a = f(%x, %y) 602 /// %b = f(%a, %a) 603 /// %c = f(%b, %b) 604 /// 605 /// %d = f(%x, %y) 606 /// %e = f(%d, %d) 607 /// %f = f(%e, %e) 608 /// 609 /// CompareValueComplexity(%f, %c) 610 /// 611 /// Since we do not continue running this routine on expression trees once we 612 /// have seen unequal values, there is no need to track them in the cache. 613 static int 614 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue, 615 const LoopInfo *const LI, Value *LV, Value *RV, 616 unsigned Depth) { 617 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV)) 618 return 0; 619 620 // Order pointer values after integer values. This helps SCEVExpander form 621 // GEPs. 622 bool LIsPointer = LV->getType()->isPointerTy(), 623 RIsPointer = RV->getType()->isPointerTy(); 624 if (LIsPointer != RIsPointer) 625 return (int)LIsPointer - (int)RIsPointer; 626 627 // Compare getValueID values. 628 unsigned LID = LV->getValueID(), RID = RV->getValueID(); 629 if (LID != RID) 630 return (int)LID - (int)RID; 631 632 // Sort arguments by their position. 633 if (const auto *LA = dyn_cast<Argument>(LV)) { 634 const auto *RA = cast<Argument>(RV); 635 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo(); 636 return (int)LArgNo - (int)RArgNo; 637 } 638 639 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) { 640 const auto *RGV = cast<GlobalValue>(RV); 641 642 const auto IsGVNameSemantic = [&](const GlobalValue *GV) { 643 auto LT = GV->getLinkage(); 644 return !(GlobalValue::isPrivateLinkage(LT) || 645 GlobalValue::isInternalLinkage(LT)); 646 }; 647 648 // Use the names to distinguish the two values, but only if the 649 // names are semantically important. 650 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV)) 651 return LGV->getName().compare(RGV->getName()); 652 } 653 654 // For instructions, compare their loop depth, and their operand count. This 655 // is pretty loose. 656 if (const auto *LInst = dyn_cast<Instruction>(LV)) { 657 const auto *RInst = cast<Instruction>(RV); 658 659 // Compare loop depths. 660 const BasicBlock *LParent = LInst->getParent(), 661 *RParent = RInst->getParent(); 662 if (LParent != RParent) { 663 unsigned LDepth = LI->getLoopDepth(LParent), 664 RDepth = LI->getLoopDepth(RParent); 665 if (LDepth != RDepth) 666 return (int)LDepth - (int)RDepth; 667 } 668 669 // Compare the number of operands. 670 unsigned LNumOps = LInst->getNumOperands(), 671 RNumOps = RInst->getNumOperands(); 672 if (LNumOps != RNumOps) 673 return (int)LNumOps - (int)RNumOps; 674 675 for (unsigned Idx : seq(0u, LNumOps)) { 676 int Result = 677 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx), 678 RInst->getOperand(Idx), Depth + 1); 679 if (Result != 0) 680 return Result; 681 } 682 } 683 684 EqCacheValue.unionSets(LV, RV); 685 return 0; 686 } 687 688 // Return negative, zero, or positive, if LHS is less than, equal to, or greater 689 // than RHS, respectively. A three-way result allows recursive comparisons to be 690 // more efficient. 691 static int CompareSCEVComplexity( 692 EquivalenceClasses<const SCEV *> &EqCacheSCEV, 693 EquivalenceClasses<const Value *> &EqCacheValue, 694 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS, 695 DominatorTree &DT, unsigned Depth = 0) { 696 // Fast-path: SCEVs are uniqued so we can do a quick equality check. 697 if (LHS == RHS) 698 return 0; 699 700 // Primarily, sort the SCEVs by their getSCEVType(). 701 SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType(); 702 if (LType != RType) 703 return (int)LType - (int)RType; 704 705 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS)) 706 return 0; 707 // Aside from the getSCEVType() ordering, the particular ordering 708 // isn't very important except that it's beneficial to be consistent, 709 // so that (a + b) and (b + a) don't end up as different expressions. 710 switch (LType) { 711 case scUnknown: { 712 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS); 713 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS); 714 715 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(), 716 RU->getValue(), Depth + 1); 717 if (X == 0) 718 EqCacheSCEV.unionSets(LHS, RHS); 719 return X; 720 } 721 722 case scConstant: { 723 const SCEVConstant *LC = cast<SCEVConstant>(LHS); 724 const SCEVConstant *RC = cast<SCEVConstant>(RHS); 725 726 // Compare constant values. 727 const APInt &LA = LC->getAPInt(); 728 const APInt &RA = RC->getAPInt(); 729 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth(); 730 if (LBitWidth != RBitWidth) 731 return (int)LBitWidth - (int)RBitWidth; 732 return LA.ult(RA) ? -1 : 1; 733 } 734 735 case scAddRecExpr: { 736 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS); 737 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS); 738 739 // There is always a dominance between two recs that are used by one SCEV, 740 // so we can safely sort recs by loop header dominance. We require such 741 // order in getAddExpr. 742 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop(); 743 if (LLoop != RLoop) { 744 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader(); 745 assert(LHead != RHead && "Two loops share the same header?"); 746 if (DT.dominates(LHead, RHead)) 747 return 1; 748 else 749 assert(DT.dominates(RHead, LHead) && 750 "No dominance between recurrences used by one SCEV?"); 751 return -1; 752 } 753 754 // Addrec complexity grows with operand count. 755 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands(); 756 if (LNumOps != RNumOps) 757 return (int)LNumOps - (int)RNumOps; 758 759 // Lexicographically compare. 760 for (unsigned i = 0; i != LNumOps; ++i) { 761 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 762 LA->getOperand(i), RA->getOperand(i), DT, 763 Depth + 1); 764 if (X != 0) 765 return X; 766 } 767 EqCacheSCEV.unionSets(LHS, RHS); 768 return 0; 769 } 770 771 case scAddExpr: 772 case scMulExpr: 773 case scSMaxExpr: 774 case scUMaxExpr: 775 case scSMinExpr: 776 case scUMinExpr: { 777 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS); 778 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS); 779 780 // Lexicographically compare n-ary expressions. 781 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands(); 782 if (LNumOps != RNumOps) 783 return (int)LNumOps - (int)RNumOps; 784 785 for (unsigned i = 0; i != LNumOps; ++i) { 786 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 787 LC->getOperand(i), RC->getOperand(i), DT, 788 Depth + 1); 789 if (X != 0) 790 return X; 791 } 792 EqCacheSCEV.unionSets(LHS, RHS); 793 return 0; 794 } 795 796 case scUDivExpr: { 797 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS); 798 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS); 799 800 // Lexicographically compare udiv expressions. 801 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(), 802 RC->getLHS(), DT, Depth + 1); 803 if (X != 0) 804 return X; 805 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(), 806 RC->getRHS(), DT, Depth + 1); 807 if (X == 0) 808 EqCacheSCEV.unionSets(LHS, RHS); 809 return X; 810 } 811 812 case scPtrToInt: 813 case scTruncate: 814 case scZeroExtend: 815 case scSignExtend: { 816 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS); 817 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS); 818 819 // Compare cast expressions by operand. 820 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, 821 LC->getOperand(), RC->getOperand(), DT, 822 Depth + 1); 823 if (X == 0) 824 EqCacheSCEV.unionSets(LHS, RHS); 825 return X; 826 } 827 828 case scCouldNotCompute: 829 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 830 } 831 llvm_unreachable("Unknown SCEV kind!"); 832 } 833 834 /// Given a list of SCEV objects, order them by their complexity, and group 835 /// objects of the same complexity together by value. When this routine is 836 /// finished, we know that any duplicates in the vector are consecutive and that 837 /// complexity is monotonically increasing. 838 /// 839 /// Note that we go take special precautions to ensure that we get deterministic 840 /// results from this routine. In other words, we don't want the results of 841 /// this to depend on where the addresses of various SCEV objects happened to 842 /// land in memory. 843 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops, 844 LoopInfo *LI, DominatorTree &DT) { 845 if (Ops.size() < 2) return; // Noop 846 847 EquivalenceClasses<const SCEV *> EqCacheSCEV; 848 EquivalenceClasses<const Value *> EqCacheValue; 849 if (Ops.size() == 2) { 850 // This is the common case, which also happens to be trivially simple. 851 // Special case it. 852 const SCEV *&LHS = Ops[0], *&RHS = Ops[1]; 853 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0) 854 std::swap(LHS, RHS); 855 return; 856 } 857 858 // Do the rough sort by complexity. 859 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) { 860 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) < 861 0; 862 }); 863 864 // Now that we are sorted by complexity, group elements of the same 865 // complexity. Note that this is, at worst, N^2, but the vector is likely to 866 // be extremely short in practice. Note that we take this approach because we 867 // do not want to depend on the addresses of the objects we are grouping. 868 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) { 869 const SCEV *S = Ops[i]; 870 unsigned Complexity = S->getSCEVType(); 871 872 // If there are any objects of the same complexity and same value as this 873 // one, group them. 874 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) { 875 if (Ops[j] == S) { // Found a duplicate. 876 // Move it to immediately after i'th element. 877 std::swap(Ops[i+1], Ops[j]); 878 ++i; // no need to rescan it. 879 if (i == e-2) return; // Done! 880 } 881 } 882 } 883 } 884 885 /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at 886 /// least HugeExprThreshold nodes). 887 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) { 888 return any_of(Ops, [](const SCEV *S) { 889 return S->getExpressionSize() >= HugeExprThreshold; 890 }); 891 } 892 893 //===----------------------------------------------------------------------===// 894 // Simple SCEV method implementations 895 //===----------------------------------------------------------------------===// 896 897 /// Compute BC(It, K). The result has width W. Assume, K > 0. 898 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K, 899 ScalarEvolution &SE, 900 Type *ResultTy) { 901 // Handle the simplest case efficiently. 902 if (K == 1) 903 return SE.getTruncateOrZeroExtend(It, ResultTy); 904 905 // We are using the following formula for BC(It, K): 906 // 907 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K! 908 // 909 // Suppose, W is the bitwidth of the return value. We must be prepared for 910 // overflow. Hence, we must assure that the result of our computation is 911 // equal to the accurate one modulo 2^W. Unfortunately, division isn't 912 // safe in modular arithmetic. 913 // 914 // However, this code doesn't use exactly that formula; the formula it uses 915 // is something like the following, where T is the number of factors of 2 in 916 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is 917 // exponentiation: 918 // 919 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T) 920 // 921 // This formula is trivially equivalent to the previous formula. However, 922 // this formula can be implemented much more efficiently. The trick is that 923 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular 924 // arithmetic. To do exact division in modular arithmetic, all we have 925 // to do is multiply by the inverse. Therefore, this step can be done at 926 // width W. 927 // 928 // The next issue is how to safely do the division by 2^T. The way this 929 // is done is by doing the multiplication step at a width of at least W + T 930 // bits. This way, the bottom W+T bits of the product are accurate. Then, 931 // when we perform the division by 2^T (which is equivalent to a right shift 932 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get 933 // truncated out after the division by 2^T. 934 // 935 // In comparison to just directly using the first formula, this technique 936 // is much more efficient; using the first formula requires W * K bits, 937 // but this formula less than W + K bits. Also, the first formula requires 938 // a division step, whereas this formula only requires multiplies and shifts. 939 // 940 // It doesn't matter whether the subtraction step is done in the calculation 941 // width or the input iteration count's width; if the subtraction overflows, 942 // the result must be zero anyway. We prefer here to do it in the width of 943 // the induction variable because it helps a lot for certain cases; CodeGen 944 // isn't smart enough to ignore the overflow, which leads to much less 945 // efficient code if the width of the subtraction is wider than the native 946 // register width. 947 // 948 // (It's possible to not widen at all by pulling out factors of 2 before 949 // the multiplication; for example, K=2 can be calculated as 950 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires 951 // extra arithmetic, so it's not an obvious win, and it gets 952 // much more complicated for K > 3.) 953 954 // Protection from insane SCEVs; this bound is conservative, 955 // but it probably doesn't matter. 956 if (K > 1000) 957 return SE.getCouldNotCompute(); 958 959 unsigned W = SE.getTypeSizeInBits(ResultTy); 960 961 // Calculate K! / 2^T and T; we divide out the factors of two before 962 // multiplying for calculating K! / 2^T to avoid overflow. 963 // Other overflow doesn't matter because we only care about the bottom 964 // W bits of the result. 965 APInt OddFactorial(W, 1); 966 unsigned T = 1; 967 for (unsigned i = 3; i <= K; ++i) { 968 APInt Mult(W, i); 969 unsigned TwoFactors = Mult.countTrailingZeros(); 970 T += TwoFactors; 971 Mult.lshrInPlace(TwoFactors); 972 OddFactorial *= Mult; 973 } 974 975 // We need at least W + T bits for the multiplication step 976 unsigned CalculationBits = W + T; 977 978 // Calculate 2^T, at width T+W. 979 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T); 980 981 // Calculate the multiplicative inverse of K! / 2^T; 982 // this multiplication factor will perform the exact division by 983 // K! / 2^T. 984 APInt Mod = APInt::getSignedMinValue(W+1); 985 APInt MultiplyFactor = OddFactorial.zext(W+1); 986 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod); 987 MultiplyFactor = MultiplyFactor.trunc(W); 988 989 // Calculate the product, at width T+W 990 IntegerType *CalculationTy = IntegerType::get(SE.getContext(), 991 CalculationBits); 992 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy); 993 for (unsigned i = 1; i != K; ++i) { 994 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i)); 995 Dividend = SE.getMulExpr(Dividend, 996 SE.getTruncateOrZeroExtend(S, CalculationTy)); 997 } 998 999 // Divide by 2^T 1000 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor)); 1001 1002 // Truncate the result, and divide by K! / 2^T. 1003 1004 return SE.getMulExpr(SE.getConstant(MultiplyFactor), 1005 SE.getTruncateOrZeroExtend(DivResult, ResultTy)); 1006 } 1007 1008 /// Return the value of this chain of recurrences at the specified iteration 1009 /// number. We can evaluate this recurrence by multiplying each element in the 1010 /// chain by the binomial coefficient corresponding to it. In other words, we 1011 /// can evaluate {A,+,B,+,C,+,D} as: 1012 /// 1013 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3) 1014 /// 1015 /// where BC(It, k) stands for binomial coefficient. 1016 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It, 1017 ScalarEvolution &SE) const { 1018 const SCEV *Result = getStart(); 1019 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1020 // The computation is correct in the face of overflow provided that the 1021 // multiplication is performed _after_ the evaluation of the binomial 1022 // coefficient. 1023 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType()); 1024 if (isa<SCEVCouldNotCompute>(Coeff)) 1025 return Coeff; 1026 1027 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff)); 1028 } 1029 return Result; 1030 } 1031 1032 //===----------------------------------------------------------------------===// 1033 // SCEV Expression folder implementations 1034 //===----------------------------------------------------------------------===// 1035 1036 const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty, 1037 unsigned Depth) { 1038 assert(Ty->isIntegerTy() && "Target type must be an integer type!"); 1039 assert(Depth <= 1 && "getPtrToIntExpr() should self-recurse at most once."); 1040 1041 // We could be called with an integer-typed operands during SCEV rewrites. 1042 // Since the operand is an integer already, just perform zext/trunc/self cast. 1043 if (!Op->getType()->isPointerTy()) 1044 return getTruncateOrZeroExtend(Op, Ty); 1045 1046 // What would be an ID for such a SCEV cast expression? 1047 FoldingSetNodeID ID; 1048 ID.AddInteger(scPtrToInt); 1049 ID.AddPointer(Op); 1050 1051 void *IP = nullptr; 1052 1053 // Is there already an expression for such a cast? 1054 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1055 return getTruncateOrZeroExtend(S, Ty); 1056 1057 // If not, is this expression something we can't reduce any further? 1058 if (isa<SCEVUnknown>(Op)) { 1059 // Create an explicit cast node. 1060 // We can reuse the existing insert position since if we get here, 1061 // we won't have made any changes which would invalidate it. 1062 Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType()); 1063 assert(getDataLayout().getTypeSizeInBits(getEffectiveSCEVType( 1064 Op->getType())) == getDataLayout().getTypeSizeInBits(IntPtrTy) && 1065 "We can only model ptrtoint if SCEV's effective (integer) type is " 1066 "sufficiently wide to represent all possible pointer values."); 1067 SCEV *S = new (SCEVAllocator) 1068 SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy); 1069 UniqueSCEVs.InsertNode(S, IP); 1070 addToLoopUseLists(S); 1071 return getTruncateOrZeroExtend(S, Ty); 1072 } 1073 1074 assert(Depth == 0 && 1075 "getPtrToIntExpr() should not self-recurse for non-SCEVUnknown's."); 1076 1077 // Otherwise, we've got some expression that is more complex than just a 1078 // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an 1079 // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown 1080 // only, and the expressions must otherwise be integer-typed. 1081 // So sink the cast down to the SCEVUnknown's. 1082 1083 /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression, 1084 /// which computes a pointer-typed value, and rewrites the whole expression 1085 /// tree so that *all* the computations are done on integers, and the only 1086 /// pointer-typed operands in the expression are SCEVUnknown. 1087 class SCEVPtrToIntSinkingRewriter 1088 : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> { 1089 using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>; 1090 1091 public: 1092 SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {} 1093 1094 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) { 1095 SCEVPtrToIntSinkingRewriter Rewriter(SE); 1096 return Rewriter.visit(Scev); 1097 } 1098 1099 const SCEV *visit(const SCEV *S) { 1100 Type *STy = S->getType(); 1101 // If the expression is not pointer-typed, just keep it as-is. 1102 if (!STy->isPointerTy()) 1103 return S; 1104 // Else, recursively sink the cast down into it. 1105 return Base::visit(S); 1106 } 1107 1108 const SCEV *visitAddExpr(const SCEVAddExpr *Expr) { 1109 SmallVector<const SCEV *, 2> Operands; 1110 bool Changed = false; 1111 for (auto *Op : Expr->operands()) { 1112 Operands.push_back(visit(Op)); 1113 Changed |= Op != Operands.back(); 1114 } 1115 return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags()); 1116 } 1117 1118 const SCEV *visitMulExpr(const SCEVMulExpr *Expr) { 1119 SmallVector<const SCEV *, 2> Operands; 1120 bool Changed = false; 1121 for (auto *Op : Expr->operands()) { 1122 Operands.push_back(visit(Op)); 1123 Changed |= Op != Operands.back(); 1124 } 1125 return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags()); 1126 } 1127 1128 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 1129 Type *ExprPtrTy = Expr->getType(); 1130 assert(ExprPtrTy->isPointerTy() && 1131 "Should only reach pointer-typed SCEVUnknown's."); 1132 Type *ExprIntPtrTy = SE.getDataLayout().getIntPtrType(ExprPtrTy); 1133 return SE.getPtrToIntExpr(Expr, ExprIntPtrTy, /*Depth=*/1); 1134 } 1135 }; 1136 1137 // And actually perform the cast sinking. 1138 const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this); 1139 assert(IntOp->getType()->isIntegerTy() && 1140 "We must have succeeded in sinking the cast, " 1141 "and ending up with an integer-typed expression!"); 1142 return getTruncateOrZeroExtend(IntOp, Ty); 1143 } 1144 1145 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty, 1146 unsigned Depth) { 1147 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) && 1148 "This is not a truncating conversion!"); 1149 assert(isSCEVable(Ty) && 1150 "This is not a conversion to a SCEVable type!"); 1151 Ty = getEffectiveSCEVType(Ty); 1152 1153 FoldingSetNodeID ID; 1154 ID.AddInteger(scTruncate); 1155 ID.AddPointer(Op); 1156 ID.AddPointer(Ty); 1157 void *IP = nullptr; 1158 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1159 1160 // Fold if the operand is constant. 1161 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1162 return getConstant( 1163 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty))); 1164 1165 // trunc(trunc(x)) --> trunc(x) 1166 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) 1167 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1); 1168 1169 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing 1170 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1171 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1); 1172 1173 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing 1174 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1175 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1); 1176 1177 if (Depth > MaxCastDepth) { 1178 SCEV *S = 1179 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty); 1180 UniqueSCEVs.InsertNode(S, IP); 1181 addToLoopUseLists(S); 1182 return S; 1183 } 1184 1185 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and 1186 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN), 1187 // if after transforming we have at most one truncate, not counting truncates 1188 // that replace other casts. 1189 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) { 1190 auto *CommOp = cast<SCEVCommutativeExpr>(Op); 1191 SmallVector<const SCEV *, 4> Operands; 1192 unsigned numTruncs = 0; 1193 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2; 1194 ++i) { 1195 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1); 1196 if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) && 1197 isa<SCEVTruncateExpr>(S)) 1198 numTruncs++; 1199 Operands.push_back(S); 1200 } 1201 if (numTruncs < 2) { 1202 if (isa<SCEVAddExpr>(Op)) 1203 return getAddExpr(Operands); 1204 else if (isa<SCEVMulExpr>(Op)) 1205 return getMulExpr(Operands); 1206 else 1207 llvm_unreachable("Unexpected SCEV type for Op."); 1208 } 1209 // Although we checked in the beginning that ID is not in the cache, it is 1210 // possible that during recursion and different modification ID was inserted 1211 // into the cache. So if we find it, just return it. 1212 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 1213 return S; 1214 } 1215 1216 // If the input value is a chrec scev, truncate the chrec's operands. 1217 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) { 1218 SmallVector<const SCEV *, 4> Operands; 1219 for (const SCEV *Op : AddRec->operands()) 1220 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1)); 1221 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap); 1222 } 1223 1224 // The cast wasn't folded; create an explicit cast node. We can reuse 1225 // the existing insert position since if we get here, we won't have 1226 // made any changes which would invalidate it. 1227 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), 1228 Op, Ty); 1229 UniqueSCEVs.InsertNode(S, IP); 1230 addToLoopUseLists(S); 1231 return S; 1232 } 1233 1234 // Get the limit of a recurrence such that incrementing by Step cannot cause 1235 // signed overflow as long as the value of the recurrence within the 1236 // loop does not exceed this limit before incrementing. 1237 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step, 1238 ICmpInst::Predicate *Pred, 1239 ScalarEvolution *SE) { 1240 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1241 if (SE->isKnownPositive(Step)) { 1242 *Pred = ICmpInst::ICMP_SLT; 1243 return SE->getConstant(APInt::getSignedMinValue(BitWidth) - 1244 SE->getSignedRangeMax(Step)); 1245 } 1246 if (SE->isKnownNegative(Step)) { 1247 *Pred = ICmpInst::ICMP_SGT; 1248 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) - 1249 SE->getSignedRangeMin(Step)); 1250 } 1251 return nullptr; 1252 } 1253 1254 // Get the limit of a recurrence such that incrementing by Step cannot cause 1255 // unsigned overflow as long as the value of the recurrence within the loop does 1256 // not exceed this limit before incrementing. 1257 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step, 1258 ICmpInst::Predicate *Pred, 1259 ScalarEvolution *SE) { 1260 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType()); 1261 *Pred = ICmpInst::ICMP_ULT; 1262 1263 return SE->getConstant(APInt::getMinValue(BitWidth) - 1264 SE->getUnsignedRangeMax(Step)); 1265 } 1266 1267 namespace { 1268 1269 struct ExtendOpTraitsBase { 1270 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *, 1271 unsigned); 1272 }; 1273 1274 // Used to make code generic over signed and unsigned overflow. 1275 template <typename ExtendOp> struct ExtendOpTraits { 1276 // Members present: 1277 // 1278 // static const SCEV::NoWrapFlags WrapType; 1279 // 1280 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr; 1281 // 1282 // static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1283 // ICmpInst::Predicate *Pred, 1284 // ScalarEvolution *SE); 1285 }; 1286 1287 template <> 1288 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase { 1289 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW; 1290 1291 static const GetExtendExprTy GetExtendExpr; 1292 1293 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1294 ICmpInst::Predicate *Pred, 1295 ScalarEvolution *SE) { 1296 return getSignedOverflowLimitForStep(Step, Pred, SE); 1297 } 1298 }; 1299 1300 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1301 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr; 1302 1303 template <> 1304 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase { 1305 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW; 1306 1307 static const GetExtendExprTy GetExtendExpr; 1308 1309 static const SCEV *getOverflowLimitForStep(const SCEV *Step, 1310 ICmpInst::Predicate *Pred, 1311 ScalarEvolution *SE) { 1312 return getUnsignedOverflowLimitForStep(Step, Pred, SE); 1313 } 1314 }; 1315 1316 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits< 1317 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr; 1318 1319 } // end anonymous namespace 1320 1321 // The recurrence AR has been shown to have no signed/unsigned wrap or something 1322 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as 1323 // easily prove NSW/NUW for its preincrement or postincrement sibling. This 1324 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step + 1325 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the 1326 // expression "Step + sext/zext(PreIncAR)" is congruent with 1327 // "sext/zext(PostIncAR)" 1328 template <typename ExtendOpTy> 1329 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty, 1330 ScalarEvolution *SE, unsigned Depth) { 1331 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1332 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1333 1334 const Loop *L = AR->getLoop(); 1335 const SCEV *Start = AR->getStart(); 1336 const SCEV *Step = AR->getStepRecurrence(*SE); 1337 1338 // Check for a simple looking step prior to loop entry. 1339 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start); 1340 if (!SA) 1341 return nullptr; 1342 1343 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV 1344 // subtraction is expensive. For this purpose, perform a quick and dirty 1345 // difference, by checking for Step in the operand list. 1346 SmallVector<const SCEV *, 4> DiffOps; 1347 for (const SCEV *Op : SA->operands()) 1348 if (Op != Step) 1349 DiffOps.push_back(Op); 1350 1351 if (DiffOps.size() == SA->getNumOperands()) 1352 return nullptr; 1353 1354 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` + 1355 // `Step`: 1356 1357 // 1. NSW/NUW flags on the step increment. 1358 auto PreStartFlags = 1359 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW); 1360 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags); 1361 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>( 1362 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap)); 1363 1364 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies 1365 // "S+X does not sign/unsign-overflow". 1366 // 1367 1368 const SCEV *BECount = SE->getBackedgeTakenCount(L); 1369 if (PreAR && PreAR->getNoWrapFlags(WrapType) && 1370 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount)) 1371 return PreStart; 1372 1373 // 2. Direct overflow check on the step operation's expression. 1374 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType()); 1375 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2); 1376 const SCEV *OperandExtendedStart = 1377 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth), 1378 (SE->*GetExtendExpr)(Step, WideTy, Depth)); 1379 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) { 1380 if (PreAR && AR->getNoWrapFlags(WrapType)) { 1381 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW 1382 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then 1383 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact. 1384 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType); 1385 } 1386 return PreStart; 1387 } 1388 1389 // 3. Loop precondition. 1390 ICmpInst::Predicate Pred; 1391 const SCEV *OverflowLimit = 1392 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE); 1393 1394 if (OverflowLimit && 1395 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) 1396 return PreStart; 1397 1398 return nullptr; 1399 } 1400 1401 // Get the normalized zero or sign extended expression for this AddRec's Start. 1402 template <typename ExtendOpTy> 1403 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty, 1404 ScalarEvolution *SE, 1405 unsigned Depth) { 1406 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr; 1407 1408 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth); 1409 if (!PreStart) 1410 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth); 1411 1412 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, 1413 Depth), 1414 (SE->*GetExtendExpr)(PreStart, Ty, Depth)); 1415 } 1416 1417 // Try to prove away overflow by looking at "nearby" add recurrences. A 1418 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it 1419 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`. 1420 // 1421 // Formally: 1422 // 1423 // {S,+,X} == {S-T,+,X} + T 1424 // => Ext({S,+,X}) == Ext({S-T,+,X} + T) 1425 // 1426 // If ({S-T,+,X} + T) does not overflow ... (1) 1427 // 1428 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T) 1429 // 1430 // If {S-T,+,X} does not overflow ... (2) 1431 // 1432 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T) 1433 // == {Ext(S-T)+Ext(T),+,Ext(X)} 1434 // 1435 // If (S-T)+T does not overflow ... (3) 1436 // 1437 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)} 1438 // == {Ext(S),+,Ext(X)} == LHS 1439 // 1440 // Thus, if (1), (2) and (3) are true for some T, then 1441 // Ext({S,+,X}) == {Ext(S),+,Ext(X)} 1442 // 1443 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T) 1444 // does not overflow" restricted to the 0th iteration. Therefore we only need 1445 // to check for (1) and (2). 1446 // 1447 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T 1448 // is `Delta` (defined below). 1449 template <typename ExtendOpTy> 1450 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start, 1451 const SCEV *Step, 1452 const Loop *L) { 1453 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType; 1454 1455 // We restrict `Start` to a constant to prevent SCEV from spending too much 1456 // time here. It is correct (but more expensive) to continue with a 1457 // non-constant `Start` and do a general SCEV subtraction to compute 1458 // `PreStart` below. 1459 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start); 1460 if (!StartC) 1461 return false; 1462 1463 APInt StartAI = StartC->getAPInt(); 1464 1465 for (unsigned Delta : {-2, -1, 1, 2}) { 1466 const SCEV *PreStart = getConstant(StartAI - Delta); 1467 1468 FoldingSetNodeID ID; 1469 ID.AddInteger(scAddRecExpr); 1470 ID.AddPointer(PreStart); 1471 ID.AddPointer(Step); 1472 ID.AddPointer(L); 1473 void *IP = nullptr; 1474 const auto *PreAR = 1475 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 1476 1477 // Give up if we don't already have the add recurrence we need because 1478 // actually constructing an add recurrence is relatively expensive. 1479 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2) 1480 const SCEV *DeltaS = getConstant(StartC->getType(), Delta); 1481 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; 1482 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep( 1483 DeltaS, &Pred, this); 1484 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1) 1485 return true; 1486 } 1487 } 1488 1489 return false; 1490 } 1491 1492 // Finds an integer D for an expression (C + x + y + ...) such that the top 1493 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or 1494 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is 1495 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and 1496 // the (C + x + y + ...) expression is \p WholeAddExpr. 1497 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1498 const SCEVConstant *ConstantTerm, 1499 const SCEVAddExpr *WholeAddExpr) { 1500 const APInt &C = ConstantTerm->getAPInt(); 1501 const unsigned BitWidth = C.getBitWidth(); 1502 // Find number of trailing zeros of (x + y + ...) w/o the C first: 1503 uint32_t TZ = BitWidth; 1504 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I) 1505 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I))); 1506 if (TZ) { 1507 // Set D to be as many least significant bits of C as possible while still 1508 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap: 1509 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C; 1510 } 1511 return APInt(BitWidth, 0); 1512 } 1513 1514 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top 1515 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the 1516 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p 1517 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count. 1518 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE, 1519 const APInt &ConstantStart, 1520 const SCEV *Step) { 1521 const unsigned BitWidth = ConstantStart.getBitWidth(); 1522 const uint32_t TZ = SE.GetMinTrailingZeros(Step); 1523 if (TZ) 1524 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth) 1525 : ConstantStart; 1526 return APInt(BitWidth, 0); 1527 } 1528 1529 const SCEV * 1530 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1531 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1532 "This is not an extending conversion!"); 1533 assert(isSCEVable(Ty) && 1534 "This is not a conversion to a SCEVable type!"); 1535 Ty = getEffectiveSCEVType(Ty); 1536 1537 // Fold if the operand is constant. 1538 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1539 return getConstant( 1540 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty))); 1541 1542 // zext(zext(x)) --> zext(x) 1543 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1544 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1545 1546 // Before doing any expensive analysis, check to see if we've already 1547 // computed a SCEV for this Op and Ty. 1548 FoldingSetNodeID ID; 1549 ID.AddInteger(scZeroExtend); 1550 ID.AddPointer(Op); 1551 ID.AddPointer(Ty); 1552 void *IP = nullptr; 1553 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1554 if (Depth > MaxCastDepth) { 1555 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1556 Op, Ty); 1557 UniqueSCEVs.InsertNode(S, IP); 1558 addToLoopUseLists(S); 1559 return S; 1560 } 1561 1562 // zext(trunc(x)) --> zext(x) or x or trunc(x) 1563 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1564 // It's possible the bits taken off by the truncate were all zero bits. If 1565 // so, we should be able to simplify this further. 1566 const SCEV *X = ST->getOperand(); 1567 ConstantRange CR = getUnsignedRange(X); 1568 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1569 unsigned NewBits = getTypeSizeInBits(Ty); 1570 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains( 1571 CR.zextOrTrunc(NewBits))) 1572 return getTruncateOrZeroExtend(X, Ty, Depth); 1573 } 1574 1575 // If the input value is a chrec scev, and we can prove that the value 1576 // did not overflow the old, smaller, value, we can zero extend all of the 1577 // operands (often constants). This allows analysis of something like 1578 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; } 1579 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1580 if (AR->isAffine()) { 1581 const SCEV *Start = AR->getStart(); 1582 const SCEV *Step = AR->getStepRecurrence(*this); 1583 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1584 const Loop *L = AR->getLoop(); 1585 1586 if (!AR->hasNoUnsignedWrap()) { 1587 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1588 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1589 } 1590 1591 // If we have special knowledge that this addrec won't overflow, 1592 // we don't need to do any further analysis. 1593 if (AR->hasNoUnsignedWrap()) 1594 return getAddRecExpr( 1595 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1596 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1597 1598 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1599 // Note that this serves two purposes: It filters out loops that are 1600 // simply not analyzable, and it covers the case where this code is 1601 // being called from within backedge-taken count analysis, such that 1602 // attempting to ask for the backedge-taken count would likely result 1603 // in infinite recursion. In the later case, the analysis code will 1604 // cope with a conservative value, and it will take care to purge 1605 // that value once it has finished. 1606 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1607 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1608 // Manually compute the final value for AR, checking for 1609 // overflow. 1610 1611 // Check whether the backedge-taken count can be losslessly casted to 1612 // the addrec's type. The count is always unsigned. 1613 const SCEV *CastedMaxBECount = 1614 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1615 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1616 CastedMaxBECount, MaxBECount->getType(), Depth); 1617 if (MaxBECount == RecastedMaxBECount) { 1618 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1619 // Check whether Start+Step*MaxBECount has no unsigned overflow. 1620 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step, 1621 SCEV::FlagAnyWrap, Depth + 1); 1622 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul, 1623 SCEV::FlagAnyWrap, 1624 Depth + 1), 1625 WideTy, Depth + 1); 1626 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1); 1627 const SCEV *WideMaxBECount = 1628 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1629 const SCEV *OperandExtendedAdd = 1630 getAddExpr(WideStart, 1631 getMulExpr(WideMaxBECount, 1632 getZeroExtendExpr(Step, WideTy, Depth + 1), 1633 SCEV::FlagAnyWrap, Depth + 1), 1634 SCEV::FlagAnyWrap, Depth + 1); 1635 if (ZAdd == OperandExtendedAdd) { 1636 // Cache knowledge of AR NUW, which is propagated to this AddRec. 1637 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1638 // Return the expression with the addrec on the outside. 1639 return getAddRecExpr( 1640 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1641 Depth + 1), 1642 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1643 AR->getNoWrapFlags()); 1644 } 1645 // Similar to above, only this time treat the step value as signed. 1646 // This covers loops that count down. 1647 OperandExtendedAdd = 1648 getAddExpr(WideStart, 1649 getMulExpr(WideMaxBECount, 1650 getSignExtendExpr(Step, WideTy, Depth + 1), 1651 SCEV::FlagAnyWrap, Depth + 1), 1652 SCEV::FlagAnyWrap, Depth + 1); 1653 if (ZAdd == OperandExtendedAdd) { 1654 // Cache knowledge of AR NW, which is propagated to this AddRec. 1655 // Negative step causes unsigned wrap, but it still can't self-wrap. 1656 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1657 // Return the expression with the addrec on the outside. 1658 return getAddRecExpr( 1659 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1660 Depth + 1), 1661 getSignExtendExpr(Step, Ty, Depth + 1), L, 1662 AR->getNoWrapFlags()); 1663 } 1664 } 1665 } 1666 1667 // Normally, in the cases we can prove no-overflow via a 1668 // backedge guarding condition, we can also compute a backedge 1669 // taken count for the loop. The exceptions are assumptions and 1670 // guards present in the loop -- SCEV is not great at exploiting 1671 // these to compute max backedge taken counts, but can still use 1672 // these to prove lack of overflow. Use this fact to avoid 1673 // doing extra work that may not pay off. 1674 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 1675 !AC.assumptions().empty()) { 1676 // If the backedge is guarded by a comparison with the pre-inc 1677 // value the addrec is safe. Also, if the entry is guarded by 1678 // a comparison with the start value and the backedge is 1679 // guarded by a comparison with the post-inc value, the addrec 1680 // is safe. 1681 if (isKnownPositive(Step)) { 1682 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) - 1683 getUnsignedRangeMax(Step)); 1684 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) || 1685 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) { 1686 // Cache knowledge of AR NUW, which is propagated to this 1687 // AddRec. 1688 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1689 // Return the expression with the addrec on the outside. 1690 return getAddRecExpr( 1691 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1692 Depth + 1), 1693 getZeroExtendExpr(Step, Ty, Depth + 1), L, 1694 AR->getNoWrapFlags()); 1695 } 1696 } else if (isKnownNegative(Step)) { 1697 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) - 1698 getSignedRangeMin(Step)); 1699 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) || 1700 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) { 1701 // Cache knowledge of AR NW, which is propagated to this 1702 // AddRec. Negative step causes unsigned wrap, but it 1703 // still can't self-wrap. 1704 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 1705 // Return the expression with the addrec on the outside. 1706 return getAddRecExpr( 1707 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 1708 Depth + 1), 1709 getSignExtendExpr(Step, Ty, Depth + 1), L, 1710 AR->getNoWrapFlags()); 1711 } 1712 } 1713 } 1714 1715 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw> 1716 // if D + (C - D + Step * n) could be proven to not unsigned wrap 1717 // where D maximizes the number of trailing zeros of (C - D + Step * n) 1718 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 1719 const APInt &C = SC->getAPInt(); 1720 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 1721 if (D != 0) { 1722 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1723 const SCEV *SResidual = 1724 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 1725 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1726 return getAddExpr(SZExtD, SZExtR, 1727 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1728 Depth + 1); 1729 } 1730 } 1731 1732 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) { 1733 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW); 1734 return getAddRecExpr( 1735 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1), 1736 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 1737 } 1738 } 1739 1740 // zext(A % B) --> zext(A) % zext(B) 1741 { 1742 const SCEV *LHS; 1743 const SCEV *RHS; 1744 if (matchURem(Op, LHS, RHS)) 1745 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1), 1746 getZeroExtendExpr(RHS, Ty, Depth + 1)); 1747 } 1748 1749 // zext(A / B) --> zext(A) / zext(B). 1750 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op)) 1751 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1), 1752 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1)); 1753 1754 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1755 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw> 1756 if (SA->hasNoUnsignedWrap()) { 1757 // If the addition does not unsign overflow then we can, by definition, 1758 // commute the zero extension with the addition operation. 1759 SmallVector<const SCEV *, 4> Ops; 1760 for (const auto *Op : SA->operands()) 1761 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1762 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1); 1763 } 1764 1765 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...)) 1766 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap 1767 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1768 // 1769 // Often address arithmetics contain expressions like 1770 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))). 1771 // This transformation is useful while proving that such expressions are 1772 // equal or differ by a small constant amount, see LoadStoreVectorizer pass. 1773 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1774 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1775 if (D != 0) { 1776 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth); 1777 const SCEV *SResidual = 1778 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1779 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1); 1780 return getAddExpr(SZExtD, SZExtR, 1781 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1782 Depth + 1); 1783 } 1784 } 1785 } 1786 1787 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) { 1788 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw> 1789 if (SM->hasNoUnsignedWrap()) { 1790 // If the multiply does not unsign overflow then we can, by definition, 1791 // commute the zero extension with the multiply operation. 1792 SmallVector<const SCEV *, 4> Ops; 1793 for (const auto *Op : SM->operands()) 1794 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1)); 1795 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1); 1796 } 1797 1798 // zext(2^K * (trunc X to iN)) to iM -> 1799 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw> 1800 // 1801 // Proof: 1802 // 1803 // zext(2^K * (trunc X to iN)) to iM 1804 // = zext((trunc X to iN) << K) to iM 1805 // = zext((trunc X to i{N-K}) << K)<nuw> to iM 1806 // (because shl removes the top K bits) 1807 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM 1808 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>. 1809 // 1810 if (SM->getNumOperands() == 2) 1811 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0))) 1812 if (MulLHS->getAPInt().isPowerOf2()) 1813 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) { 1814 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) - 1815 MulLHS->getAPInt().logBase2(); 1816 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits); 1817 return getMulExpr( 1818 getZeroExtendExpr(MulLHS, Ty), 1819 getZeroExtendExpr( 1820 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty), 1821 SCEV::FlagNUW, Depth + 1); 1822 } 1823 } 1824 1825 // The cast wasn't folded; create an explicit cast node. 1826 // Recompute the insert position, as it may have been invalidated. 1827 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1828 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator), 1829 Op, Ty); 1830 UniqueSCEVs.InsertNode(S, IP); 1831 addToLoopUseLists(S); 1832 return S; 1833 } 1834 1835 const SCEV * 1836 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) { 1837 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 1838 "This is not an extending conversion!"); 1839 assert(isSCEVable(Ty) && 1840 "This is not a conversion to a SCEVable type!"); 1841 Ty = getEffectiveSCEVType(Ty); 1842 1843 // Fold if the operand is constant. 1844 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 1845 return getConstant( 1846 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty))); 1847 1848 // sext(sext(x)) --> sext(x) 1849 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op)) 1850 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1); 1851 1852 // sext(zext(x)) --> zext(x) 1853 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op)) 1854 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1); 1855 1856 // Before doing any expensive analysis, check to see if we've already 1857 // computed a SCEV for this Op and Ty. 1858 FoldingSetNodeID ID; 1859 ID.AddInteger(scSignExtend); 1860 ID.AddPointer(Op); 1861 ID.AddPointer(Ty); 1862 void *IP = nullptr; 1863 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 1864 // Limit recursion depth. 1865 if (Depth > MaxCastDepth) { 1866 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 1867 Op, Ty); 1868 UniqueSCEVs.InsertNode(S, IP); 1869 addToLoopUseLists(S); 1870 return S; 1871 } 1872 1873 // sext(trunc(x)) --> sext(x) or x or trunc(x) 1874 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) { 1875 // It's possible the bits taken off by the truncate were all sign bits. If 1876 // so, we should be able to simplify this further. 1877 const SCEV *X = ST->getOperand(); 1878 ConstantRange CR = getSignedRange(X); 1879 unsigned TruncBits = getTypeSizeInBits(ST->getType()); 1880 unsigned NewBits = getTypeSizeInBits(Ty); 1881 if (CR.truncate(TruncBits).signExtend(NewBits).contains( 1882 CR.sextOrTrunc(NewBits))) 1883 return getTruncateOrSignExtend(X, Ty, Depth); 1884 } 1885 1886 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) { 1887 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 1888 if (SA->hasNoSignedWrap()) { 1889 // If the addition does not sign overflow then we can, by definition, 1890 // commute the sign extension with the addition operation. 1891 SmallVector<const SCEV *, 4> Ops; 1892 for (const auto *Op : SA->operands()) 1893 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1)); 1894 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1); 1895 } 1896 1897 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...)) 1898 // if D + (C - D + x + y + ...) could be proven to not signed wrap 1899 // where D maximizes the number of trailing zeros of (C - D + x + y + ...) 1900 // 1901 // For instance, this will bring two seemingly different expressions: 1902 // 1 + sext(5 + 20 * %x + 24 * %y) and 1903 // sext(6 + 20 * %x + 24 * %y) 1904 // to the same form: 1905 // 2 + sext(4 + 20 * %x + 24 * %y) 1906 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) { 1907 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA); 1908 if (D != 0) { 1909 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 1910 const SCEV *SResidual = 1911 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth); 1912 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 1913 return getAddExpr(SSExtD, SSExtR, 1914 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 1915 Depth + 1); 1916 } 1917 } 1918 } 1919 // If the input value is a chrec scev, and we can prove that the value 1920 // did not overflow the old, smaller, value, we can sign extend all of the 1921 // operands (often constants). This allows analysis of something like 1922 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; } 1923 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) 1924 if (AR->isAffine()) { 1925 const SCEV *Start = AR->getStart(); 1926 const SCEV *Step = AR->getStepRecurrence(*this); 1927 unsigned BitWidth = getTypeSizeInBits(AR->getType()); 1928 const Loop *L = AR->getLoop(); 1929 1930 if (!AR->hasNoSignedWrap()) { 1931 auto NewFlags = proveNoWrapViaConstantRanges(AR); 1932 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags); 1933 } 1934 1935 // If we have special knowledge that this addrec won't overflow, 1936 // we don't need to do any further analysis. 1937 if (AR->hasNoSignedWrap()) 1938 return getAddRecExpr( 1939 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 1940 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW); 1941 1942 // Check whether the backedge-taken count is SCEVCouldNotCompute. 1943 // Note that this serves two purposes: It filters out loops that are 1944 // simply not analyzable, and it covers the case where this code is 1945 // being called from within backedge-taken count analysis, such that 1946 // attempting to ask for the backedge-taken count would likely result 1947 // in infinite recursion. In the later case, the analysis code will 1948 // cope with a conservative value, and it will take care to purge 1949 // that value once it has finished. 1950 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L); 1951 if (!isa<SCEVCouldNotCompute>(MaxBECount)) { 1952 // Manually compute the final value for AR, checking for 1953 // overflow. 1954 1955 // Check whether the backedge-taken count can be losslessly casted to 1956 // the addrec's type. The count is always unsigned. 1957 const SCEV *CastedMaxBECount = 1958 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth); 1959 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend( 1960 CastedMaxBECount, MaxBECount->getType(), Depth); 1961 if (MaxBECount == RecastedMaxBECount) { 1962 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2); 1963 // Check whether Start+Step*MaxBECount has no signed overflow. 1964 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step, 1965 SCEV::FlagAnyWrap, Depth + 1); 1966 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul, 1967 SCEV::FlagAnyWrap, 1968 Depth + 1), 1969 WideTy, Depth + 1); 1970 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1); 1971 const SCEV *WideMaxBECount = 1972 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1); 1973 const SCEV *OperandExtendedAdd = 1974 getAddExpr(WideStart, 1975 getMulExpr(WideMaxBECount, 1976 getSignExtendExpr(Step, WideTy, Depth + 1), 1977 SCEV::FlagAnyWrap, Depth + 1), 1978 SCEV::FlagAnyWrap, Depth + 1); 1979 if (SAdd == OperandExtendedAdd) { 1980 // Cache knowledge of AR NSW, which is propagated to this AddRec. 1981 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 1982 // Return the expression with the addrec on the outside. 1983 return getAddRecExpr( 1984 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 1985 Depth + 1), 1986 getSignExtendExpr(Step, Ty, Depth + 1), L, 1987 AR->getNoWrapFlags()); 1988 } 1989 // Similar to above, only this time treat the step value as unsigned. 1990 // This covers loops that count up with an unsigned step. 1991 OperandExtendedAdd = 1992 getAddExpr(WideStart, 1993 getMulExpr(WideMaxBECount, 1994 getZeroExtendExpr(Step, WideTy, Depth + 1), 1995 SCEV::FlagAnyWrap, Depth + 1), 1996 SCEV::FlagAnyWrap, Depth + 1); 1997 if (SAdd == OperandExtendedAdd) { 1998 // If AR wraps around then 1999 // 2000 // abs(Step) * MaxBECount > unsigned-max(AR->getType()) 2001 // => SAdd != OperandExtendedAdd 2002 // 2003 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=> 2004 // (SAdd == OperandExtendedAdd => AR is NW) 2005 2006 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW); 2007 2008 // Return the expression with the addrec on the outside. 2009 return getAddRecExpr( 2010 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, 2011 Depth + 1), 2012 getZeroExtendExpr(Step, Ty, Depth + 1), L, 2013 AR->getNoWrapFlags()); 2014 } 2015 } 2016 } 2017 2018 // Normally, in the cases we can prove no-overflow via a 2019 // backedge guarding condition, we can also compute a backedge 2020 // taken count for the loop. The exceptions are assumptions and 2021 // guards present in the loop -- SCEV is not great at exploiting 2022 // these to compute max backedge taken counts, but can still use 2023 // these to prove lack of overflow. Use this fact to avoid 2024 // doing extra work that may not pay off. 2025 2026 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards || 2027 !AC.assumptions().empty()) { 2028 // If the backedge is guarded by a comparison with the pre-inc 2029 // value the addrec is safe. Also, if the entry is guarded by 2030 // a comparison with the start value and the backedge is 2031 // guarded by a comparison with the post-inc value, the addrec 2032 // is safe. 2033 ICmpInst::Predicate Pred; 2034 const SCEV *OverflowLimit = 2035 getSignedOverflowLimitForStep(Step, &Pred, this); 2036 if (OverflowLimit && 2037 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) || 2038 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) { 2039 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec. 2040 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2041 return getAddRecExpr( 2042 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2043 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2044 } 2045 } 2046 2047 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw> 2048 // if D + (C - D + Step * n) could be proven to not signed wrap 2049 // where D maximizes the number of trailing zeros of (C - D + Step * n) 2050 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) { 2051 const APInt &C = SC->getAPInt(); 2052 const APInt &D = extractConstantWithoutWrapping(*this, C, Step); 2053 if (D != 0) { 2054 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth); 2055 const SCEV *SResidual = 2056 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags()); 2057 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1); 2058 return getAddExpr(SSExtD, SSExtR, 2059 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW), 2060 Depth + 1); 2061 } 2062 } 2063 2064 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) { 2065 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW); 2066 return getAddRecExpr( 2067 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1), 2068 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags()); 2069 } 2070 } 2071 2072 // If the input value is provably positive and we could not simplify 2073 // away the sext build a zext instead. 2074 if (isKnownNonNegative(Op)) 2075 return getZeroExtendExpr(Op, Ty, Depth + 1); 2076 2077 // The cast wasn't folded; create an explicit cast node. 2078 // Recompute the insert position, as it may have been invalidated. 2079 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 2080 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator), 2081 Op, Ty); 2082 UniqueSCEVs.InsertNode(S, IP); 2083 addToLoopUseLists(S); 2084 return S; 2085 } 2086 2087 /// getAnyExtendExpr - Return a SCEV for the given operand extended with 2088 /// unspecified bits out to the given type. 2089 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op, 2090 Type *Ty) { 2091 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) && 2092 "This is not an extending conversion!"); 2093 assert(isSCEVable(Ty) && 2094 "This is not a conversion to a SCEVable type!"); 2095 Ty = getEffectiveSCEVType(Ty); 2096 2097 // Sign-extend negative constants. 2098 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) 2099 if (SC->getAPInt().isNegative()) 2100 return getSignExtendExpr(Op, Ty); 2101 2102 // Peel off a truncate cast. 2103 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) { 2104 const SCEV *NewOp = T->getOperand(); 2105 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty)) 2106 return getAnyExtendExpr(NewOp, Ty); 2107 return getTruncateOrNoop(NewOp, Ty); 2108 } 2109 2110 // Next try a zext cast. If the cast is folded, use it. 2111 const SCEV *ZExt = getZeroExtendExpr(Op, Ty); 2112 if (!isa<SCEVZeroExtendExpr>(ZExt)) 2113 return ZExt; 2114 2115 // Next try a sext cast. If the cast is folded, use it. 2116 const SCEV *SExt = getSignExtendExpr(Op, Ty); 2117 if (!isa<SCEVSignExtendExpr>(SExt)) 2118 return SExt; 2119 2120 // Force the cast to be folded into the operands of an addrec. 2121 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) { 2122 SmallVector<const SCEV *, 4> Ops; 2123 for (const SCEV *Op : AR->operands()) 2124 Ops.push_back(getAnyExtendExpr(Op, Ty)); 2125 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW); 2126 } 2127 2128 // If the expression is obviously signed, use the sext cast value. 2129 if (isa<SCEVSMaxExpr>(Op)) 2130 return SExt; 2131 2132 // Absent any other information, use the zext cast value. 2133 return ZExt; 2134 } 2135 2136 /// Process the given Ops list, which is a list of operands to be added under 2137 /// the given scale, update the given map. This is a helper function for 2138 /// getAddRecExpr. As an example of what it does, given a sequence of operands 2139 /// that would form an add expression like this: 2140 /// 2141 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r) 2142 /// 2143 /// where A and B are constants, update the map with these values: 2144 /// 2145 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0) 2146 /// 2147 /// and add 13 + A*B*29 to AccumulatedConstant. 2148 /// This will allow getAddRecExpr to produce this: 2149 /// 2150 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B) 2151 /// 2152 /// This form often exposes folding opportunities that are hidden in 2153 /// the original operand list. 2154 /// 2155 /// Return true iff it appears that any interesting folding opportunities 2156 /// may be exposed. This helps getAddRecExpr short-circuit extra work in 2157 /// the common case where no interesting opportunities are present, and 2158 /// is also used as a check to avoid infinite recursion. 2159 static bool 2160 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M, 2161 SmallVectorImpl<const SCEV *> &NewOps, 2162 APInt &AccumulatedConstant, 2163 const SCEV *const *Ops, size_t NumOperands, 2164 const APInt &Scale, 2165 ScalarEvolution &SE) { 2166 bool Interesting = false; 2167 2168 // Iterate over the add operands. They are sorted, with constants first. 2169 unsigned i = 0; 2170 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2171 ++i; 2172 // Pull a buried constant out to the outside. 2173 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero()) 2174 Interesting = true; 2175 AccumulatedConstant += Scale * C->getAPInt(); 2176 } 2177 2178 // Next comes everything else. We're especially interested in multiplies 2179 // here, but they're in the middle, so just visit the rest with one loop. 2180 for (; i != NumOperands; ++i) { 2181 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]); 2182 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) { 2183 APInt NewScale = 2184 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt(); 2185 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) { 2186 // A multiplication of a constant with another add; recurse. 2187 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1)); 2188 Interesting |= 2189 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2190 Add->op_begin(), Add->getNumOperands(), 2191 NewScale, SE); 2192 } else { 2193 // A multiplication of a constant with some other value. Update 2194 // the map. 2195 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end()); 2196 const SCEV *Key = SE.getMulExpr(MulOps); 2197 auto Pair = M.insert({Key, NewScale}); 2198 if (Pair.second) { 2199 NewOps.push_back(Pair.first->first); 2200 } else { 2201 Pair.first->second += NewScale; 2202 // The map already had an entry for this value, which may indicate 2203 // a folding opportunity. 2204 Interesting = true; 2205 } 2206 } 2207 } else { 2208 // An ordinary operand. Update the map. 2209 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair = 2210 M.insert({Ops[i], Scale}); 2211 if (Pair.second) { 2212 NewOps.push_back(Pair.first->first); 2213 } else { 2214 Pair.first->second += Scale; 2215 // The map already had an entry for this value, which may indicate 2216 // a folding opportunity. 2217 Interesting = true; 2218 } 2219 } 2220 } 2221 2222 return Interesting; 2223 } 2224 2225 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and 2226 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of 2227 // can't-overflow flags for the operation if possible. 2228 static SCEV::NoWrapFlags 2229 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type, 2230 const ArrayRef<const SCEV *> Ops, 2231 SCEV::NoWrapFlags Flags) { 2232 using namespace std::placeholders; 2233 2234 using OBO = OverflowingBinaryOperator; 2235 2236 bool CanAnalyze = 2237 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr; 2238 (void)CanAnalyze; 2239 assert(CanAnalyze && "don't call from other places!"); 2240 2241 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW; 2242 SCEV::NoWrapFlags SignOrUnsignWrap = 2243 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2244 2245 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW. 2246 auto IsKnownNonNegative = [&](const SCEV *S) { 2247 return SE->isKnownNonNegative(S); 2248 }; 2249 2250 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative)) 2251 Flags = 2252 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask); 2253 2254 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask); 2255 2256 if (SignOrUnsignWrap != SignOrUnsignMask && 2257 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 && 2258 isa<SCEVConstant>(Ops[0])) { 2259 2260 auto Opcode = [&] { 2261 switch (Type) { 2262 case scAddExpr: 2263 return Instruction::Add; 2264 case scMulExpr: 2265 return Instruction::Mul; 2266 default: 2267 llvm_unreachable("Unexpected SCEV op."); 2268 } 2269 }(); 2270 2271 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt(); 2272 2273 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow. 2274 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) { 2275 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2276 Opcode, C, OBO::NoSignedWrap); 2277 if (NSWRegion.contains(SE->getSignedRange(Ops[1]))) 2278 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW); 2279 } 2280 2281 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow. 2282 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) { 2283 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 2284 Opcode, C, OBO::NoUnsignedWrap); 2285 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1]))) 2286 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW); 2287 } 2288 } 2289 2290 return Flags; 2291 } 2292 2293 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) { 2294 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader()); 2295 } 2296 2297 /// Get a canonical add expression, or something simpler if possible. 2298 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 2299 SCEV::NoWrapFlags Flags, 2300 unsigned Depth) { 2301 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) && 2302 "only nuw or nsw allowed"); 2303 assert(!Ops.empty() && "Cannot get empty add!"); 2304 if (Ops.size() == 1) return Ops[0]; 2305 #ifndef NDEBUG 2306 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2307 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2308 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2309 "SCEVAddExpr operand types don't match!"); 2310 #endif 2311 2312 // Sort by complexity, this groups all similar expression types together. 2313 GroupByComplexity(Ops, &LI, DT); 2314 2315 // If there are any constants, fold them together. 2316 unsigned Idx = 0; 2317 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2318 ++Idx; 2319 assert(Idx < Ops.size()); 2320 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2321 // We found two constants, fold them together! 2322 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt()); 2323 if (Ops.size() == 2) return Ops[0]; 2324 Ops.erase(Ops.begin()+1); // Erase the folded element 2325 LHSC = cast<SCEVConstant>(Ops[0]); 2326 } 2327 2328 // If we are left with a constant zero being added, strip it off. 2329 if (LHSC->getValue()->isZero()) { 2330 Ops.erase(Ops.begin()); 2331 --Idx; 2332 } 2333 2334 if (Ops.size() == 1) return Ops[0]; 2335 } 2336 2337 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags); 2338 2339 // Limit recursion calls depth. 2340 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2341 return getOrCreateAddExpr(Ops, Flags); 2342 2343 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scAddExpr, Ops))) { 2344 static_cast<SCEVAddExpr *>(S)->setNoWrapFlags(Flags); 2345 return S; 2346 } 2347 2348 // Okay, check to see if the same value occurs in the operand list more than 2349 // once. If so, merge them together into an multiply expression. Since we 2350 // sorted the list, these values are required to be adjacent. 2351 Type *Ty = Ops[0]->getType(); 2352 bool FoundMatch = false; 2353 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i) 2354 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2 2355 // Scan ahead to count how many equal operands there are. 2356 unsigned Count = 2; 2357 while (i+Count != e && Ops[i+Count] == Ops[i]) 2358 ++Count; 2359 // Merge the values into a multiply. 2360 const SCEV *Scale = getConstant(Ty, Count); 2361 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1); 2362 if (Ops.size() == Count) 2363 return Mul; 2364 Ops[i] = Mul; 2365 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count); 2366 --i; e -= Count - 1; 2367 FoundMatch = true; 2368 } 2369 if (FoundMatch) 2370 return getAddExpr(Ops, Flags, Depth + 1); 2371 2372 // Check for truncates. If all the operands are truncated from the same 2373 // type, see if factoring out the truncate would permit the result to be 2374 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y) 2375 // if the contents of the resulting outer trunc fold to something simple. 2376 auto FindTruncSrcType = [&]() -> Type * { 2377 // We're ultimately looking to fold an addrec of truncs and muls of only 2378 // constants and truncs, so if we find any other types of SCEV 2379 // as operands of the addrec then we bail and return nullptr here. 2380 // Otherwise, we return the type of the operand of a trunc that we find. 2381 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx])) 2382 return T->getOperand()->getType(); 2383 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2384 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1); 2385 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp)) 2386 return T->getOperand()->getType(); 2387 } 2388 return nullptr; 2389 }; 2390 if (auto *SrcType = FindTruncSrcType()) { 2391 SmallVector<const SCEV *, 8> LargeOps; 2392 bool Ok = true; 2393 // Check all the operands to see if they can be represented in the 2394 // source type of the truncate. 2395 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 2396 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) { 2397 if (T->getOperand()->getType() != SrcType) { 2398 Ok = false; 2399 break; 2400 } 2401 LargeOps.push_back(T->getOperand()); 2402 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) { 2403 LargeOps.push_back(getAnyExtendExpr(C, SrcType)); 2404 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) { 2405 SmallVector<const SCEV *, 8> LargeMulOps; 2406 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) { 2407 if (const SCEVTruncateExpr *T = 2408 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) { 2409 if (T->getOperand()->getType() != SrcType) { 2410 Ok = false; 2411 break; 2412 } 2413 LargeMulOps.push_back(T->getOperand()); 2414 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) { 2415 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType)); 2416 } else { 2417 Ok = false; 2418 break; 2419 } 2420 } 2421 if (Ok) 2422 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1)); 2423 } else { 2424 Ok = false; 2425 break; 2426 } 2427 } 2428 if (Ok) { 2429 // Evaluate the expression in the larger type. 2430 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1); 2431 // If it folds to something simple, use it. Otherwise, don't. 2432 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold)) 2433 return getTruncateExpr(Fold, Ty); 2434 } 2435 } 2436 2437 // Skip past any other cast SCEVs. 2438 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr) 2439 ++Idx; 2440 2441 // If there are add operands they would be next. 2442 if (Idx < Ops.size()) { 2443 bool DeletedAdd = false; 2444 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) { 2445 if (Ops.size() > AddOpsInlineThreshold || 2446 Add->getNumOperands() > AddOpsInlineThreshold) 2447 break; 2448 // If we have an add, expand the add operands onto the end of the operands 2449 // list. 2450 Ops.erase(Ops.begin()+Idx); 2451 Ops.append(Add->op_begin(), Add->op_end()); 2452 DeletedAdd = true; 2453 } 2454 2455 // If we deleted at least one add, we added operands to the end of the list, 2456 // and they are not necessarily sorted. Recurse to resort and resimplify 2457 // any operands we just acquired. 2458 if (DeletedAdd) 2459 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2460 } 2461 2462 // Skip over the add expression until we get to a multiply. 2463 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2464 ++Idx; 2465 2466 // Check to see if there are any folding opportunities present with 2467 // operands multiplied by constant values. 2468 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) { 2469 uint64_t BitWidth = getTypeSizeInBits(Ty); 2470 DenseMap<const SCEV *, APInt> M; 2471 SmallVector<const SCEV *, 8> NewOps; 2472 APInt AccumulatedConstant(BitWidth, 0); 2473 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant, 2474 Ops.data(), Ops.size(), 2475 APInt(BitWidth, 1), *this)) { 2476 struct APIntCompare { 2477 bool operator()(const APInt &LHS, const APInt &RHS) const { 2478 return LHS.ult(RHS); 2479 } 2480 }; 2481 2482 // Some interesting folding opportunity is present, so its worthwhile to 2483 // re-generate the operands list. Group the operands by constant scale, 2484 // to avoid multiplying by the same constant scale multiple times. 2485 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists; 2486 for (const SCEV *NewOp : NewOps) 2487 MulOpLists[M.find(NewOp)->second].push_back(NewOp); 2488 // Re-generate the operands list. 2489 Ops.clear(); 2490 if (AccumulatedConstant != 0) 2491 Ops.push_back(getConstant(AccumulatedConstant)); 2492 for (auto &MulOp : MulOpLists) 2493 if (MulOp.first != 0) 2494 Ops.push_back(getMulExpr( 2495 getConstant(MulOp.first), 2496 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1), 2497 SCEV::FlagAnyWrap, Depth + 1)); 2498 if (Ops.empty()) 2499 return getZero(Ty); 2500 if (Ops.size() == 1) 2501 return Ops[0]; 2502 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2503 } 2504 } 2505 2506 // If we are adding something to a multiply expression, make sure the 2507 // something is not already an operand of the multiply. If so, merge it into 2508 // the multiply. 2509 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) { 2510 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]); 2511 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) { 2512 const SCEV *MulOpSCEV = Mul->getOperand(MulOp); 2513 if (isa<SCEVConstant>(MulOpSCEV)) 2514 continue; 2515 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp) 2516 if (MulOpSCEV == Ops[AddOp]) { 2517 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1)) 2518 const SCEV *InnerMul = Mul->getOperand(MulOp == 0); 2519 if (Mul->getNumOperands() != 2) { 2520 // If the multiply has more than two operands, we must get the 2521 // Y*Z term. 2522 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2523 Mul->op_begin()+MulOp); 2524 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2525 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2526 } 2527 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul}; 2528 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2529 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV, 2530 SCEV::FlagAnyWrap, Depth + 1); 2531 if (Ops.size() == 2) return OuterMul; 2532 if (AddOp < Idx) { 2533 Ops.erase(Ops.begin()+AddOp); 2534 Ops.erase(Ops.begin()+Idx-1); 2535 } else { 2536 Ops.erase(Ops.begin()+Idx); 2537 Ops.erase(Ops.begin()+AddOp-1); 2538 } 2539 Ops.push_back(OuterMul); 2540 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2541 } 2542 2543 // Check this multiply against other multiplies being added together. 2544 for (unsigned OtherMulIdx = Idx+1; 2545 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]); 2546 ++OtherMulIdx) { 2547 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]); 2548 // If MulOp occurs in OtherMul, we can fold the two multiplies 2549 // together. 2550 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands(); 2551 OMulOp != e; ++OMulOp) 2552 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) { 2553 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E)) 2554 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0); 2555 if (Mul->getNumOperands() != 2) { 2556 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), 2557 Mul->op_begin()+MulOp); 2558 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end()); 2559 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2560 } 2561 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0); 2562 if (OtherMul->getNumOperands() != 2) { 2563 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(), 2564 OtherMul->op_begin()+OMulOp); 2565 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end()); 2566 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1); 2567 } 2568 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2}; 2569 const SCEV *InnerMulSum = 2570 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2571 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum, 2572 SCEV::FlagAnyWrap, Depth + 1); 2573 if (Ops.size() == 2) return OuterMul; 2574 Ops.erase(Ops.begin()+Idx); 2575 Ops.erase(Ops.begin()+OtherMulIdx-1); 2576 Ops.push_back(OuterMul); 2577 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2578 } 2579 } 2580 } 2581 } 2582 2583 // If there are any add recurrences in the operands list, see if any other 2584 // added values are loop invariant. If so, we can fold them into the 2585 // recurrence. 2586 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2587 ++Idx; 2588 2589 // Scan over all recurrences, trying to fold loop invariants into them. 2590 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2591 // Scan all of the other operands to this add and add them to the vector if 2592 // they are loop invariant w.r.t. the recurrence. 2593 SmallVector<const SCEV *, 8> LIOps; 2594 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2595 const Loop *AddRecLoop = AddRec->getLoop(); 2596 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2597 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2598 LIOps.push_back(Ops[i]); 2599 Ops.erase(Ops.begin()+i); 2600 --i; --e; 2601 } 2602 2603 // If we found some loop invariants, fold them into the recurrence. 2604 if (!LIOps.empty()) { 2605 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step} 2606 LIOps.push_back(AddRec->getStart()); 2607 2608 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2609 AddRec->op_end()); 2610 // This follows from the fact that the no-wrap flags on the outer add 2611 // expression are applicable on the 0th iteration, when the add recurrence 2612 // will be equal to its start value. 2613 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1); 2614 2615 // Build the new addrec. Propagate the NUW and NSW flags if both the 2616 // outer add and the inner addrec are guaranteed to have no overflow. 2617 // Always propagate NW. 2618 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW)); 2619 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags); 2620 2621 // If all of the other operands were loop invariant, we are done. 2622 if (Ops.size() == 1) return NewRec; 2623 2624 // Otherwise, add the folded AddRec by the non-invariant parts. 2625 for (unsigned i = 0;; ++i) 2626 if (Ops[i] == AddRec) { 2627 Ops[i] = NewRec; 2628 break; 2629 } 2630 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2631 } 2632 2633 // Okay, if there weren't any loop invariants to be folded, check to see if 2634 // there are multiple AddRec's with the same loop induction variable being 2635 // added together. If so, we can fold them. 2636 for (unsigned OtherIdx = Idx+1; 2637 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2638 ++OtherIdx) { 2639 // We expect the AddRecExpr's to be sorted in reverse dominance order, 2640 // so that the 1st found AddRecExpr is dominated by all others. 2641 assert(DT.dominates( 2642 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(), 2643 AddRec->getLoop()->getHeader()) && 2644 "AddRecExprs are not sorted in reverse dominance order?"); 2645 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) { 2646 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L> 2647 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(), 2648 AddRec->op_end()); 2649 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2650 ++OtherIdx) { 2651 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2652 if (OtherAddRec->getLoop() == AddRecLoop) { 2653 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); 2654 i != e; ++i) { 2655 if (i >= AddRecOps.size()) { 2656 AddRecOps.append(OtherAddRec->op_begin()+i, 2657 OtherAddRec->op_end()); 2658 break; 2659 } 2660 SmallVector<const SCEV *, 2> TwoOps = { 2661 AddRecOps[i], OtherAddRec->getOperand(i)}; 2662 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1); 2663 } 2664 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 2665 } 2666 } 2667 // Step size has changed, so we cannot guarantee no self-wraparound. 2668 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap); 2669 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2670 } 2671 } 2672 2673 // Otherwise couldn't fold anything into this recurrence. Move onto the 2674 // next one. 2675 } 2676 2677 // Okay, it looks like we really DO need an add expr. Check to see if we 2678 // already have one, otherwise create a new one. 2679 return getOrCreateAddExpr(Ops, Flags); 2680 } 2681 2682 const SCEV * 2683 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops, 2684 SCEV::NoWrapFlags Flags) { 2685 FoldingSetNodeID ID; 2686 ID.AddInteger(scAddExpr); 2687 for (const SCEV *Op : Ops) 2688 ID.AddPointer(Op); 2689 void *IP = nullptr; 2690 SCEVAddExpr *S = 2691 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2692 if (!S) { 2693 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2694 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2695 S = new (SCEVAllocator) 2696 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size()); 2697 UniqueSCEVs.InsertNode(S, IP); 2698 addToLoopUseLists(S); 2699 } 2700 S->setNoWrapFlags(Flags); 2701 return S; 2702 } 2703 2704 const SCEV * 2705 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops, 2706 const Loop *L, SCEV::NoWrapFlags Flags) { 2707 FoldingSetNodeID ID; 2708 ID.AddInteger(scAddRecExpr); 2709 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2710 ID.AddPointer(Ops[i]); 2711 ID.AddPointer(L); 2712 void *IP = nullptr; 2713 SCEVAddRecExpr *S = 2714 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2715 if (!S) { 2716 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2717 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2718 S = new (SCEVAllocator) 2719 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L); 2720 UniqueSCEVs.InsertNode(S, IP); 2721 addToLoopUseLists(S); 2722 } 2723 S->setNoWrapFlags(Flags); 2724 return S; 2725 } 2726 2727 const SCEV * 2728 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops, 2729 SCEV::NoWrapFlags Flags) { 2730 FoldingSetNodeID ID; 2731 ID.AddInteger(scMulExpr); 2732 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2733 ID.AddPointer(Ops[i]); 2734 void *IP = nullptr; 2735 SCEVMulExpr *S = 2736 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP)); 2737 if (!S) { 2738 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 2739 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 2740 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator), 2741 O, Ops.size()); 2742 UniqueSCEVs.InsertNode(S, IP); 2743 addToLoopUseLists(S); 2744 } 2745 S->setNoWrapFlags(Flags); 2746 return S; 2747 } 2748 2749 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) { 2750 uint64_t k = i*j; 2751 if (j > 1 && k / j != i) Overflow = true; 2752 return k; 2753 } 2754 2755 /// Compute the result of "n choose k", the binomial coefficient. If an 2756 /// intermediate computation overflows, Overflow will be set and the return will 2757 /// be garbage. Overflow is not cleared on absence of overflow. 2758 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) { 2759 // We use the multiplicative formula: 2760 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 . 2761 // At each iteration, we take the n-th term of the numeral and divide by the 2762 // (k-n)th term of the denominator. This division will always produce an 2763 // integral result, and helps reduce the chance of overflow in the 2764 // intermediate computations. However, we can still overflow even when the 2765 // final result would fit. 2766 2767 if (n == 0 || n == k) return 1; 2768 if (k > n) return 0; 2769 2770 if (k > n/2) 2771 k = n-k; 2772 2773 uint64_t r = 1; 2774 for (uint64_t i = 1; i <= k; ++i) { 2775 r = umul_ov(r, n-(i-1), Overflow); 2776 r /= i; 2777 } 2778 return r; 2779 } 2780 2781 /// Determine if any of the operands in this SCEV are a constant or if 2782 /// any of the add or multiply expressions in this SCEV contain a constant. 2783 static bool containsConstantInAddMulChain(const SCEV *StartExpr) { 2784 struct FindConstantInAddMulChain { 2785 bool FoundConstant = false; 2786 2787 bool follow(const SCEV *S) { 2788 FoundConstant |= isa<SCEVConstant>(S); 2789 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S); 2790 } 2791 2792 bool isDone() const { 2793 return FoundConstant; 2794 } 2795 }; 2796 2797 FindConstantInAddMulChain F; 2798 SCEVTraversal<FindConstantInAddMulChain> ST(F); 2799 ST.visitAll(StartExpr); 2800 return F.FoundConstant; 2801 } 2802 2803 /// Get a canonical multiply expression, or something simpler if possible. 2804 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 2805 SCEV::NoWrapFlags Flags, 2806 unsigned Depth) { 2807 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) && 2808 "only nuw or nsw allowed"); 2809 assert(!Ops.empty() && "Cannot get empty mul!"); 2810 if (Ops.size() == 1) return Ops[0]; 2811 #ifndef NDEBUG 2812 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 2813 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 2814 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 2815 "SCEVMulExpr operand types don't match!"); 2816 #endif 2817 2818 // Sort by complexity, this groups all similar expression types together. 2819 GroupByComplexity(Ops, &LI, DT); 2820 2821 // If there are any constants, fold them together. 2822 unsigned Idx = 0; 2823 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2824 ++Idx; 2825 assert(Idx < Ops.size()); 2826 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 2827 // We found two constants, fold them together! 2828 Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt()); 2829 if (Ops.size() == 2) return Ops[0]; 2830 Ops.erase(Ops.begin()+1); // Erase the folded element 2831 LHSC = cast<SCEVConstant>(Ops[0]); 2832 } 2833 2834 // If we have a multiply of zero, it will always be zero. 2835 if (LHSC->getValue()->isZero()) 2836 return LHSC; 2837 2838 // If we are left with a constant one being multiplied, strip it off. 2839 if (LHSC->getValue()->isOne()) { 2840 Ops.erase(Ops.begin()); 2841 --Idx; 2842 } 2843 2844 if (Ops.size() == 1) 2845 return Ops[0]; 2846 } 2847 2848 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags); 2849 2850 // Limit recursion calls depth. 2851 if (Depth > MaxArithDepth || hasHugeExpression(Ops)) 2852 return getOrCreateMulExpr(Ops, Flags); 2853 2854 if (SCEV *S = std::get<0>(findExistingSCEVInCache(scMulExpr, Ops))) { 2855 static_cast<SCEVMulExpr *>(S)->setNoWrapFlags(Flags); 2856 return S; 2857 } 2858 2859 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 2860 if (Ops.size() == 2) { 2861 // C1*(C2+V) -> C1*C2 + C1*V 2862 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) 2863 // If any of Add's ops are Adds or Muls with a constant, apply this 2864 // transformation as well. 2865 // 2866 // TODO: There are some cases where this transformation is not 2867 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of 2868 // this transformation should be narrowed down. 2869 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) 2870 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0), 2871 SCEV::FlagAnyWrap, Depth + 1), 2872 getMulExpr(LHSC, Add->getOperand(1), 2873 SCEV::FlagAnyWrap, Depth + 1), 2874 SCEV::FlagAnyWrap, Depth + 1); 2875 2876 if (Ops[0]->isAllOnesValue()) { 2877 // If we have a mul by -1 of an add, try distributing the -1 among the 2878 // add operands. 2879 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) { 2880 SmallVector<const SCEV *, 4> NewOps; 2881 bool AnyFolded = false; 2882 for (const SCEV *AddOp : Add->operands()) { 2883 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap, 2884 Depth + 1); 2885 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true; 2886 NewOps.push_back(Mul); 2887 } 2888 if (AnyFolded) 2889 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1); 2890 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) { 2891 // Negation preserves a recurrence's no self-wrap property. 2892 SmallVector<const SCEV *, 4> Operands; 2893 for (const SCEV *AddRecOp : AddRec->operands()) 2894 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap, 2895 Depth + 1)); 2896 2897 return getAddRecExpr(Operands, AddRec->getLoop(), 2898 AddRec->getNoWrapFlags(SCEV::FlagNW)); 2899 } 2900 } 2901 } 2902 } 2903 2904 // Skip over the add expression until we get to a multiply. 2905 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr) 2906 ++Idx; 2907 2908 // If there are mul operands inline them all into this expression. 2909 if (Idx < Ops.size()) { 2910 bool DeletedMul = false; 2911 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) { 2912 if (Ops.size() > MulOpsInlineThreshold) 2913 break; 2914 // If we have an mul, expand the mul operands onto the end of the 2915 // operands list. 2916 Ops.erase(Ops.begin()+Idx); 2917 Ops.append(Mul->op_begin(), Mul->op_end()); 2918 DeletedMul = true; 2919 } 2920 2921 // If we deleted at least one mul, we added operands to the end of the 2922 // list, and they are not necessarily sorted. Recurse to resort and 2923 // resimplify any operands we just acquired. 2924 if (DeletedMul) 2925 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2926 } 2927 2928 // If there are any add recurrences in the operands list, see if any other 2929 // added values are loop invariant. If so, we can fold them into the 2930 // recurrence. 2931 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr) 2932 ++Idx; 2933 2934 // Scan over all recurrences, trying to fold loop invariants into them. 2935 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) { 2936 // Scan all of the other operands to this mul and add them to the vector 2937 // if they are loop invariant w.r.t. the recurrence. 2938 SmallVector<const SCEV *, 8> LIOps; 2939 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]); 2940 const Loop *AddRecLoop = AddRec->getLoop(); 2941 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2942 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) { 2943 LIOps.push_back(Ops[i]); 2944 Ops.erase(Ops.begin()+i); 2945 --i; --e; 2946 } 2947 2948 // If we found some loop invariants, fold them into the recurrence. 2949 if (!LIOps.empty()) { 2950 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step} 2951 SmallVector<const SCEV *, 4> NewOps; 2952 NewOps.reserve(AddRec->getNumOperands()); 2953 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1); 2954 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) 2955 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i), 2956 SCEV::FlagAnyWrap, Depth + 1)); 2957 2958 // Build the new addrec. Propagate the NUW and NSW flags if both the 2959 // outer mul and the inner addrec are guaranteed to have no overflow. 2960 // 2961 // No self-wrap cannot be guaranteed after changing the step size, but 2962 // will be inferred if either NUW or NSW is true. 2963 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW)); 2964 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags); 2965 2966 // If all of the other operands were loop invariant, we are done. 2967 if (Ops.size() == 1) return NewRec; 2968 2969 // Otherwise, multiply the folded AddRec by the non-invariant parts. 2970 for (unsigned i = 0;; ++i) 2971 if (Ops[i] == AddRec) { 2972 Ops[i] = NewRec; 2973 break; 2974 } 2975 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 2976 } 2977 2978 // Okay, if there weren't any loop invariants to be folded, check to see 2979 // if there are multiple AddRec's with the same loop induction variable 2980 // being multiplied together. If so, we can fold them. 2981 2982 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L> 2983 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [ 2984 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z 2985 // ]]],+,...up to x=2n}. 2986 // Note that the arguments to choose() are always integers with values 2987 // known at compile time, never SCEV objects. 2988 // 2989 // The implementation avoids pointless extra computations when the two 2990 // addrec's are of different length (mathematically, it's equivalent to 2991 // an infinite stream of zeros on the right). 2992 bool OpsModified = false; 2993 for (unsigned OtherIdx = Idx+1; 2994 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]); 2995 ++OtherIdx) { 2996 const SCEVAddRecExpr *OtherAddRec = 2997 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]); 2998 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop) 2999 continue; 3000 3001 // Limit max number of arguments to avoid creation of unreasonably big 3002 // SCEVAddRecs with very complex operands. 3003 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 > 3004 MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec})) 3005 continue; 3006 3007 bool Overflow = false; 3008 Type *Ty = AddRec->getType(); 3009 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64; 3010 SmallVector<const SCEV*, 7> AddRecOps; 3011 for (int x = 0, xe = AddRec->getNumOperands() + 3012 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) { 3013 SmallVector <const SCEV *, 7> SumOps; 3014 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) { 3015 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow); 3016 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1), 3017 ze = std::min(x+1, (int)OtherAddRec->getNumOperands()); 3018 z < ze && !Overflow; ++z) { 3019 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow); 3020 uint64_t Coeff; 3021 if (LargerThan64Bits) 3022 Coeff = umul_ov(Coeff1, Coeff2, Overflow); 3023 else 3024 Coeff = Coeff1*Coeff2; 3025 const SCEV *CoeffTerm = getConstant(Ty, Coeff); 3026 const SCEV *Term1 = AddRec->getOperand(y-z); 3027 const SCEV *Term2 = OtherAddRec->getOperand(z); 3028 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2, 3029 SCEV::FlagAnyWrap, Depth + 1)); 3030 } 3031 } 3032 if (SumOps.empty()) 3033 SumOps.push_back(getZero(Ty)); 3034 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1)); 3035 } 3036 if (!Overflow) { 3037 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop, 3038 SCEV::FlagAnyWrap); 3039 if (Ops.size() == 2) return NewAddRec; 3040 Ops[Idx] = NewAddRec; 3041 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx; 3042 OpsModified = true; 3043 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec); 3044 if (!AddRec) 3045 break; 3046 } 3047 } 3048 if (OpsModified) 3049 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1); 3050 3051 // Otherwise couldn't fold anything into this recurrence. Move onto the 3052 // next one. 3053 } 3054 3055 // Okay, it looks like we really DO need an mul expr. Check to see if we 3056 // already have one, otherwise create a new one. 3057 return getOrCreateMulExpr(Ops, Flags); 3058 } 3059 3060 /// Represents an unsigned remainder expression based on unsigned division. 3061 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS, 3062 const SCEV *RHS) { 3063 assert(getEffectiveSCEVType(LHS->getType()) == 3064 getEffectiveSCEVType(RHS->getType()) && 3065 "SCEVURemExpr operand types don't match!"); 3066 3067 // Short-circuit easy cases 3068 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3069 // If constant is one, the result is trivial 3070 if (RHSC->getValue()->isOne()) 3071 return getZero(LHS->getType()); // X urem 1 --> 0 3072 3073 // If constant is a power of two, fold into a zext(trunc(LHS)). 3074 if (RHSC->getAPInt().isPowerOf2()) { 3075 Type *FullTy = LHS->getType(); 3076 Type *TruncTy = 3077 IntegerType::get(getContext(), RHSC->getAPInt().logBase2()); 3078 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy); 3079 } 3080 } 3081 3082 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y) 3083 const SCEV *UDiv = getUDivExpr(LHS, RHS); 3084 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW); 3085 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW); 3086 } 3087 3088 /// Get a canonical unsigned division expression, or something simpler if 3089 /// possible. 3090 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS, 3091 const SCEV *RHS) { 3092 assert(getEffectiveSCEVType(LHS->getType()) == 3093 getEffectiveSCEVType(RHS->getType()) && 3094 "SCEVUDivExpr operand types don't match!"); 3095 3096 FoldingSetNodeID ID; 3097 ID.AddInteger(scUDivExpr); 3098 ID.AddPointer(LHS); 3099 ID.AddPointer(RHS); 3100 void *IP = nullptr; 3101 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3102 return S; 3103 3104 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 3105 if (RHSC->getValue()->isOne()) 3106 return LHS; // X udiv 1 --> x 3107 // If the denominator is zero, the result of the udiv is undefined. Don't 3108 // try to analyze it, because the resolution chosen here may differ from 3109 // the resolution chosen in other parts of the compiler. 3110 if (!RHSC->getValue()->isZero()) { 3111 // Determine if the division can be folded into the operands of 3112 // its operands. 3113 // TODO: Generalize this to non-constants by using known-bits information. 3114 Type *Ty = LHS->getType(); 3115 unsigned LZ = RHSC->getAPInt().countLeadingZeros(); 3116 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1; 3117 // For non-power-of-two values, effectively round the value up to the 3118 // nearest power of two. 3119 if (!RHSC->getAPInt().isPowerOf2()) 3120 ++MaxShiftAmt; 3121 IntegerType *ExtTy = 3122 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt); 3123 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) 3124 if (const SCEVConstant *Step = 3125 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) { 3126 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded. 3127 const APInt &StepInt = Step->getAPInt(); 3128 const APInt &DivInt = RHSC->getAPInt(); 3129 if (!StepInt.urem(DivInt) && 3130 getZeroExtendExpr(AR, ExtTy) == 3131 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3132 getZeroExtendExpr(Step, ExtTy), 3133 AR->getLoop(), SCEV::FlagAnyWrap)) { 3134 SmallVector<const SCEV *, 4> Operands; 3135 for (const SCEV *Op : AR->operands()) 3136 Operands.push_back(getUDivExpr(Op, RHS)); 3137 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW); 3138 } 3139 /// Get a canonical UDivExpr for a recurrence. 3140 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0. 3141 // We can currently only fold X%N if X is constant. 3142 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart()); 3143 if (StartC && !DivInt.urem(StepInt) && 3144 getZeroExtendExpr(AR, ExtTy) == 3145 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy), 3146 getZeroExtendExpr(Step, ExtTy), 3147 AR->getLoop(), SCEV::FlagAnyWrap)) { 3148 const APInt &StartInt = StartC->getAPInt(); 3149 const APInt &StartRem = StartInt.urem(StepInt); 3150 if (StartRem != 0) { 3151 const SCEV *NewLHS = 3152 getAddRecExpr(getConstant(StartInt - StartRem), Step, 3153 AR->getLoop(), SCEV::FlagNW); 3154 if (LHS != NewLHS) { 3155 LHS = NewLHS; 3156 3157 // Reset the ID to include the new LHS, and check if it is 3158 // already cached. 3159 ID.clear(); 3160 ID.AddInteger(scUDivExpr); 3161 ID.AddPointer(LHS); 3162 ID.AddPointer(RHS); 3163 IP = nullptr; 3164 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) 3165 return S; 3166 } 3167 } 3168 } 3169 } 3170 // (A*B)/C --> A*(B/C) if safe and B/C can be folded. 3171 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) { 3172 SmallVector<const SCEV *, 4> Operands; 3173 for (const SCEV *Op : M->operands()) 3174 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3175 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands)) 3176 // Find an operand that's safely divisible. 3177 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) { 3178 const SCEV *Op = M->getOperand(i); 3179 const SCEV *Div = getUDivExpr(Op, RHSC); 3180 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) { 3181 Operands = SmallVector<const SCEV *, 4>(M->op_begin(), 3182 M->op_end()); 3183 Operands[i] = Div; 3184 return getMulExpr(Operands); 3185 } 3186 } 3187 } 3188 3189 // (A/B)/C --> A/(B*C) if safe and B*C can be folded. 3190 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) { 3191 if (auto *DivisorConstant = 3192 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) { 3193 bool Overflow = false; 3194 APInt NewRHS = 3195 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow); 3196 if (Overflow) { 3197 return getConstant(RHSC->getType(), 0, false); 3198 } 3199 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS)); 3200 } 3201 } 3202 3203 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded. 3204 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) { 3205 SmallVector<const SCEV *, 4> Operands; 3206 for (const SCEV *Op : A->operands()) 3207 Operands.push_back(getZeroExtendExpr(Op, ExtTy)); 3208 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) { 3209 Operands.clear(); 3210 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) { 3211 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS); 3212 if (isa<SCEVUDivExpr>(Op) || 3213 getMulExpr(Op, RHS) != A->getOperand(i)) 3214 break; 3215 Operands.push_back(Op); 3216 } 3217 if (Operands.size() == A->getNumOperands()) 3218 return getAddExpr(Operands); 3219 } 3220 } 3221 3222 // Fold if both operands are constant. 3223 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 3224 Constant *LHSCV = LHSC->getValue(); 3225 Constant *RHSCV = RHSC->getValue(); 3226 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV, 3227 RHSCV))); 3228 } 3229 } 3230 } 3231 3232 // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs 3233 // changes). Make sure we get a new one. 3234 IP = nullptr; 3235 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S; 3236 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator), 3237 LHS, RHS); 3238 UniqueSCEVs.InsertNode(S, IP); 3239 addToLoopUseLists(S); 3240 return S; 3241 } 3242 3243 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) { 3244 APInt A = C1->getAPInt().abs(); 3245 APInt B = C2->getAPInt().abs(); 3246 uint32_t ABW = A.getBitWidth(); 3247 uint32_t BBW = B.getBitWidth(); 3248 3249 if (ABW > BBW) 3250 B = B.zext(ABW); 3251 else if (ABW < BBW) 3252 A = A.zext(BBW); 3253 3254 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B)); 3255 } 3256 3257 /// Get a canonical unsigned division expression, or something simpler if 3258 /// possible. There is no representation for an exact udiv in SCEV IR, but we 3259 /// can attempt to remove factors from the LHS and RHS. We can't do this when 3260 /// it's not exact because the udiv may be clearing bits. 3261 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS, 3262 const SCEV *RHS) { 3263 // TODO: we could try to find factors in all sorts of things, but for now we 3264 // just deal with u/exact (multiply, constant). See SCEVDivision towards the 3265 // end of this file for inspiration. 3266 3267 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS); 3268 if (!Mul || !Mul->hasNoUnsignedWrap()) 3269 return getUDivExpr(LHS, RHS); 3270 3271 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) { 3272 // If the mulexpr multiplies by a constant, then that constant must be the 3273 // first element of the mulexpr. 3274 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) { 3275 if (LHSCst == RHSCst) { 3276 SmallVector<const SCEV *, 2> Operands; 3277 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3278 return getMulExpr(Operands); 3279 } 3280 3281 // We can't just assume that LHSCst divides RHSCst cleanly, it could be 3282 // that there's a factor provided by one of the other terms. We need to 3283 // check. 3284 APInt Factor = gcd(LHSCst, RHSCst); 3285 if (!Factor.isIntN(1)) { 3286 LHSCst = 3287 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor))); 3288 RHSCst = 3289 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor))); 3290 SmallVector<const SCEV *, 2> Operands; 3291 Operands.push_back(LHSCst); 3292 Operands.append(Mul->op_begin() + 1, Mul->op_end()); 3293 LHS = getMulExpr(Operands); 3294 RHS = RHSCst; 3295 Mul = dyn_cast<SCEVMulExpr>(LHS); 3296 if (!Mul) 3297 return getUDivExactExpr(LHS, RHS); 3298 } 3299 } 3300 } 3301 3302 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) { 3303 if (Mul->getOperand(i) == RHS) { 3304 SmallVector<const SCEV *, 2> Operands; 3305 Operands.append(Mul->op_begin(), Mul->op_begin() + i); 3306 Operands.append(Mul->op_begin() + i + 1, Mul->op_end()); 3307 return getMulExpr(Operands); 3308 } 3309 } 3310 3311 return getUDivExpr(LHS, RHS); 3312 } 3313 3314 /// Get an add recurrence expression for the specified loop. Simplify the 3315 /// expression as much as possible. 3316 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step, 3317 const Loop *L, 3318 SCEV::NoWrapFlags Flags) { 3319 SmallVector<const SCEV *, 4> Operands; 3320 Operands.push_back(Start); 3321 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step)) 3322 if (StepChrec->getLoop() == L) { 3323 Operands.append(StepChrec->op_begin(), StepChrec->op_end()); 3324 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW)); 3325 } 3326 3327 Operands.push_back(Step); 3328 return getAddRecExpr(Operands, L, Flags); 3329 } 3330 3331 /// Get an add recurrence expression for the specified loop. Simplify the 3332 /// expression as much as possible. 3333 const SCEV * 3334 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 3335 const Loop *L, SCEV::NoWrapFlags Flags) { 3336 if (Operands.size() == 1) return Operands[0]; 3337 #ifndef NDEBUG 3338 Type *ETy = getEffectiveSCEVType(Operands[0]->getType()); 3339 for (unsigned i = 1, e = Operands.size(); i != e; ++i) 3340 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy && 3341 "SCEVAddRecExpr operand types don't match!"); 3342 for (unsigned i = 0, e = Operands.size(); i != e; ++i) 3343 assert(isLoopInvariant(Operands[i], L) && 3344 "SCEVAddRecExpr operand is not loop-invariant!"); 3345 #endif 3346 3347 if (Operands.back()->isZero()) { 3348 Operands.pop_back(); 3349 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X 3350 } 3351 3352 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and 3353 // use that information to infer NUW and NSW flags. However, computing a 3354 // BE count requires calling getAddRecExpr, so we may not yet have a 3355 // meaningful BE count at this point (and if we don't, we'd be stuck 3356 // with a SCEVCouldNotCompute as the cached BE count). 3357 3358 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags); 3359 3360 // Canonicalize nested AddRecs in by nesting them in order of loop depth. 3361 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) { 3362 const Loop *NestedLoop = NestedAR->getLoop(); 3363 if (L->contains(NestedLoop) 3364 ? (L->getLoopDepth() < NestedLoop->getLoopDepth()) 3365 : (!NestedLoop->contains(L) && 3366 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) { 3367 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(), 3368 NestedAR->op_end()); 3369 Operands[0] = NestedAR->getStart(); 3370 // AddRecs require their operands be loop-invariant with respect to their 3371 // loops. Don't perform this transformation if it would break this 3372 // requirement. 3373 bool AllInvariant = all_of( 3374 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); }); 3375 3376 if (AllInvariant) { 3377 // Create a recurrence for the outer loop with the same step size. 3378 // 3379 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the 3380 // inner recurrence has the same property. 3381 SCEV::NoWrapFlags OuterFlags = 3382 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags()); 3383 3384 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags); 3385 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) { 3386 return isLoopInvariant(Op, NestedLoop); 3387 }); 3388 3389 if (AllInvariant) { 3390 // Ok, both add recurrences are valid after the transformation. 3391 // 3392 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if 3393 // the outer recurrence has the same property. 3394 SCEV::NoWrapFlags InnerFlags = 3395 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags); 3396 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags); 3397 } 3398 } 3399 // Reset Operands to its original state. 3400 Operands[0] = NestedAR; 3401 } 3402 } 3403 3404 // Okay, it looks like we really DO need an addrec expr. Check to see if we 3405 // already have one, otherwise create a new one. 3406 return getOrCreateAddRecExpr(Operands, L, Flags); 3407 } 3408 3409 const SCEV * 3410 ScalarEvolution::getGEPExpr(GEPOperator *GEP, 3411 const SmallVectorImpl<const SCEV *> &IndexExprs) { 3412 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand()); 3413 // getSCEV(Base)->getType() has the same address space as Base->getType() 3414 // because SCEV::getType() preserves the address space. 3415 Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType()); 3416 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP 3417 // instruction to its SCEV, because the Instruction may be guarded by control 3418 // flow and the no-overflow bits may not be valid for the expression in any 3419 // context. This can be fixed similarly to how these flags are handled for 3420 // adds. 3421 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW 3422 : SCEV::FlagAnyWrap; 3423 3424 const SCEV *TotalOffset = getZero(IntIdxTy); 3425 Type *CurTy = GEP->getType(); 3426 bool FirstIter = true; 3427 for (const SCEV *IndexExpr : IndexExprs) { 3428 // Compute the (potentially symbolic) offset in bytes for this index. 3429 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 3430 // For a struct, add the member offset. 3431 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue(); 3432 unsigned FieldNo = Index->getZExtValue(); 3433 const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo); 3434 3435 // Add the field offset to the running total offset. 3436 TotalOffset = getAddExpr(TotalOffset, FieldOffset); 3437 3438 // Update CurTy to the type of the field at Index. 3439 CurTy = STy->getTypeAtIndex(Index); 3440 } else { 3441 // Update CurTy to its element type. 3442 if (FirstIter) { 3443 assert(isa<PointerType>(CurTy) && 3444 "The first index of a GEP indexes a pointer"); 3445 CurTy = GEP->getSourceElementType(); 3446 FirstIter = false; 3447 } else { 3448 CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0); 3449 } 3450 // For an array, add the element offset, explicitly scaled. 3451 const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy); 3452 // Getelementptr indices are signed. 3453 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy); 3454 3455 // Multiply the index by the element size to compute the element offset. 3456 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap); 3457 3458 // Add the element offset to the running total offset. 3459 TotalOffset = getAddExpr(TotalOffset, LocalOffset); 3460 } 3461 } 3462 3463 // Add the total offset from all the GEP indices to the base. 3464 return getAddExpr(BaseExpr, TotalOffset, Wrap); 3465 } 3466 3467 std::tuple<SCEV *, FoldingSetNodeID, void *> 3468 ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType, 3469 ArrayRef<const SCEV *> Ops) { 3470 FoldingSetNodeID ID; 3471 void *IP = nullptr; 3472 ID.AddInteger(SCEVType); 3473 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 3474 ID.AddPointer(Ops[i]); 3475 return std::tuple<SCEV *, FoldingSetNodeID, void *>( 3476 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP); 3477 } 3478 3479 const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) { 3480 SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3481 return getSMaxExpr(Op, getNegativeSCEV(Op, Flags)); 3482 } 3483 3484 const SCEV *ScalarEvolution::getSignumExpr(const SCEV *Op) { 3485 Type *Ty = Op->getType(); 3486 return getSMinExpr(getSMaxExpr(Op, getMinusOne(Ty)), getOne(Ty)); 3487 } 3488 3489 const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind, 3490 SmallVectorImpl<const SCEV *> &Ops) { 3491 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!"); 3492 if (Ops.size() == 1) return Ops[0]; 3493 #ifndef NDEBUG 3494 Type *ETy = getEffectiveSCEVType(Ops[0]->getType()); 3495 for (unsigned i = 1, e = Ops.size(); i != e; ++i) 3496 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy && 3497 "Operand types don't match!"); 3498 #endif 3499 3500 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr; 3501 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr; 3502 3503 // Sort by complexity, this groups all similar expression types together. 3504 GroupByComplexity(Ops, &LI, DT); 3505 3506 // Check if we have created the same expression before. 3507 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) { 3508 return S; 3509 } 3510 3511 // If there are any constants, fold them together. 3512 unsigned Idx = 0; 3513 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) { 3514 ++Idx; 3515 assert(Idx < Ops.size()); 3516 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) { 3517 if (Kind == scSMaxExpr) 3518 return APIntOps::smax(LHS, RHS); 3519 else if (Kind == scSMinExpr) 3520 return APIntOps::smin(LHS, RHS); 3521 else if (Kind == scUMaxExpr) 3522 return APIntOps::umax(LHS, RHS); 3523 else if (Kind == scUMinExpr) 3524 return APIntOps::umin(LHS, RHS); 3525 llvm_unreachable("Unknown SCEV min/max opcode"); 3526 }; 3527 3528 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) { 3529 // We found two constants, fold them together! 3530 ConstantInt *Fold = ConstantInt::get( 3531 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt())); 3532 Ops[0] = getConstant(Fold); 3533 Ops.erase(Ops.begin()+1); // Erase the folded element 3534 if (Ops.size() == 1) return Ops[0]; 3535 LHSC = cast<SCEVConstant>(Ops[0]); 3536 } 3537 3538 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned); 3539 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned); 3540 3541 if (IsMax ? IsMinV : IsMaxV) { 3542 // If we are left with a constant minimum(/maximum)-int, strip it off. 3543 Ops.erase(Ops.begin()); 3544 --Idx; 3545 } else if (IsMax ? IsMaxV : IsMinV) { 3546 // If we have a max(/min) with a constant maximum(/minimum)-int, 3547 // it will always be the extremum. 3548 return LHSC; 3549 } 3550 3551 if (Ops.size() == 1) return Ops[0]; 3552 } 3553 3554 // Find the first operation of the same kind 3555 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind) 3556 ++Idx; 3557 3558 // Check to see if one of the operands is of the same kind. If so, expand its 3559 // operands onto our operand list, and recurse to simplify. 3560 if (Idx < Ops.size()) { 3561 bool DeletedAny = false; 3562 while (Ops[Idx]->getSCEVType() == Kind) { 3563 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]); 3564 Ops.erase(Ops.begin()+Idx); 3565 Ops.append(SMME->op_begin(), SMME->op_end()); 3566 DeletedAny = true; 3567 } 3568 3569 if (DeletedAny) 3570 return getMinMaxExpr(Kind, Ops); 3571 } 3572 3573 // Okay, check to see if the same value occurs in the operand list twice. If 3574 // so, delete one. Since we sorted the list, these values are required to 3575 // be adjacent. 3576 llvm::CmpInst::Predicate GEPred = 3577 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 3578 llvm::CmpInst::Predicate LEPred = 3579 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 3580 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred; 3581 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred; 3582 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) { 3583 if (Ops[i] == Ops[i + 1] || 3584 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) { 3585 // X op Y op Y --> X op Y 3586 // X op Y --> X, if we know X, Y are ordered appropriately 3587 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2); 3588 --i; 3589 --e; 3590 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i], 3591 Ops[i + 1])) { 3592 // X op Y --> Y, if we know X, Y are ordered appropriately 3593 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1); 3594 --i; 3595 --e; 3596 } 3597 } 3598 3599 if (Ops.size() == 1) return Ops[0]; 3600 3601 assert(!Ops.empty() && "Reduced smax down to nothing!"); 3602 3603 // Okay, it looks like we really DO need an expr. Check to see if we 3604 // already have one, otherwise create a new one. 3605 const SCEV *ExistingSCEV; 3606 FoldingSetNodeID ID; 3607 void *IP; 3608 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops); 3609 if (ExistingSCEV) 3610 return ExistingSCEV; 3611 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size()); 3612 std::uninitialized_copy(Ops.begin(), Ops.end(), O); 3613 SCEV *S = new (SCEVAllocator) 3614 SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size()); 3615 3616 UniqueSCEVs.InsertNode(S, IP); 3617 addToLoopUseLists(S); 3618 return S; 3619 } 3620 3621 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3622 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3623 return getSMaxExpr(Ops); 3624 } 3625 3626 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3627 return getMinMaxExpr(scSMaxExpr, Ops); 3628 } 3629 3630 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) { 3631 SmallVector<const SCEV *, 2> Ops = {LHS, RHS}; 3632 return getUMaxExpr(Ops); 3633 } 3634 3635 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) { 3636 return getMinMaxExpr(scUMaxExpr, Ops); 3637 } 3638 3639 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS, 3640 const SCEV *RHS) { 3641 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3642 return getSMinExpr(Ops); 3643 } 3644 3645 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3646 return getMinMaxExpr(scSMinExpr, Ops); 3647 } 3648 3649 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, 3650 const SCEV *RHS) { 3651 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 3652 return getUMinExpr(Ops); 3653 } 3654 3655 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) { 3656 return getMinMaxExpr(scUMinExpr, Ops); 3657 } 3658 3659 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) { 3660 if (isa<ScalableVectorType>(AllocTy)) { 3661 Constant *NullPtr = Constant::getNullValue(AllocTy->getPointerTo()); 3662 Constant *One = ConstantInt::get(IntTy, 1); 3663 Constant *GEP = ConstantExpr::getGetElementPtr(AllocTy, NullPtr, One); 3664 // Note that the expression we created is the final expression, we don't 3665 // want to simplify it any further Also, if we call a normal getSCEV(), 3666 // we'll end up in an endless recursion. So just create an SCEVUnknown. 3667 return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy)); 3668 } 3669 // We can bypass creating a target-independent 3670 // constant expression and then folding it back into a ConstantInt. 3671 // This is just a compile-time optimization. 3672 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy)); 3673 } 3674 3675 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy, 3676 StructType *STy, 3677 unsigned FieldNo) { 3678 // We can bypass creating a target-independent 3679 // constant expression and then folding it back into a ConstantInt. 3680 // This is just a compile-time optimization. 3681 return getConstant( 3682 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo)); 3683 } 3684 3685 const SCEV *ScalarEvolution::getUnknown(Value *V) { 3686 // Don't attempt to do anything other than create a SCEVUnknown object 3687 // here. createSCEV only calls getUnknown after checking for all other 3688 // interesting possibilities, and any other code that calls getUnknown 3689 // is doing so in order to hide a value from SCEV canonicalization. 3690 3691 FoldingSetNodeID ID; 3692 ID.AddInteger(scUnknown); 3693 ID.AddPointer(V); 3694 void *IP = nullptr; 3695 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) { 3696 assert(cast<SCEVUnknown>(S)->getValue() == V && 3697 "Stale SCEVUnknown in uniquing map!"); 3698 return S; 3699 } 3700 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this, 3701 FirstUnknown); 3702 FirstUnknown = cast<SCEVUnknown>(S); 3703 UniqueSCEVs.InsertNode(S, IP); 3704 return S; 3705 } 3706 3707 //===----------------------------------------------------------------------===// 3708 // Basic SCEV Analysis and PHI Idiom Recognition Code 3709 // 3710 3711 /// Test if values of the given type are analyzable within the SCEV 3712 /// framework. This primarily includes integer types, and it can optionally 3713 /// include pointer types if the ScalarEvolution class has access to 3714 /// target-specific information. 3715 bool ScalarEvolution::isSCEVable(Type *Ty) const { 3716 // Integers and pointers are always SCEVable. 3717 return Ty->isIntOrPtrTy(); 3718 } 3719 3720 /// Return the size in bits of the specified type, for which isSCEVable must 3721 /// return true. 3722 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const { 3723 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3724 if (Ty->isPointerTy()) 3725 return getDataLayout().getIndexTypeSizeInBits(Ty); 3726 return getDataLayout().getTypeSizeInBits(Ty); 3727 } 3728 3729 /// Return a type with the same bitwidth as the given type and which represents 3730 /// how SCEV will treat the given type, for which isSCEVable must return 3731 /// true. For pointer types, this is the pointer index sized integer type. 3732 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const { 3733 assert(isSCEVable(Ty) && "Type is not SCEVable!"); 3734 3735 if (Ty->isIntegerTy()) 3736 return Ty; 3737 3738 // The only other support type is pointer. 3739 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!"); 3740 return getDataLayout().getIndexType(Ty); 3741 } 3742 3743 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const { 3744 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2; 3745 } 3746 3747 const SCEV *ScalarEvolution::getCouldNotCompute() { 3748 return CouldNotCompute.get(); 3749 } 3750 3751 bool ScalarEvolution::checkValidity(const SCEV *S) const { 3752 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) { 3753 auto *SU = dyn_cast<SCEVUnknown>(S); 3754 return SU && SU->getValue() == nullptr; 3755 }); 3756 3757 return !ContainsNulls; 3758 } 3759 3760 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) { 3761 HasRecMapType::iterator I = HasRecMap.find(S); 3762 if (I != HasRecMap.end()) 3763 return I->second; 3764 3765 bool FoundAddRec = 3766 SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }); 3767 HasRecMap.insert({S, FoundAddRec}); 3768 return FoundAddRec; 3769 } 3770 3771 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}. 3772 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an 3773 /// offset I, then return {S', I}, else return {\p S, nullptr}. 3774 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) { 3775 const auto *Add = dyn_cast<SCEVAddExpr>(S); 3776 if (!Add) 3777 return {S, nullptr}; 3778 3779 if (Add->getNumOperands() != 2) 3780 return {S, nullptr}; 3781 3782 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0)); 3783 if (!ConstOp) 3784 return {S, nullptr}; 3785 3786 return {Add->getOperand(1), ConstOp->getValue()}; 3787 } 3788 3789 /// Return the ValueOffsetPair set for \p S. \p S can be represented 3790 /// by the value and offset from any ValueOffsetPair in the set. 3791 SetVector<ScalarEvolution::ValueOffsetPair> * 3792 ScalarEvolution::getSCEVValues(const SCEV *S) { 3793 ExprValueMapType::iterator SI = ExprValueMap.find_as(S); 3794 if (SI == ExprValueMap.end()) 3795 return nullptr; 3796 #ifndef NDEBUG 3797 if (VerifySCEVMap) { 3798 // Check there is no dangling Value in the set returned. 3799 for (const auto &VE : SI->second) 3800 assert(ValueExprMap.count(VE.first)); 3801 } 3802 #endif 3803 return &SI->second; 3804 } 3805 3806 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V) 3807 /// cannot be used separately. eraseValueFromMap should be used to remove 3808 /// V from ValueExprMap and ExprValueMap at the same time. 3809 void ScalarEvolution::eraseValueFromMap(Value *V) { 3810 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3811 if (I != ValueExprMap.end()) { 3812 const SCEV *S = I->second; 3813 // Remove {V, 0} from the set of ExprValueMap[S] 3814 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S)) 3815 SV->remove({V, nullptr}); 3816 3817 // Remove {V, Offset} from the set of ExprValueMap[Stripped] 3818 const SCEV *Stripped; 3819 ConstantInt *Offset; 3820 std::tie(Stripped, Offset) = splitAddExpr(S); 3821 if (Offset != nullptr) { 3822 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped)) 3823 SV->remove({V, Offset}); 3824 } 3825 ValueExprMap.erase(V); 3826 } 3827 } 3828 3829 /// Check whether value has nuw/nsw/exact set but SCEV does not. 3830 /// TODO: In reality it is better to check the poison recursively 3831 /// but this is better than nothing. 3832 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) { 3833 if (auto *I = dyn_cast<Instruction>(V)) { 3834 if (isa<OverflowingBinaryOperator>(I)) { 3835 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) { 3836 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap()) 3837 return true; 3838 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap()) 3839 return true; 3840 } 3841 } else if (isa<PossiblyExactOperator>(I) && I->isExact()) 3842 return true; 3843 } 3844 return false; 3845 } 3846 3847 /// Return an existing SCEV if it exists, otherwise analyze the expression and 3848 /// create a new one. 3849 const SCEV *ScalarEvolution::getSCEV(Value *V) { 3850 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3851 3852 const SCEV *S = getExistingSCEV(V); 3853 if (S == nullptr) { 3854 S = createSCEV(V); 3855 // During PHI resolution, it is possible to create two SCEVs for the same 3856 // V, so it is needed to double check whether V->S is inserted into 3857 // ValueExprMap before insert S->{V, 0} into ExprValueMap. 3858 std::pair<ValueExprMapType::iterator, bool> Pair = 3859 ValueExprMap.insert({SCEVCallbackVH(V, this), S}); 3860 if (Pair.second && !SCEVLostPoisonFlags(S, V)) { 3861 ExprValueMap[S].insert({V, nullptr}); 3862 3863 // If S == Stripped + Offset, add Stripped -> {V, Offset} into 3864 // ExprValueMap. 3865 const SCEV *Stripped = S; 3866 ConstantInt *Offset = nullptr; 3867 std::tie(Stripped, Offset) = splitAddExpr(S); 3868 // If stripped is SCEVUnknown, don't bother to save 3869 // Stripped -> {V, offset}. It doesn't simplify and sometimes even 3870 // increase the complexity of the expansion code. 3871 // If V is GetElementPtrInst, don't save Stripped -> {V, offset} 3872 // because it may generate add/sub instead of GEP in SCEV expansion. 3873 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) && 3874 !isa<GetElementPtrInst>(V)) 3875 ExprValueMap[Stripped].insert({V, Offset}); 3876 } 3877 } 3878 return S; 3879 } 3880 3881 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) { 3882 assert(isSCEVable(V->getType()) && "Value is not SCEVable!"); 3883 3884 ValueExprMapType::iterator I = ValueExprMap.find_as(V); 3885 if (I != ValueExprMap.end()) { 3886 const SCEV *S = I->second; 3887 if (checkValidity(S)) 3888 return S; 3889 eraseValueFromMap(V); 3890 forgetMemoizedResults(S); 3891 } 3892 return nullptr; 3893 } 3894 3895 /// Return a SCEV corresponding to -V = -1*V 3896 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V, 3897 SCEV::NoWrapFlags Flags) { 3898 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3899 return getConstant( 3900 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue()))); 3901 3902 Type *Ty = V->getType(); 3903 Ty = getEffectiveSCEVType(Ty); 3904 return getMulExpr(V, getMinusOne(Ty), Flags); 3905 } 3906 3907 /// If Expr computes ~A, return A else return nullptr 3908 static const SCEV *MatchNotExpr(const SCEV *Expr) { 3909 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr); 3910 if (!Add || Add->getNumOperands() != 2 || 3911 !Add->getOperand(0)->isAllOnesValue()) 3912 return nullptr; 3913 3914 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1)); 3915 if (!AddRHS || AddRHS->getNumOperands() != 2 || 3916 !AddRHS->getOperand(0)->isAllOnesValue()) 3917 return nullptr; 3918 3919 return AddRHS->getOperand(1); 3920 } 3921 3922 /// Return a SCEV corresponding to ~V = -1-V 3923 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) { 3924 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V)) 3925 return getConstant( 3926 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue()))); 3927 3928 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y) 3929 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) { 3930 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) { 3931 SmallVector<const SCEV *, 2> MatchedOperands; 3932 for (const SCEV *Operand : MME->operands()) { 3933 const SCEV *Matched = MatchNotExpr(Operand); 3934 if (!Matched) 3935 return (const SCEV *)nullptr; 3936 MatchedOperands.push_back(Matched); 3937 } 3938 return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()), 3939 MatchedOperands); 3940 }; 3941 if (const SCEV *Replaced = MatchMinMaxNegation(MME)) 3942 return Replaced; 3943 } 3944 3945 Type *Ty = V->getType(); 3946 Ty = getEffectiveSCEVType(Ty); 3947 return getMinusSCEV(getMinusOne(Ty), V); 3948 } 3949 3950 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 3951 SCEV::NoWrapFlags Flags, 3952 unsigned Depth) { 3953 // Fast path: X - X --> 0. 3954 if (LHS == RHS) 3955 return getZero(LHS->getType()); 3956 3957 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation 3958 // makes it so that we cannot make much use of NUW. 3959 auto AddFlags = SCEV::FlagAnyWrap; 3960 const bool RHSIsNotMinSigned = 3961 !getSignedRangeMin(RHS).isMinSignedValue(); 3962 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) { 3963 // Let M be the minimum representable signed value. Then (-1)*RHS 3964 // signed-wraps if and only if RHS is M. That can happen even for 3965 // a NSW subtraction because e.g. (-1)*M signed-wraps even though 3966 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS + 3967 // (-1)*RHS, we need to prove that RHS != M. 3968 // 3969 // If LHS is non-negative and we know that LHS - RHS does not 3970 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap 3971 // either by proving that RHS > M or that LHS >= 0. 3972 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) { 3973 AddFlags = SCEV::FlagNSW; 3974 } 3975 } 3976 3977 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS - 3978 // RHS is NSW and LHS >= 0. 3979 // 3980 // The difficulty here is that the NSW flag may have been proven 3981 // relative to a loop that is to be found in a recurrence in LHS and 3982 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a 3983 // larger scope than intended. 3984 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap; 3985 3986 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth); 3987 } 3988 3989 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty, 3990 unsigned Depth) { 3991 Type *SrcTy = V->getType(); 3992 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 3993 "Cannot truncate or zero extend with non-integer arguments!"); 3994 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 3995 return V; // No conversion 3996 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 3997 return getTruncateExpr(V, Ty, Depth); 3998 return getZeroExtendExpr(V, Ty, Depth); 3999 } 4000 4001 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty, 4002 unsigned Depth) { 4003 Type *SrcTy = V->getType(); 4004 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4005 "Cannot truncate or zero extend with non-integer arguments!"); 4006 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4007 return V; // No conversion 4008 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty)) 4009 return getTruncateExpr(V, Ty, Depth); 4010 return getSignExtendExpr(V, Ty, Depth); 4011 } 4012 4013 const SCEV * 4014 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) { 4015 Type *SrcTy = V->getType(); 4016 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4017 "Cannot noop or zero extend with non-integer arguments!"); 4018 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4019 "getNoopOrZeroExtend cannot truncate!"); 4020 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4021 return V; // No conversion 4022 return getZeroExtendExpr(V, Ty); 4023 } 4024 4025 const SCEV * 4026 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) { 4027 Type *SrcTy = V->getType(); 4028 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4029 "Cannot noop or sign extend with non-integer arguments!"); 4030 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4031 "getNoopOrSignExtend cannot truncate!"); 4032 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4033 return V; // No conversion 4034 return getSignExtendExpr(V, Ty); 4035 } 4036 4037 const SCEV * 4038 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) { 4039 Type *SrcTy = V->getType(); 4040 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4041 "Cannot noop or any extend with non-integer arguments!"); 4042 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) && 4043 "getNoopOrAnyExtend cannot truncate!"); 4044 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4045 return V; // No conversion 4046 return getAnyExtendExpr(V, Ty); 4047 } 4048 4049 const SCEV * 4050 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) { 4051 Type *SrcTy = V->getType(); 4052 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() && 4053 "Cannot truncate or noop with non-integer arguments!"); 4054 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) && 4055 "getTruncateOrNoop cannot extend!"); 4056 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty)) 4057 return V; // No conversion 4058 return getTruncateExpr(V, Ty); 4059 } 4060 4061 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS, 4062 const SCEV *RHS) { 4063 const SCEV *PromotedLHS = LHS; 4064 const SCEV *PromotedRHS = RHS; 4065 4066 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType())) 4067 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType()); 4068 else 4069 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType()); 4070 4071 return getUMaxExpr(PromotedLHS, PromotedRHS); 4072 } 4073 4074 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS, 4075 const SCEV *RHS) { 4076 SmallVector<const SCEV *, 2> Ops = { LHS, RHS }; 4077 return getUMinFromMismatchedTypes(Ops); 4078 } 4079 4080 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes( 4081 SmallVectorImpl<const SCEV *> &Ops) { 4082 assert(!Ops.empty() && "At least one operand must be!"); 4083 // Trivial case. 4084 if (Ops.size() == 1) 4085 return Ops[0]; 4086 4087 // Find the max type first. 4088 Type *MaxType = nullptr; 4089 for (auto *S : Ops) 4090 if (MaxType) 4091 MaxType = getWiderType(MaxType, S->getType()); 4092 else 4093 MaxType = S->getType(); 4094 assert(MaxType && "Failed to find maximum type!"); 4095 4096 // Extend all ops to max type. 4097 SmallVector<const SCEV *, 2> PromotedOps; 4098 for (auto *S : Ops) 4099 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType)); 4100 4101 // Generate umin. 4102 return getUMinExpr(PromotedOps); 4103 } 4104 4105 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) { 4106 // A pointer operand may evaluate to a nonpointer expression, such as null. 4107 if (!V->getType()->isPointerTy()) 4108 return V; 4109 4110 while (true) { 4111 if (const SCEVIntegralCastExpr *Cast = dyn_cast<SCEVIntegralCastExpr>(V)) { 4112 V = Cast->getOperand(); 4113 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) { 4114 const SCEV *PtrOp = nullptr; 4115 for (const SCEV *NAryOp : NAry->operands()) { 4116 if (NAryOp->getType()->isPointerTy()) { 4117 // Cannot find the base of an expression with multiple pointer ops. 4118 if (PtrOp) 4119 return V; 4120 PtrOp = NAryOp; 4121 } 4122 } 4123 if (!PtrOp) // All operands were non-pointer. 4124 return V; 4125 V = PtrOp; 4126 } else // Not something we can look further into. 4127 return V; 4128 } 4129 } 4130 4131 /// Push users of the given Instruction onto the given Worklist. 4132 static void 4133 PushDefUseChildren(Instruction *I, 4134 SmallVectorImpl<Instruction *> &Worklist) { 4135 // Push the def-use children onto the Worklist stack. 4136 for (User *U : I->users()) 4137 Worklist.push_back(cast<Instruction>(U)); 4138 } 4139 4140 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) { 4141 SmallVector<Instruction *, 16> Worklist; 4142 PushDefUseChildren(PN, Worklist); 4143 4144 SmallPtrSet<Instruction *, 8> Visited; 4145 Visited.insert(PN); 4146 while (!Worklist.empty()) { 4147 Instruction *I = Worklist.pop_back_val(); 4148 if (!Visited.insert(I).second) 4149 continue; 4150 4151 auto It = ValueExprMap.find_as(static_cast<Value *>(I)); 4152 if (It != ValueExprMap.end()) { 4153 const SCEV *Old = It->second; 4154 4155 // Short-circuit the def-use traversal if the symbolic name 4156 // ceases to appear in expressions. 4157 if (Old != SymName && !hasOperand(Old, SymName)) 4158 continue; 4159 4160 // SCEVUnknown for a PHI either means that it has an unrecognized 4161 // structure, it's a PHI that's in the progress of being computed 4162 // by createNodeForPHI, or it's a single-value PHI. In the first case, 4163 // additional loop trip count information isn't going to change anything. 4164 // In the second case, createNodeForPHI will perform the necessary 4165 // updates on its own when it gets to that point. In the third, we do 4166 // want to forget the SCEVUnknown. 4167 if (!isa<PHINode>(I) || 4168 !isa<SCEVUnknown>(Old) || 4169 (I != PN && Old == SymName)) { 4170 eraseValueFromMap(It->first); 4171 forgetMemoizedResults(Old); 4172 } 4173 } 4174 4175 PushDefUseChildren(I, Worklist); 4176 } 4177 } 4178 4179 namespace { 4180 4181 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start 4182 /// expression in case its Loop is L. If it is not L then 4183 /// if IgnoreOtherLoops is true then use AddRec itself 4184 /// otherwise rewrite cannot be done. 4185 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4186 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> { 4187 public: 4188 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 4189 bool IgnoreOtherLoops = true) { 4190 SCEVInitRewriter Rewriter(L, SE); 4191 const SCEV *Result = Rewriter.visit(S); 4192 if (Rewriter.hasSeenLoopVariantSCEVUnknown()) 4193 return SE.getCouldNotCompute(); 4194 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops 4195 ? SE.getCouldNotCompute() 4196 : Result; 4197 } 4198 4199 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4200 if (!SE.isLoopInvariant(Expr, L)) 4201 SeenLoopVariantSCEVUnknown = true; 4202 return Expr; 4203 } 4204 4205 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4206 // Only re-write AddRecExprs for this loop. 4207 if (Expr->getLoop() == L) 4208 return Expr->getStart(); 4209 SeenOtherLoops = true; 4210 return Expr; 4211 } 4212 4213 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4214 4215 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4216 4217 private: 4218 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE) 4219 : SCEVRewriteVisitor(SE), L(L) {} 4220 4221 const Loop *L; 4222 bool SeenLoopVariantSCEVUnknown = false; 4223 bool SeenOtherLoops = false; 4224 }; 4225 4226 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post 4227 /// increment expression in case its Loop is L. If it is not L then 4228 /// use AddRec itself. 4229 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done. 4230 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> { 4231 public: 4232 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) { 4233 SCEVPostIncRewriter Rewriter(L, SE); 4234 const SCEV *Result = Rewriter.visit(S); 4235 return Rewriter.hasSeenLoopVariantSCEVUnknown() 4236 ? SE.getCouldNotCompute() 4237 : Result; 4238 } 4239 4240 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4241 if (!SE.isLoopInvariant(Expr, L)) 4242 SeenLoopVariantSCEVUnknown = true; 4243 return Expr; 4244 } 4245 4246 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4247 // Only re-write AddRecExprs for this loop. 4248 if (Expr->getLoop() == L) 4249 return Expr->getPostIncExpr(SE); 4250 SeenOtherLoops = true; 4251 return Expr; 4252 } 4253 4254 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; } 4255 4256 bool hasSeenOtherLoops() { return SeenOtherLoops; } 4257 4258 private: 4259 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE) 4260 : SCEVRewriteVisitor(SE), L(L) {} 4261 4262 const Loop *L; 4263 bool SeenLoopVariantSCEVUnknown = false; 4264 bool SeenOtherLoops = false; 4265 }; 4266 4267 /// This class evaluates the compare condition by matching it against the 4268 /// condition of loop latch. If there is a match we assume a true value 4269 /// for the condition while building SCEV nodes. 4270 class SCEVBackedgeConditionFolder 4271 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> { 4272 public: 4273 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4274 ScalarEvolution &SE) { 4275 bool IsPosBECond = false; 4276 Value *BECond = nullptr; 4277 if (BasicBlock *Latch = L->getLoopLatch()) { 4278 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator()); 4279 if (BI && BI->isConditional()) { 4280 assert(BI->getSuccessor(0) != BI->getSuccessor(1) && 4281 "Both outgoing branches should not target same header!"); 4282 BECond = BI->getCondition(); 4283 IsPosBECond = BI->getSuccessor(0) == L->getHeader(); 4284 } else { 4285 return S; 4286 } 4287 } 4288 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE); 4289 return Rewriter.visit(S); 4290 } 4291 4292 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4293 const SCEV *Result = Expr; 4294 bool InvariantF = SE.isLoopInvariant(Expr, L); 4295 4296 if (!InvariantF) { 4297 Instruction *I = cast<Instruction>(Expr->getValue()); 4298 switch (I->getOpcode()) { 4299 case Instruction::Select: { 4300 SelectInst *SI = cast<SelectInst>(I); 4301 Optional<const SCEV *> Res = 4302 compareWithBackedgeCondition(SI->getCondition()); 4303 if (Res.hasValue()) { 4304 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne(); 4305 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue()); 4306 } 4307 break; 4308 } 4309 default: { 4310 Optional<const SCEV *> Res = compareWithBackedgeCondition(I); 4311 if (Res.hasValue()) 4312 Result = Res.getValue(); 4313 break; 4314 } 4315 } 4316 } 4317 return Result; 4318 } 4319 4320 private: 4321 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond, 4322 bool IsPosBECond, ScalarEvolution &SE) 4323 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond), 4324 IsPositiveBECond(IsPosBECond) {} 4325 4326 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC); 4327 4328 const Loop *L; 4329 /// Loop back condition. 4330 Value *BackedgeCond = nullptr; 4331 /// Set to true if loop back is on positive branch condition. 4332 bool IsPositiveBECond; 4333 }; 4334 4335 Optional<const SCEV *> 4336 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) { 4337 4338 // If value matches the backedge condition for loop latch, 4339 // then return a constant evolution node based on loopback 4340 // branch taken. 4341 if (BackedgeCond == IC) 4342 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext())) 4343 : SE.getZero(Type::getInt1Ty(SE.getContext())); 4344 return None; 4345 } 4346 4347 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> { 4348 public: 4349 static const SCEV *rewrite(const SCEV *S, const Loop *L, 4350 ScalarEvolution &SE) { 4351 SCEVShiftRewriter Rewriter(L, SE); 4352 const SCEV *Result = Rewriter.visit(S); 4353 return Rewriter.isValid() ? Result : SE.getCouldNotCompute(); 4354 } 4355 4356 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 4357 // Only allow AddRecExprs for this loop. 4358 if (!SE.isLoopInvariant(Expr, L)) 4359 Valid = false; 4360 return Expr; 4361 } 4362 4363 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 4364 if (Expr->getLoop() == L && Expr->isAffine()) 4365 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE)); 4366 Valid = false; 4367 return Expr; 4368 } 4369 4370 bool isValid() { return Valid; } 4371 4372 private: 4373 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE) 4374 : SCEVRewriteVisitor(SE), L(L) {} 4375 4376 const Loop *L; 4377 bool Valid = true; 4378 }; 4379 4380 } // end anonymous namespace 4381 4382 SCEV::NoWrapFlags 4383 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) { 4384 if (!AR->isAffine()) 4385 return SCEV::FlagAnyWrap; 4386 4387 using OBO = OverflowingBinaryOperator; 4388 4389 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap; 4390 4391 if (!AR->hasNoSignedWrap()) { 4392 ConstantRange AddRecRange = getSignedRange(AR); 4393 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this)); 4394 4395 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4396 Instruction::Add, IncRange, OBO::NoSignedWrap); 4397 if (NSWRegion.contains(AddRecRange)) 4398 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW); 4399 } 4400 4401 if (!AR->hasNoUnsignedWrap()) { 4402 ConstantRange AddRecRange = getUnsignedRange(AR); 4403 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this)); 4404 4405 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion( 4406 Instruction::Add, IncRange, OBO::NoUnsignedWrap); 4407 if (NUWRegion.contains(AddRecRange)) 4408 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW); 4409 } 4410 4411 return Result; 4412 } 4413 4414 namespace { 4415 4416 /// Represents an abstract binary operation. This may exist as a 4417 /// normal instruction or constant expression, or may have been 4418 /// derived from an expression tree. 4419 struct BinaryOp { 4420 unsigned Opcode; 4421 Value *LHS; 4422 Value *RHS; 4423 bool IsNSW = false; 4424 bool IsNUW = false; 4425 bool IsExact = false; 4426 4427 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or 4428 /// constant expression. 4429 Operator *Op = nullptr; 4430 4431 explicit BinaryOp(Operator *Op) 4432 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)), 4433 Op(Op) { 4434 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) { 4435 IsNSW = OBO->hasNoSignedWrap(); 4436 IsNUW = OBO->hasNoUnsignedWrap(); 4437 } 4438 if (auto *PEO = dyn_cast<PossiblyExactOperator>(Op)) 4439 IsExact = PEO->isExact(); 4440 } 4441 4442 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false, 4443 bool IsNUW = false, bool IsExact = false) 4444 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW), 4445 IsExact(IsExact) {} 4446 }; 4447 4448 } // end anonymous namespace 4449 4450 /// Try to map \p V into a BinaryOp, and return \c None on failure. 4451 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) { 4452 auto *Op = dyn_cast<Operator>(V); 4453 if (!Op) 4454 return None; 4455 4456 // Implementation detail: all the cleverness here should happen without 4457 // creating new SCEV expressions -- our caller knowns tricks to avoid creating 4458 // SCEV expressions when possible, and we should not break that. 4459 4460 switch (Op->getOpcode()) { 4461 case Instruction::Add: 4462 case Instruction::Sub: 4463 case Instruction::Mul: 4464 case Instruction::UDiv: 4465 case Instruction::URem: 4466 case Instruction::And: 4467 case Instruction::Or: 4468 case Instruction::AShr: 4469 case Instruction::Shl: 4470 return BinaryOp(Op); 4471 4472 case Instruction::Xor: 4473 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1))) 4474 // If the RHS of the xor is a signmask, then this is just an add. 4475 // Instcombine turns add of signmask into xor as a strength reduction step. 4476 if (RHSC->getValue().isSignMask()) 4477 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1)); 4478 return BinaryOp(Op); 4479 4480 case Instruction::LShr: 4481 // Turn logical shift right of a constant into a unsigned divide. 4482 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) { 4483 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth(); 4484 4485 // If the shift count is not less than the bitwidth, the result of 4486 // the shift is undefined. Don't try to analyze it, because the 4487 // resolution chosen here may differ from the resolution chosen in 4488 // other parts of the compiler. 4489 if (SA->getValue().ult(BitWidth)) { 4490 Constant *X = 4491 ConstantInt::get(SA->getContext(), 4492 APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 4493 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X); 4494 } 4495 } 4496 return BinaryOp(Op); 4497 4498 case Instruction::ExtractValue: { 4499 auto *EVI = cast<ExtractValueInst>(Op); 4500 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0) 4501 break; 4502 4503 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()); 4504 if (!WO) 4505 break; 4506 4507 Instruction::BinaryOps BinOp = WO->getBinaryOp(); 4508 bool Signed = WO->isSigned(); 4509 // TODO: Should add nuw/nsw flags for mul as well. 4510 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT)) 4511 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS()); 4512 4513 // Now that we know that all uses of the arithmetic-result component of 4514 // CI are guarded by the overflow check, we can go ahead and pretend 4515 // that the arithmetic is non-overflowing. 4516 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(), 4517 /* IsNSW = */ Signed, /* IsNUW = */ !Signed); 4518 } 4519 4520 default: 4521 break; 4522 } 4523 4524 // Recognise intrinsic loop.decrement.reg, and as this has exactly the same 4525 // semantics as a Sub, return a binary sub expression. 4526 if (auto *II = dyn_cast<IntrinsicInst>(V)) 4527 if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg) 4528 return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1)); 4529 4530 return None; 4531 } 4532 4533 /// Helper function to createAddRecFromPHIWithCasts. We have a phi 4534 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via 4535 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the 4536 /// way. This function checks if \p Op, an operand of this SCEVAddExpr, 4537 /// follows one of the following patterns: 4538 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4539 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) 4540 /// If the SCEV expression of \p Op conforms with one of the expected patterns 4541 /// we return the type of the truncation operation, and indicate whether the 4542 /// truncated type should be treated as signed/unsigned by setting 4543 /// \p Signed to true/false, respectively. 4544 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI, 4545 bool &Signed, ScalarEvolution &SE) { 4546 // The case where Op == SymbolicPHI (that is, with no type conversions on 4547 // the way) is handled by the regular add recurrence creating logic and 4548 // would have already been triggered in createAddRecForPHI. Reaching it here 4549 // means that createAddRecFromPHI had failed for this PHI before (e.g., 4550 // because one of the other operands of the SCEVAddExpr updating this PHI is 4551 // not invariant). 4552 // 4553 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in 4554 // this case predicates that allow us to prove that Op == SymbolicPHI will 4555 // be added. 4556 if (Op == SymbolicPHI) 4557 return nullptr; 4558 4559 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType()); 4560 unsigned NewBits = SE.getTypeSizeInBits(Op->getType()); 4561 if (SourceBits != NewBits) 4562 return nullptr; 4563 4564 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op); 4565 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op); 4566 if (!SExt && !ZExt) 4567 return nullptr; 4568 const SCEVTruncateExpr *Trunc = 4569 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand()) 4570 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand()); 4571 if (!Trunc) 4572 return nullptr; 4573 const SCEV *X = Trunc->getOperand(); 4574 if (X != SymbolicPHI) 4575 return nullptr; 4576 Signed = SExt != nullptr; 4577 return Trunc->getType(); 4578 } 4579 4580 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) { 4581 if (!PN->getType()->isIntegerTy()) 4582 return nullptr; 4583 const Loop *L = LI.getLoopFor(PN->getParent()); 4584 if (!L || L->getHeader() != PN->getParent()) 4585 return nullptr; 4586 return L; 4587 } 4588 4589 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the 4590 // computation that updates the phi follows the following pattern: 4591 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum 4592 // which correspond to a phi->trunc->sext/zext->add->phi update chain. 4593 // If so, try to see if it can be rewritten as an AddRecExpr under some 4594 // Predicates. If successful, return them as a pair. Also cache the results 4595 // of the analysis. 4596 // 4597 // Example usage scenario: 4598 // Say the Rewriter is called for the following SCEV: 4599 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4600 // where: 4601 // %X = phi i64 (%Start, %BEValue) 4602 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X), 4603 // and call this function with %SymbolicPHI = %X. 4604 // 4605 // The analysis will find that the value coming around the backedge has 4606 // the following SCEV: 4607 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step) 4608 // Upon concluding that this matches the desired pattern, the function 4609 // will return the pair {NewAddRec, SmallPredsVec} where: 4610 // NewAddRec = {%Start,+,%Step} 4611 // SmallPredsVec = {P1, P2, P3} as follows: 4612 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw> 4613 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64) 4614 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64) 4615 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec 4616 // under the predicates {P1,P2,P3}. 4617 // This predicated rewrite will be cached in PredicatedSCEVRewrites: 4618 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)} 4619 // 4620 // TODO's: 4621 // 4622 // 1) Extend the Induction descriptor to also support inductions that involve 4623 // casts: When needed (namely, when we are called in the context of the 4624 // vectorizer induction analysis), a Set of cast instructions will be 4625 // populated by this method, and provided back to isInductionPHI. This is 4626 // needed to allow the vectorizer to properly record them to be ignored by 4627 // the cost model and to avoid vectorizing them (otherwise these casts, 4628 // which are redundant under the runtime overflow checks, will be 4629 // vectorized, which can be costly). 4630 // 4631 // 2) Support additional induction/PHISCEV patterns: We also want to support 4632 // inductions where the sext-trunc / zext-trunc operations (partly) occur 4633 // after the induction update operation (the induction increment): 4634 // 4635 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix) 4636 // which correspond to a phi->add->trunc->sext/zext->phi update chain. 4637 // 4638 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix) 4639 // which correspond to a phi->trunc->add->sext/zext->phi update chain. 4640 // 4641 // 3) Outline common code with createAddRecFromPHI to avoid duplication. 4642 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4643 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) { 4644 SmallVector<const SCEVPredicate *, 3> Predicates; 4645 4646 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can 4647 // return an AddRec expression under some predicate. 4648 4649 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4650 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4651 assert(L && "Expecting an integer loop header phi"); 4652 4653 // The loop may have multiple entrances or multiple exits; we can analyze 4654 // this phi as an addrec if it has a unique entry value and a unique 4655 // backedge value. 4656 Value *BEValueV = nullptr, *StartValueV = nullptr; 4657 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4658 Value *V = PN->getIncomingValue(i); 4659 if (L->contains(PN->getIncomingBlock(i))) { 4660 if (!BEValueV) { 4661 BEValueV = V; 4662 } else if (BEValueV != V) { 4663 BEValueV = nullptr; 4664 break; 4665 } 4666 } else if (!StartValueV) { 4667 StartValueV = V; 4668 } else if (StartValueV != V) { 4669 StartValueV = nullptr; 4670 break; 4671 } 4672 } 4673 if (!BEValueV || !StartValueV) 4674 return None; 4675 4676 const SCEV *BEValue = getSCEV(BEValueV); 4677 4678 // If the value coming around the backedge is an add with the symbolic 4679 // value we just inserted, possibly with casts that we can ignore under 4680 // an appropriate runtime guard, then we found a simple induction variable! 4681 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue); 4682 if (!Add) 4683 return None; 4684 4685 // If there is a single occurrence of the symbolic value, possibly 4686 // casted, replace it with a recurrence. 4687 unsigned FoundIndex = Add->getNumOperands(); 4688 Type *TruncTy = nullptr; 4689 bool Signed; 4690 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4691 if ((TruncTy = 4692 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this))) 4693 if (FoundIndex == e) { 4694 FoundIndex = i; 4695 break; 4696 } 4697 4698 if (FoundIndex == Add->getNumOperands()) 4699 return None; 4700 4701 // Create an add with everything but the specified operand. 4702 SmallVector<const SCEV *, 8> Ops; 4703 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 4704 if (i != FoundIndex) 4705 Ops.push_back(Add->getOperand(i)); 4706 const SCEV *Accum = getAddExpr(Ops); 4707 4708 // The runtime checks will not be valid if the step amount is 4709 // varying inside the loop. 4710 if (!isLoopInvariant(Accum, L)) 4711 return None; 4712 4713 // *** Part2: Create the predicates 4714 4715 // Analysis was successful: we have a phi-with-cast pattern for which we 4716 // can return an AddRec expression under the following predicates: 4717 // 4718 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum) 4719 // fits within the truncated type (does not overflow) for i = 0 to n-1. 4720 // P2: An Equal predicate that guarantees that 4721 // Start = (Ext ix (Trunc iy (Start) to ix) to iy) 4722 // P3: An Equal predicate that guarantees that 4723 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy) 4724 // 4725 // As we next prove, the above predicates guarantee that: 4726 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy) 4727 // 4728 // 4729 // More formally, we want to prove that: 4730 // Expr(i+1) = Start + (i+1) * Accum 4731 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4732 // 4733 // Given that: 4734 // 1) Expr(0) = Start 4735 // 2) Expr(1) = Start + Accum 4736 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2 4737 // 3) Induction hypothesis (step i): 4738 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum 4739 // 4740 // Proof: 4741 // Expr(i+1) = 4742 // = Start + (i+1)*Accum 4743 // = (Start + i*Accum) + Accum 4744 // = Expr(i) + Accum 4745 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum 4746 // :: from step i 4747 // 4748 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum 4749 // 4750 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) 4751 // + (Ext ix (Trunc iy (Accum) to ix) to iy) 4752 // + Accum :: from P3 4753 // 4754 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy) 4755 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y) 4756 // 4757 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum 4758 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum 4759 // 4760 // By induction, the same applies to all iterations 1<=i<n: 4761 // 4762 4763 // Create a truncated addrec for which we will add a no overflow check (P1). 4764 const SCEV *StartVal = getSCEV(StartValueV); 4765 const SCEV *PHISCEV = 4766 getAddRecExpr(getTruncateExpr(StartVal, TruncTy), 4767 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap); 4768 4769 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr. 4770 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV 4771 // will be constant. 4772 // 4773 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't 4774 // add P1. 4775 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) { 4776 SCEVWrapPredicate::IncrementWrapFlags AddedFlags = 4777 Signed ? SCEVWrapPredicate::IncrementNSSW 4778 : SCEVWrapPredicate::IncrementNUSW; 4779 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags); 4780 Predicates.push_back(AddRecPred); 4781 } 4782 4783 // Create the Equal Predicates P2,P3: 4784 4785 // It is possible that the predicates P2 and/or P3 are computable at 4786 // compile time due to StartVal and/or Accum being constants. 4787 // If either one is, then we can check that now and escape if either P2 4788 // or P3 is false. 4789 4790 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy) 4791 // for each of StartVal and Accum 4792 auto getExtendedExpr = [&](const SCEV *Expr, 4793 bool CreateSignExtend) -> const SCEV * { 4794 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant"); 4795 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy); 4796 const SCEV *ExtendedExpr = 4797 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType()) 4798 : getZeroExtendExpr(TruncatedExpr, Expr->getType()); 4799 return ExtendedExpr; 4800 }; 4801 4802 // Given: 4803 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy 4804 // = getExtendedExpr(Expr) 4805 // Determine whether the predicate P: Expr == ExtendedExpr 4806 // is known to be false at compile time 4807 auto PredIsKnownFalse = [&](const SCEV *Expr, 4808 const SCEV *ExtendedExpr) -> bool { 4809 return Expr != ExtendedExpr && 4810 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr); 4811 }; 4812 4813 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed); 4814 if (PredIsKnownFalse(StartVal, StartExtended)) { 4815 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";); 4816 return None; 4817 } 4818 4819 // The Step is always Signed (because the overflow checks are either 4820 // NSSW or NUSW) 4821 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true); 4822 if (PredIsKnownFalse(Accum, AccumExtended)) { 4823 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";); 4824 return None; 4825 } 4826 4827 auto AppendPredicate = [&](const SCEV *Expr, 4828 const SCEV *ExtendedExpr) -> void { 4829 if (Expr != ExtendedExpr && 4830 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) { 4831 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr); 4832 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred); 4833 Predicates.push_back(Pred); 4834 } 4835 }; 4836 4837 AppendPredicate(StartVal, StartExtended); 4838 AppendPredicate(Accum, AccumExtended); 4839 4840 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in 4841 // which the casts had been folded away. The caller can rewrite SymbolicPHI 4842 // into NewAR if it will also add the runtime overflow checks specified in 4843 // Predicates. 4844 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap); 4845 4846 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite = 4847 std::make_pair(NewAR, Predicates); 4848 // Remember the result of the analysis for this SCEV at this locayyytion. 4849 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite; 4850 return PredRewrite; 4851 } 4852 4853 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4854 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) { 4855 auto *PN = cast<PHINode>(SymbolicPHI->getValue()); 4856 const Loop *L = isIntegerLoopHeaderPHI(PN, LI); 4857 if (!L) 4858 return None; 4859 4860 // Check to see if we already analyzed this PHI. 4861 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L}); 4862 if (I != PredicatedSCEVRewrites.end()) { 4863 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite = 4864 I->second; 4865 // Analysis was done before and failed to create an AddRec: 4866 if (Rewrite.first == SymbolicPHI) 4867 return None; 4868 // Analysis was done before and succeeded to create an AddRec under 4869 // a predicate: 4870 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec"); 4871 assert(!(Rewrite.second).empty() && "Expected to find Predicates"); 4872 return Rewrite; 4873 } 4874 4875 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 4876 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI); 4877 4878 // Record in the cache that the analysis failed 4879 if (!Rewrite) { 4880 SmallVector<const SCEVPredicate *, 3> Predicates; 4881 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates}; 4882 return None; 4883 } 4884 4885 return Rewrite; 4886 } 4887 4888 // FIXME: This utility is currently required because the Rewriter currently 4889 // does not rewrite this expression: 4890 // {0, +, (sext ix (trunc iy to ix) to iy)} 4891 // into {0, +, %step}, 4892 // even when the following Equal predicate exists: 4893 // "%step == (sext ix (trunc iy to ix) to iy)". 4894 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds( 4895 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const { 4896 if (AR1 == AR2) 4897 return true; 4898 4899 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool { 4900 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) && 4901 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1))) 4902 return false; 4903 return true; 4904 }; 4905 4906 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) || 4907 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE))) 4908 return false; 4909 return true; 4910 } 4911 4912 /// A helper function for createAddRecFromPHI to handle simple cases. 4913 /// 4914 /// This function tries to find an AddRec expression for the simplest (yet most 4915 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)). 4916 /// If it fails, createAddRecFromPHI will use a more general, but slow, 4917 /// technique for finding the AddRec expression. 4918 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN, 4919 Value *BEValueV, 4920 Value *StartValueV) { 4921 const Loop *L = LI.getLoopFor(PN->getParent()); 4922 assert(L && L->getHeader() == PN->getParent()); 4923 assert(BEValueV && StartValueV); 4924 4925 auto BO = MatchBinaryOp(BEValueV, DT); 4926 if (!BO) 4927 return nullptr; 4928 4929 if (BO->Opcode != Instruction::Add) 4930 return nullptr; 4931 4932 const SCEV *Accum = nullptr; 4933 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS)) 4934 Accum = getSCEV(BO->RHS); 4935 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS)) 4936 Accum = getSCEV(BO->LHS); 4937 4938 if (!Accum) 4939 return nullptr; 4940 4941 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 4942 if (BO->IsNUW) 4943 Flags = setFlags(Flags, SCEV::FlagNUW); 4944 if (BO->IsNSW) 4945 Flags = setFlags(Flags, SCEV::FlagNSW); 4946 4947 const SCEV *StartVal = getSCEV(StartValueV); 4948 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 4949 4950 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 4951 4952 // We can add Flags to the post-inc expression only if we 4953 // know that it is *undefined behavior* for BEValueV to 4954 // overflow. 4955 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 4956 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 4957 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 4958 4959 return PHISCEV; 4960 } 4961 4962 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) { 4963 const Loop *L = LI.getLoopFor(PN->getParent()); 4964 if (!L || L->getHeader() != PN->getParent()) 4965 return nullptr; 4966 4967 // The loop may have multiple entrances or multiple exits; we can analyze 4968 // this phi as an addrec if it has a unique entry value and a unique 4969 // backedge value. 4970 Value *BEValueV = nullptr, *StartValueV = nullptr; 4971 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 4972 Value *V = PN->getIncomingValue(i); 4973 if (L->contains(PN->getIncomingBlock(i))) { 4974 if (!BEValueV) { 4975 BEValueV = V; 4976 } else if (BEValueV != V) { 4977 BEValueV = nullptr; 4978 break; 4979 } 4980 } else if (!StartValueV) { 4981 StartValueV = V; 4982 } else if (StartValueV != V) { 4983 StartValueV = nullptr; 4984 break; 4985 } 4986 } 4987 if (!BEValueV || !StartValueV) 4988 return nullptr; 4989 4990 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() && 4991 "PHI node already processed?"); 4992 4993 // First, try to find AddRec expression without creating a fictituos symbolic 4994 // value for PN. 4995 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV)) 4996 return S; 4997 4998 // Handle PHI node value symbolically. 4999 const SCEV *SymbolicName = getUnknown(PN); 5000 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName}); 5001 5002 // Using this symbolic name for the PHI, analyze the value coming around 5003 // the back-edge. 5004 const SCEV *BEValue = getSCEV(BEValueV); 5005 5006 // NOTE: If BEValue is loop invariant, we know that the PHI node just 5007 // has a special value for the first iteration of the loop. 5008 5009 // If the value coming around the backedge is an add with the symbolic 5010 // value we just inserted, then we found a simple induction variable! 5011 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) { 5012 // If there is a single occurrence of the symbolic value, replace it 5013 // with a recurrence. 5014 unsigned FoundIndex = Add->getNumOperands(); 5015 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5016 if (Add->getOperand(i) == SymbolicName) 5017 if (FoundIndex == e) { 5018 FoundIndex = i; 5019 break; 5020 } 5021 5022 if (FoundIndex != Add->getNumOperands()) { 5023 // Create an add with everything but the specified operand. 5024 SmallVector<const SCEV *, 8> Ops; 5025 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i) 5026 if (i != FoundIndex) 5027 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i), 5028 L, *this)); 5029 const SCEV *Accum = getAddExpr(Ops); 5030 5031 // This is not a valid addrec if the step amount is varying each 5032 // loop iteration, but is not itself an addrec in this loop. 5033 if (isLoopInvariant(Accum, L) || 5034 (isa<SCEVAddRecExpr>(Accum) && 5035 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) { 5036 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 5037 5038 if (auto BO = MatchBinaryOp(BEValueV, DT)) { 5039 if (BO->Opcode == Instruction::Add && BO->LHS == PN) { 5040 if (BO->IsNUW) 5041 Flags = setFlags(Flags, SCEV::FlagNUW); 5042 if (BO->IsNSW) 5043 Flags = setFlags(Flags, SCEV::FlagNSW); 5044 } 5045 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) { 5046 // If the increment is an inbounds GEP, then we know the address 5047 // space cannot be wrapped around. We cannot make any guarantee 5048 // about signed or unsigned overflow because pointers are 5049 // unsigned but we may have a negative index from the base 5050 // pointer. We can guarantee that no unsigned wrap occurs if the 5051 // indices form a positive value. 5052 if (GEP->isInBounds() && GEP->getOperand(0) == PN) { 5053 Flags = setFlags(Flags, SCEV::FlagNW); 5054 5055 const SCEV *Ptr = getSCEV(GEP->getPointerOperand()); 5056 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr))) 5057 Flags = setFlags(Flags, SCEV::FlagNUW); 5058 } 5059 5060 // We cannot transfer nuw and nsw flags from subtraction 5061 // operations -- sub nuw X, Y is not the same as add nuw X, -Y 5062 // for instance. 5063 } 5064 5065 const SCEV *StartVal = getSCEV(StartValueV); 5066 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags); 5067 5068 // Okay, for the entire analysis of this edge we assumed the PHI 5069 // to be symbolic. We now need to go back and purge all of the 5070 // entries for the scalars that use the symbolic expression. 5071 forgetSymbolicName(PN, SymbolicName); 5072 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV; 5073 5074 // We can add Flags to the post-inc expression only if we 5075 // know that it is *undefined behavior* for BEValueV to 5076 // overflow. 5077 if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) 5078 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L)) 5079 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags); 5080 5081 return PHISCEV; 5082 } 5083 } 5084 } else { 5085 // Otherwise, this could be a loop like this: 5086 // i = 0; for (j = 1; ..; ++j) { .... i = j; } 5087 // In this case, j = {1,+,1} and BEValue is j. 5088 // Because the other in-value of i (0) fits the evolution of BEValue 5089 // i really is an addrec evolution. 5090 // 5091 // We can generalize this saying that i is the shifted value of BEValue 5092 // by one iteration: 5093 // PHI(f(0), f({1,+,1})) --> f({0,+,1}) 5094 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this); 5095 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false); 5096 if (Shifted != getCouldNotCompute() && 5097 Start != getCouldNotCompute()) { 5098 const SCEV *StartVal = getSCEV(StartValueV); 5099 if (Start == StartVal) { 5100 // Okay, for the entire analysis of this edge we assumed the PHI 5101 // to be symbolic. We now need to go back and purge all of the 5102 // entries for the scalars that use the symbolic expression. 5103 forgetSymbolicName(PN, SymbolicName); 5104 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted; 5105 return Shifted; 5106 } 5107 } 5108 } 5109 5110 // Remove the temporary PHI node SCEV that has been inserted while intending 5111 // to create an AddRecExpr for this PHI node. We can not keep this temporary 5112 // as it will prevent later (possibly simpler) SCEV expressions to be added 5113 // to the ValueExprMap. 5114 eraseValueFromMap(PN); 5115 5116 return nullptr; 5117 } 5118 5119 // Checks if the SCEV S is available at BB. S is considered available at BB 5120 // if S can be materialized at BB without introducing a fault. 5121 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S, 5122 BasicBlock *BB) { 5123 struct CheckAvailable { 5124 bool TraversalDone = false; 5125 bool Available = true; 5126 5127 const Loop *L = nullptr; // The loop BB is in (can be nullptr) 5128 BasicBlock *BB = nullptr; 5129 DominatorTree &DT; 5130 5131 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT) 5132 : L(L), BB(BB), DT(DT) {} 5133 5134 bool setUnavailable() { 5135 TraversalDone = true; 5136 Available = false; 5137 return false; 5138 } 5139 5140 bool follow(const SCEV *S) { 5141 switch (S->getSCEVType()) { 5142 case scConstant: 5143 case scPtrToInt: 5144 case scTruncate: 5145 case scZeroExtend: 5146 case scSignExtend: 5147 case scAddExpr: 5148 case scMulExpr: 5149 case scUMaxExpr: 5150 case scSMaxExpr: 5151 case scUMinExpr: 5152 case scSMinExpr: 5153 // These expressions are available if their operand(s) is/are. 5154 return true; 5155 5156 case scAddRecExpr: { 5157 // We allow add recurrences that are on the loop BB is in, or some 5158 // outer loop. This guarantees availability because the value of the 5159 // add recurrence at BB is simply the "current" value of the induction 5160 // variable. We can relax this in the future; for instance an add 5161 // recurrence on a sibling dominating loop is also available at BB. 5162 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop(); 5163 if (L && (ARLoop == L || ARLoop->contains(L))) 5164 return true; 5165 5166 return setUnavailable(); 5167 } 5168 5169 case scUnknown: { 5170 // For SCEVUnknown, we check for simple dominance. 5171 const auto *SU = cast<SCEVUnknown>(S); 5172 Value *V = SU->getValue(); 5173 5174 if (isa<Argument>(V)) 5175 return false; 5176 5177 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB)) 5178 return false; 5179 5180 return setUnavailable(); 5181 } 5182 5183 case scUDivExpr: 5184 case scCouldNotCompute: 5185 // We do not try to smart about these at all. 5186 return setUnavailable(); 5187 } 5188 llvm_unreachable("Unknown SCEV kind!"); 5189 } 5190 5191 bool isDone() { return TraversalDone; } 5192 }; 5193 5194 CheckAvailable CA(L, BB, DT); 5195 SCEVTraversal<CheckAvailable> ST(CA); 5196 5197 ST.visitAll(S); 5198 return CA.Available; 5199 } 5200 5201 // Try to match a control flow sequence that branches out at BI and merges back 5202 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful 5203 // match. 5204 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge, 5205 Value *&C, Value *&LHS, Value *&RHS) { 5206 C = BI->getCondition(); 5207 5208 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0)); 5209 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1)); 5210 5211 if (!LeftEdge.isSingleEdge()) 5212 return false; 5213 5214 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()"); 5215 5216 Use &LeftUse = Merge->getOperandUse(0); 5217 Use &RightUse = Merge->getOperandUse(1); 5218 5219 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) { 5220 LHS = LeftUse; 5221 RHS = RightUse; 5222 return true; 5223 } 5224 5225 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) { 5226 LHS = RightUse; 5227 RHS = LeftUse; 5228 return true; 5229 } 5230 5231 return false; 5232 } 5233 5234 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) { 5235 auto IsReachable = 5236 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); }; 5237 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) { 5238 const Loop *L = LI.getLoopFor(PN->getParent()); 5239 5240 // We don't want to break LCSSA, even in a SCEV expression tree. 5241 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 5242 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L) 5243 return nullptr; 5244 5245 // Try to match 5246 // 5247 // br %cond, label %left, label %right 5248 // left: 5249 // br label %merge 5250 // right: 5251 // br label %merge 5252 // merge: 5253 // V = phi [ %x, %left ], [ %y, %right ] 5254 // 5255 // as "select %cond, %x, %y" 5256 5257 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock(); 5258 assert(IDom && "At least the entry block should dominate PN"); 5259 5260 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator()); 5261 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr; 5262 5263 if (BI && BI->isConditional() && 5264 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) && 5265 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) && 5266 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent())) 5267 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS); 5268 } 5269 5270 return nullptr; 5271 } 5272 5273 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) { 5274 if (const SCEV *S = createAddRecFromPHI(PN)) 5275 return S; 5276 5277 if (const SCEV *S = createNodeFromSelectLikePHI(PN)) 5278 return S; 5279 5280 // If the PHI has a single incoming value, follow that value, unless the 5281 // PHI's incoming blocks are in a different loop, in which case doing so 5282 // risks breaking LCSSA form. Instcombine would normally zap these, but 5283 // it doesn't have DominatorTree information, so it may miss cases. 5284 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC})) 5285 if (LI.replacementPreservesLCSSAForm(PN, V)) 5286 return getSCEV(V); 5287 5288 // If it's not a loop phi, we can't handle it yet. 5289 return getUnknown(PN); 5290 } 5291 5292 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I, 5293 Value *Cond, 5294 Value *TrueVal, 5295 Value *FalseVal) { 5296 // Handle "constant" branch or select. This can occur for instance when a 5297 // loop pass transforms an inner loop and moves on to process the outer loop. 5298 if (auto *CI = dyn_cast<ConstantInt>(Cond)) 5299 return getSCEV(CI->isOne() ? TrueVal : FalseVal); 5300 5301 // Try to match some simple smax or umax patterns. 5302 auto *ICI = dyn_cast<ICmpInst>(Cond); 5303 if (!ICI) 5304 return getUnknown(I); 5305 5306 Value *LHS = ICI->getOperand(0); 5307 Value *RHS = ICI->getOperand(1); 5308 5309 switch (ICI->getPredicate()) { 5310 case ICmpInst::ICMP_SLT: 5311 case ICmpInst::ICMP_SLE: 5312 std::swap(LHS, RHS); 5313 LLVM_FALLTHROUGH; 5314 case ICmpInst::ICMP_SGT: 5315 case ICmpInst::ICMP_SGE: 5316 // a >s b ? a+x : b+x -> smax(a, b)+x 5317 // a >s b ? b+x : a+x -> smin(a, b)+x 5318 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5319 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType()); 5320 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType()); 5321 const SCEV *LA = getSCEV(TrueVal); 5322 const SCEV *RA = getSCEV(FalseVal); 5323 const SCEV *LDiff = getMinusSCEV(LA, LS); 5324 const SCEV *RDiff = getMinusSCEV(RA, RS); 5325 if (LDiff == RDiff) 5326 return getAddExpr(getSMaxExpr(LS, RS), LDiff); 5327 LDiff = getMinusSCEV(LA, RS); 5328 RDiff = getMinusSCEV(RA, LS); 5329 if (LDiff == RDiff) 5330 return getAddExpr(getSMinExpr(LS, RS), LDiff); 5331 } 5332 break; 5333 case ICmpInst::ICMP_ULT: 5334 case ICmpInst::ICMP_ULE: 5335 std::swap(LHS, RHS); 5336 LLVM_FALLTHROUGH; 5337 case ICmpInst::ICMP_UGT: 5338 case ICmpInst::ICMP_UGE: 5339 // a >u b ? a+x : b+x -> umax(a, b)+x 5340 // a >u b ? b+x : a+x -> umin(a, b)+x 5341 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) { 5342 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5343 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType()); 5344 const SCEV *LA = getSCEV(TrueVal); 5345 const SCEV *RA = getSCEV(FalseVal); 5346 const SCEV *LDiff = getMinusSCEV(LA, LS); 5347 const SCEV *RDiff = getMinusSCEV(RA, RS); 5348 if (LDiff == RDiff) 5349 return getAddExpr(getUMaxExpr(LS, RS), LDiff); 5350 LDiff = getMinusSCEV(LA, RS); 5351 RDiff = getMinusSCEV(RA, LS); 5352 if (LDiff == RDiff) 5353 return getAddExpr(getUMinExpr(LS, RS), LDiff); 5354 } 5355 break; 5356 case ICmpInst::ICMP_NE: 5357 // n != 0 ? n+x : 1+x -> umax(n, 1)+x 5358 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5359 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5360 const SCEV *One = getOne(I->getType()); 5361 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5362 const SCEV *LA = getSCEV(TrueVal); 5363 const SCEV *RA = getSCEV(FalseVal); 5364 const SCEV *LDiff = getMinusSCEV(LA, LS); 5365 const SCEV *RDiff = getMinusSCEV(RA, One); 5366 if (LDiff == RDiff) 5367 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5368 } 5369 break; 5370 case ICmpInst::ICMP_EQ: 5371 // n == 0 ? 1+x : n+x -> umax(n, 1)+x 5372 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) && 5373 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) { 5374 const SCEV *One = getOne(I->getType()); 5375 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType()); 5376 const SCEV *LA = getSCEV(TrueVal); 5377 const SCEV *RA = getSCEV(FalseVal); 5378 const SCEV *LDiff = getMinusSCEV(LA, One); 5379 const SCEV *RDiff = getMinusSCEV(RA, LS); 5380 if (LDiff == RDiff) 5381 return getAddExpr(getUMaxExpr(One, LS), LDiff); 5382 } 5383 break; 5384 default: 5385 break; 5386 } 5387 5388 return getUnknown(I); 5389 } 5390 5391 /// Expand GEP instructions into add and multiply operations. This allows them 5392 /// to be analyzed by regular SCEV code. 5393 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) { 5394 // Don't attempt to analyze GEPs over unsized objects. 5395 if (!GEP->getSourceElementType()->isSized()) 5396 return getUnknown(GEP); 5397 5398 SmallVector<const SCEV *, 4> IndexExprs; 5399 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) 5400 IndexExprs.push_back(getSCEV(*Index)); 5401 return getGEPExpr(GEP, IndexExprs); 5402 } 5403 5404 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) { 5405 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5406 return C->getAPInt().countTrailingZeros(); 5407 5408 if (const SCEVPtrToIntExpr *I = dyn_cast<SCEVPtrToIntExpr>(S)) 5409 return GetMinTrailingZeros(I->getOperand()); 5410 5411 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) 5412 return std::min(GetMinTrailingZeros(T->getOperand()), 5413 (uint32_t)getTypeSizeInBits(T->getType())); 5414 5415 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) { 5416 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5417 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5418 ? getTypeSizeInBits(E->getType()) 5419 : OpRes; 5420 } 5421 5422 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) { 5423 uint32_t OpRes = GetMinTrailingZeros(E->getOperand()); 5424 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) 5425 ? getTypeSizeInBits(E->getType()) 5426 : OpRes; 5427 } 5428 5429 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) { 5430 // The result is the min of all operands results. 5431 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5432 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5433 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5434 return MinOpRes; 5435 } 5436 5437 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) { 5438 // The result is the sum of all operands results. 5439 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0)); 5440 uint32_t BitWidth = getTypeSizeInBits(M->getType()); 5441 for (unsigned i = 1, e = M->getNumOperands(); 5442 SumOpRes != BitWidth && i != e; ++i) 5443 SumOpRes = 5444 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth); 5445 return SumOpRes; 5446 } 5447 5448 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) { 5449 // The result is the min of all operands results. 5450 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0)); 5451 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i) 5452 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i))); 5453 return MinOpRes; 5454 } 5455 5456 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) { 5457 // The result is the min of all operands results. 5458 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5459 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5460 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5461 return MinOpRes; 5462 } 5463 5464 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) { 5465 // The result is the min of all operands results. 5466 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0)); 5467 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i) 5468 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i))); 5469 return MinOpRes; 5470 } 5471 5472 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5473 // For a SCEVUnknown, ask ValueTracking. 5474 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT); 5475 return Known.countMinTrailingZeros(); 5476 } 5477 5478 // SCEVUDivExpr 5479 return 0; 5480 } 5481 5482 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) { 5483 auto I = MinTrailingZerosCache.find(S); 5484 if (I != MinTrailingZerosCache.end()) 5485 return I->second; 5486 5487 uint32_t Result = GetMinTrailingZerosImpl(S); 5488 auto InsertPair = MinTrailingZerosCache.insert({S, Result}); 5489 assert(InsertPair.second && "Should insert a new key"); 5490 return InsertPair.first->second; 5491 } 5492 5493 /// Helper method to assign a range to V from metadata present in the IR. 5494 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) { 5495 if (Instruction *I = dyn_cast<Instruction>(V)) 5496 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) 5497 return getConstantRangeFromMetadata(*MD); 5498 5499 return None; 5500 } 5501 5502 /// Determine the range for a particular SCEV. If SignHint is 5503 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges 5504 /// with a "cleaner" unsigned (resp. signed) representation. 5505 const ConstantRange & 5506 ScalarEvolution::getRangeRef(const SCEV *S, 5507 ScalarEvolution::RangeSignHint SignHint) { 5508 DenseMap<const SCEV *, ConstantRange> &Cache = 5509 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges 5510 : SignedRanges; 5511 ConstantRange::PreferredRangeType RangeType = 5512 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED 5513 ? ConstantRange::Unsigned : ConstantRange::Signed; 5514 5515 // See if we've computed this range already. 5516 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S); 5517 if (I != Cache.end()) 5518 return I->second; 5519 5520 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) 5521 return setRange(C, SignHint, ConstantRange(C->getAPInt())); 5522 5523 unsigned BitWidth = getTypeSizeInBits(S->getType()); 5524 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true); 5525 using OBO = OverflowingBinaryOperator; 5526 5527 // If the value has known zeros, the maximum value will have those known zeros 5528 // as well. 5529 uint32_t TZ = GetMinTrailingZeros(S); 5530 if (TZ != 0) { 5531 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) 5532 ConservativeResult = 5533 ConstantRange(APInt::getMinValue(BitWidth), 5534 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1); 5535 else 5536 ConservativeResult = ConstantRange( 5537 APInt::getSignedMinValue(BitWidth), 5538 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1); 5539 } 5540 5541 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { 5542 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint); 5543 unsigned WrapType = OBO::AnyWrap; 5544 if (Add->hasNoSignedWrap()) 5545 WrapType |= OBO::NoSignedWrap; 5546 if (Add->hasNoUnsignedWrap()) 5547 WrapType |= OBO::NoUnsignedWrap; 5548 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i) 5549 X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint), 5550 WrapType, RangeType); 5551 return setRange(Add, SignHint, 5552 ConservativeResult.intersectWith(X, RangeType)); 5553 } 5554 5555 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { 5556 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint); 5557 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i) 5558 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint)); 5559 return setRange(Mul, SignHint, 5560 ConservativeResult.intersectWith(X, RangeType)); 5561 } 5562 5563 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) { 5564 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint); 5565 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i) 5566 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint)); 5567 return setRange(SMax, SignHint, 5568 ConservativeResult.intersectWith(X, RangeType)); 5569 } 5570 5571 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) { 5572 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint); 5573 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i) 5574 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint)); 5575 return setRange(UMax, SignHint, 5576 ConservativeResult.intersectWith(X, RangeType)); 5577 } 5578 5579 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) { 5580 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint); 5581 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i) 5582 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint)); 5583 return setRange(SMin, SignHint, 5584 ConservativeResult.intersectWith(X, RangeType)); 5585 } 5586 5587 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) { 5588 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint); 5589 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i) 5590 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint)); 5591 return setRange(UMin, SignHint, 5592 ConservativeResult.intersectWith(X, RangeType)); 5593 } 5594 5595 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) { 5596 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint); 5597 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint); 5598 return setRange(UDiv, SignHint, 5599 ConservativeResult.intersectWith(X.udiv(Y), RangeType)); 5600 } 5601 5602 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) { 5603 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint); 5604 return setRange(ZExt, SignHint, 5605 ConservativeResult.intersectWith(X.zeroExtend(BitWidth), 5606 RangeType)); 5607 } 5608 5609 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) { 5610 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint); 5611 return setRange(SExt, SignHint, 5612 ConservativeResult.intersectWith(X.signExtend(BitWidth), 5613 RangeType)); 5614 } 5615 5616 if (const SCEVPtrToIntExpr *PtrToInt = dyn_cast<SCEVPtrToIntExpr>(S)) { 5617 ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint); 5618 return setRange(PtrToInt, SignHint, X); 5619 } 5620 5621 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) { 5622 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint); 5623 return setRange(Trunc, SignHint, 5624 ConservativeResult.intersectWith(X.truncate(BitWidth), 5625 RangeType)); 5626 } 5627 5628 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 5629 // If there's no unsigned wrap, the value will never be less than its 5630 // initial value. 5631 if (AddRec->hasNoUnsignedWrap()) { 5632 APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart()); 5633 if (!UnsignedMinValue.isNullValue()) 5634 ConservativeResult = ConservativeResult.intersectWith( 5635 ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType); 5636 } 5637 5638 // If there's no signed wrap, and all the operands except initial value have 5639 // the same sign or zero, the value won't ever be: 5640 // 1: smaller than initial value if operands are non negative, 5641 // 2: bigger than initial value if operands are non positive. 5642 // For both cases, value can not cross signed min/max boundary. 5643 if (AddRec->hasNoSignedWrap()) { 5644 bool AllNonNeg = true; 5645 bool AllNonPos = true; 5646 for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) { 5647 if (!isKnownNonNegative(AddRec->getOperand(i))) 5648 AllNonNeg = false; 5649 if (!isKnownNonPositive(AddRec->getOperand(i))) 5650 AllNonPos = false; 5651 } 5652 if (AllNonNeg) 5653 ConservativeResult = ConservativeResult.intersectWith( 5654 ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()), 5655 APInt::getSignedMinValue(BitWidth)), 5656 RangeType); 5657 else if (AllNonPos) 5658 ConservativeResult = ConservativeResult.intersectWith( 5659 ConstantRange::getNonEmpty( 5660 APInt::getSignedMinValue(BitWidth), 5661 getSignedRangeMax(AddRec->getStart()) + 1), 5662 RangeType); 5663 } 5664 5665 // TODO: non-affine addrec 5666 if (AddRec->isAffine()) { 5667 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop()); 5668 if (!isa<SCEVCouldNotCompute>(MaxBECount) && 5669 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) { 5670 auto RangeFromAffine = getRangeForAffineAR( 5671 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5672 BitWidth); 5673 ConservativeResult = 5674 ConservativeResult.intersectWith(RangeFromAffine, RangeType); 5675 5676 auto RangeFromFactoring = getRangeViaFactoring( 5677 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount, 5678 BitWidth); 5679 ConservativeResult = 5680 ConservativeResult.intersectWith(RangeFromFactoring, RangeType); 5681 } 5682 5683 // Now try symbolic BE count and more powerful methods. 5684 if (UseExpensiveRangeSharpening) { 5685 const SCEV *SymbolicMaxBECount = 5686 getSymbolicMaxBackedgeTakenCount(AddRec->getLoop()); 5687 if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) && 5688 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5689 AddRec->hasNoSelfWrap()) { 5690 auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR( 5691 AddRec, SymbolicMaxBECount, BitWidth, SignHint); 5692 ConservativeResult = 5693 ConservativeResult.intersectWith(RangeFromAffineNew, RangeType); 5694 } 5695 } 5696 } 5697 5698 return setRange(AddRec, SignHint, std::move(ConservativeResult)); 5699 } 5700 5701 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { 5702 // Check if the IR explicitly contains !range metadata. 5703 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue()); 5704 if (MDRange.hasValue()) 5705 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(), 5706 RangeType); 5707 5708 // Split here to avoid paying the compile-time cost of calling both 5709 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted 5710 // if needed. 5711 const DataLayout &DL = getDataLayout(); 5712 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) { 5713 // For a SCEVUnknown, ask ValueTracking. 5714 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5715 if (Known.getBitWidth() != BitWidth) 5716 Known = Known.zextOrTrunc(BitWidth); 5717 // If Known does not result in full-set, intersect with it. 5718 if (Known.getMinValue() != Known.getMaxValue() + 1) 5719 ConservativeResult = ConservativeResult.intersectWith( 5720 ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1), 5721 RangeType); 5722 } else { 5723 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED && 5724 "generalize as needed!"); 5725 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT); 5726 // If the pointer size is larger than the index size type, this can cause 5727 // NS to be larger than BitWidth. So compensate for this. 5728 if (U->getType()->isPointerTy()) { 5729 unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType()); 5730 int ptrIdxDiff = ptrSize - BitWidth; 5731 if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff) 5732 NS -= ptrIdxDiff; 5733 } 5734 5735 if (NS > 1) 5736 ConservativeResult = ConservativeResult.intersectWith( 5737 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1), 5738 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1), 5739 RangeType); 5740 } 5741 5742 // A range of Phi is a subset of union of all ranges of its input. 5743 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) { 5744 // Make sure that we do not run over cycled Phis. 5745 if (PendingPhiRanges.insert(Phi).second) { 5746 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false); 5747 for (auto &Op : Phi->operands()) { 5748 auto OpRange = getRangeRef(getSCEV(Op), SignHint); 5749 RangeFromOps = RangeFromOps.unionWith(OpRange); 5750 // No point to continue if we already have a full set. 5751 if (RangeFromOps.isFullSet()) 5752 break; 5753 } 5754 ConservativeResult = 5755 ConservativeResult.intersectWith(RangeFromOps, RangeType); 5756 bool Erased = PendingPhiRanges.erase(Phi); 5757 assert(Erased && "Failed to erase Phi properly?"); 5758 (void) Erased; 5759 } 5760 } 5761 5762 return setRange(U, SignHint, std::move(ConservativeResult)); 5763 } 5764 5765 return setRange(S, SignHint, std::move(ConservativeResult)); 5766 } 5767 5768 // Given a StartRange, Step and MaxBECount for an expression compute a range of 5769 // values that the expression can take. Initially, the expression has a value 5770 // from StartRange and then is changed by Step up to MaxBECount times. Signed 5771 // argument defines if we treat Step as signed or unsigned. 5772 static ConstantRange getRangeForAffineARHelper(APInt Step, 5773 const ConstantRange &StartRange, 5774 const APInt &MaxBECount, 5775 unsigned BitWidth, bool Signed) { 5776 // If either Step or MaxBECount is 0, then the expression won't change, and we 5777 // just need to return the initial range. 5778 if (Step == 0 || MaxBECount == 0) 5779 return StartRange; 5780 5781 // If we don't know anything about the initial value (i.e. StartRange is 5782 // FullRange), then we don't know anything about the final range either. 5783 // Return FullRange. 5784 if (StartRange.isFullSet()) 5785 return ConstantRange::getFull(BitWidth); 5786 5787 // If Step is signed and negative, then we use its absolute value, but we also 5788 // note that we're moving in the opposite direction. 5789 bool Descending = Signed && Step.isNegative(); 5790 5791 if (Signed) 5792 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this: 5793 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128. 5794 // This equations hold true due to the well-defined wrap-around behavior of 5795 // APInt. 5796 Step = Step.abs(); 5797 5798 // Check if Offset is more than full span of BitWidth. If it is, the 5799 // expression is guaranteed to overflow. 5800 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount)) 5801 return ConstantRange::getFull(BitWidth); 5802 5803 // Offset is by how much the expression can change. Checks above guarantee no 5804 // overflow here. 5805 APInt Offset = Step * MaxBECount; 5806 5807 // Minimum value of the final range will match the minimal value of StartRange 5808 // if the expression is increasing and will be decreased by Offset otherwise. 5809 // Maximum value of the final range will match the maximal value of StartRange 5810 // if the expression is decreasing and will be increased by Offset otherwise. 5811 APInt StartLower = StartRange.getLower(); 5812 APInt StartUpper = StartRange.getUpper() - 1; 5813 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset)) 5814 : (StartUpper + std::move(Offset)); 5815 5816 // It's possible that the new minimum/maximum value will fall into the initial 5817 // range (due to wrap around). This means that the expression can take any 5818 // value in this bitwidth, and we have to return full range. 5819 if (StartRange.contains(MovedBoundary)) 5820 return ConstantRange::getFull(BitWidth); 5821 5822 APInt NewLower = 5823 Descending ? std::move(MovedBoundary) : std::move(StartLower); 5824 APInt NewUpper = 5825 Descending ? std::move(StartUpper) : std::move(MovedBoundary); 5826 NewUpper += 1; 5827 5828 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range. 5829 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper)); 5830 } 5831 5832 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start, 5833 const SCEV *Step, 5834 const SCEV *MaxBECount, 5835 unsigned BitWidth) { 5836 assert(!isa<SCEVCouldNotCompute>(MaxBECount) && 5837 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth && 5838 "Precondition!"); 5839 5840 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType()); 5841 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount); 5842 5843 // First, consider step signed. 5844 ConstantRange StartSRange = getSignedRange(Start); 5845 ConstantRange StepSRange = getSignedRange(Step); 5846 5847 // If Step can be both positive and negative, we need to find ranges for the 5848 // maximum absolute step values in both directions and union them. 5849 ConstantRange SR = 5850 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange, 5851 MaxBECountValue, BitWidth, /* Signed = */ true); 5852 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(), 5853 StartSRange, MaxBECountValue, 5854 BitWidth, /* Signed = */ true)); 5855 5856 // Next, consider step unsigned. 5857 ConstantRange UR = getRangeForAffineARHelper( 5858 getUnsignedRangeMax(Step), getUnsignedRange(Start), 5859 MaxBECountValue, BitWidth, /* Signed = */ false); 5860 5861 // Finally, intersect signed and unsigned ranges. 5862 return SR.intersectWith(UR, ConstantRange::Smallest); 5863 } 5864 5865 ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR( 5866 const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth, 5867 ScalarEvolution::RangeSignHint SignHint) { 5868 assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n"); 5869 assert(AddRec->hasNoSelfWrap() && 5870 "This only works for non-self-wrapping AddRecs!"); 5871 const bool IsSigned = SignHint == HINT_RANGE_SIGNED; 5872 const SCEV *Step = AddRec->getStepRecurrence(*this); 5873 // Only deal with constant step to save compile time. 5874 if (!isa<SCEVConstant>(Step)) 5875 return ConstantRange::getFull(BitWidth); 5876 // Let's make sure that we can prove that we do not self-wrap during 5877 // MaxBECount iterations. We need this because MaxBECount is a maximum 5878 // iteration count estimate, and we might infer nw from some exit for which we 5879 // do not know max exit count (or any other side reasoning). 5880 // TODO: Turn into assert at some point. 5881 MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType()); 5882 const SCEV *RangeWidth = getMinusOne(AddRec->getType()); 5883 const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step)); 5884 const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs); 5885 if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount, 5886 MaxItersWithoutWrap)) 5887 return ConstantRange::getFull(BitWidth); 5888 5889 ICmpInst::Predicate LEPred = 5890 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 5891 ICmpInst::Predicate GEPred = 5892 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; 5893 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this); 5894 5895 // We know that there is no self-wrap. Let's take Start and End values and 5896 // look at all intermediate values V1, V2, ..., Vn that IndVar takes during 5897 // the iteration. They either lie inside the range [Min(Start, End), 5898 // Max(Start, End)] or outside it: 5899 // 5900 // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax; 5901 // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax; 5902 // 5903 // No self wrap flag guarantees that the intermediate values cannot be BOTH 5904 // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that 5905 // knowledge, let's try to prove that we are dealing with Case 1. It is so if 5906 // Start <= End and step is positive, or Start >= End and step is negative. 5907 const SCEV *Start = AddRec->getStart(); 5908 ConstantRange StartRange = getRangeRef(Start, SignHint); 5909 ConstantRange EndRange = getRangeRef(End, SignHint); 5910 ConstantRange RangeBetween = StartRange.unionWith(EndRange); 5911 // If they already cover full iteration space, we will know nothing useful 5912 // even if we prove what we want to prove. 5913 if (RangeBetween.isFullSet()) 5914 return RangeBetween; 5915 // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax). 5916 bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet() 5917 : RangeBetween.isWrappedSet(); 5918 if (IsWrappedSet) 5919 return ConstantRange::getFull(BitWidth); 5920 5921 if (isKnownPositive(Step) && 5922 isKnownPredicateViaConstantRanges(LEPred, Start, End)) 5923 return RangeBetween; 5924 else if (isKnownNegative(Step) && 5925 isKnownPredicateViaConstantRanges(GEPred, Start, End)) 5926 return RangeBetween; 5927 return ConstantRange::getFull(BitWidth); 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<SCEVIntegralCastExpr>(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<Operator>(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 // FIXME: we shouldn't special-case null pointer constant. 6228 return getZero(V->getType()); 6229 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) 6230 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee()); 6231 else if (!isa<ConstantExpr>(V)) 6232 return getUnknown(V); 6233 6234 Operator *U = cast<Operator>(V); 6235 if (auto BO = MatchBinaryOp(U, DT)) { 6236 switch (BO->Opcode) { 6237 case Instruction::Add: { 6238 // The simple thing to do would be to just call getSCEV on both operands 6239 // and call getAddExpr with the result. However if we're looking at a 6240 // bunch of things all added together, this can be quite inefficient, 6241 // because it leads to N-1 getAddExpr calls for N ultimate operands. 6242 // Instead, gather up all the operands and make a single getAddExpr call. 6243 // LLVM IR canonical form means we need only traverse the left operands. 6244 SmallVector<const SCEV *, 4> AddOps; 6245 do { 6246 if (BO->Op) { 6247 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6248 AddOps.push_back(OpSCEV); 6249 break; 6250 } 6251 6252 // If a NUW or NSW flag can be applied to the SCEV for this 6253 // addition, then compute the SCEV for this addition by itself 6254 // with a separate call to getAddExpr. We need to do that 6255 // instead of pushing the operands of the addition onto AddOps, 6256 // since the flags are only known to apply to this particular 6257 // addition - they may not apply to other additions that can be 6258 // formed with operands from AddOps. 6259 const SCEV *RHS = getSCEV(BO->RHS); 6260 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6261 if (Flags != SCEV::FlagAnyWrap) { 6262 const SCEV *LHS = getSCEV(BO->LHS); 6263 if (BO->Opcode == Instruction::Sub) 6264 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags)); 6265 else 6266 AddOps.push_back(getAddExpr(LHS, RHS, Flags)); 6267 break; 6268 } 6269 } 6270 6271 if (BO->Opcode == Instruction::Sub) 6272 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS))); 6273 else 6274 AddOps.push_back(getSCEV(BO->RHS)); 6275 6276 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6277 if (!NewBO || (NewBO->Opcode != Instruction::Add && 6278 NewBO->Opcode != Instruction::Sub)) { 6279 AddOps.push_back(getSCEV(BO->LHS)); 6280 break; 6281 } 6282 BO = NewBO; 6283 } while (true); 6284 6285 return getAddExpr(AddOps); 6286 } 6287 6288 case Instruction::Mul: { 6289 SmallVector<const SCEV *, 4> MulOps; 6290 do { 6291 if (BO->Op) { 6292 if (auto *OpSCEV = getExistingSCEV(BO->Op)) { 6293 MulOps.push_back(OpSCEV); 6294 break; 6295 } 6296 6297 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op); 6298 if (Flags != SCEV::FlagAnyWrap) { 6299 MulOps.push_back( 6300 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags)); 6301 break; 6302 } 6303 } 6304 6305 MulOps.push_back(getSCEV(BO->RHS)); 6306 auto NewBO = MatchBinaryOp(BO->LHS, DT); 6307 if (!NewBO || NewBO->Opcode != Instruction::Mul) { 6308 MulOps.push_back(getSCEV(BO->LHS)); 6309 break; 6310 } 6311 BO = NewBO; 6312 } while (true); 6313 6314 return getMulExpr(MulOps); 6315 } 6316 case Instruction::UDiv: 6317 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6318 case Instruction::URem: 6319 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS)); 6320 case Instruction::Sub: { 6321 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap; 6322 if (BO->Op) 6323 Flags = getNoWrapFlagsFromUB(BO->Op); 6324 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags); 6325 } 6326 case Instruction::And: 6327 // For an expression like x&255 that merely masks off the high bits, 6328 // use zext(trunc(x)) as the SCEV expression. 6329 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6330 if (CI->isZero()) 6331 return getSCEV(BO->RHS); 6332 if (CI->isMinusOne()) 6333 return getSCEV(BO->LHS); 6334 const APInt &A = CI->getValue(); 6335 6336 // Instcombine's ShrinkDemandedConstant may strip bits out of 6337 // constants, obscuring what would otherwise be a low-bits mask. 6338 // Use computeKnownBits to compute what ShrinkDemandedConstant 6339 // knew about to reconstruct a low-bits mask value. 6340 unsigned LZ = A.countLeadingZeros(); 6341 unsigned TZ = A.countTrailingZeros(); 6342 unsigned BitWidth = A.getBitWidth(); 6343 KnownBits Known(BitWidth); 6344 computeKnownBits(BO->LHS, Known, getDataLayout(), 6345 0, &AC, nullptr, &DT); 6346 6347 APInt EffectiveMask = 6348 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ); 6349 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) { 6350 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ)); 6351 const SCEV *LHS = getSCEV(BO->LHS); 6352 const SCEV *ShiftedLHS = nullptr; 6353 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) { 6354 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) { 6355 // For an expression like (x * 8) & 8, simplify the multiply. 6356 unsigned MulZeros = OpC->getAPInt().countTrailingZeros(); 6357 unsigned GCD = std::min(MulZeros, TZ); 6358 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD); 6359 SmallVector<const SCEV*, 4> MulOps; 6360 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD))); 6361 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end()); 6362 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags()); 6363 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt)); 6364 } 6365 } 6366 if (!ShiftedLHS) 6367 ShiftedLHS = getUDivExpr(LHS, MulCount); 6368 return getMulExpr( 6369 getZeroExtendExpr( 6370 getTruncateExpr(ShiftedLHS, 6371 IntegerType::get(getContext(), BitWidth - LZ - TZ)), 6372 BO->LHS->getType()), 6373 MulCount); 6374 } 6375 } 6376 break; 6377 6378 case Instruction::Or: 6379 // If the RHS of the Or is a constant, we may have something like: 6380 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop 6381 // optimizations will transparently handle this case. 6382 // 6383 // In order for this transformation to be safe, the LHS must be of the 6384 // form X*(2^n) and the Or constant must be less than 2^n. 6385 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6386 const SCEV *LHS = getSCEV(BO->LHS); 6387 const APInt &CIVal = CI->getValue(); 6388 if (GetMinTrailingZeros(LHS) >= 6389 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) { 6390 // Build a plain add SCEV. 6391 return getAddExpr(LHS, getSCEV(CI), 6392 (SCEV::NoWrapFlags)(SCEV::FlagNUW | SCEV::FlagNSW)); 6393 } 6394 } 6395 break; 6396 6397 case Instruction::Xor: 6398 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) { 6399 // If the RHS of xor is -1, then this is a not operation. 6400 if (CI->isMinusOne()) 6401 return getNotSCEV(getSCEV(BO->LHS)); 6402 6403 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask. 6404 // This is a variant of the check for xor with -1, and it handles 6405 // the case where instcombine has trimmed non-demanded bits out 6406 // of an xor with -1. 6407 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS)) 6408 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1))) 6409 if (LBO->getOpcode() == Instruction::And && 6410 LCI->getValue() == CI->getValue()) 6411 if (const SCEVZeroExtendExpr *Z = 6412 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) { 6413 Type *UTy = BO->LHS->getType(); 6414 const SCEV *Z0 = Z->getOperand(); 6415 Type *Z0Ty = Z0->getType(); 6416 unsigned Z0TySize = getTypeSizeInBits(Z0Ty); 6417 6418 // If C is a low-bits mask, the zero extend is serving to 6419 // mask off the high bits. Complement the operand and 6420 // re-apply the zext. 6421 if (CI->getValue().isMask(Z0TySize)) 6422 return getZeroExtendExpr(getNotSCEV(Z0), UTy); 6423 6424 // If C is a single bit, it may be in the sign-bit position 6425 // before the zero-extend. In this case, represent the xor 6426 // using an add, which is equivalent, and re-apply the zext. 6427 APInt Trunc = CI->getValue().trunc(Z0TySize); 6428 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() && 6429 Trunc.isSignMask()) 6430 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)), 6431 UTy); 6432 } 6433 } 6434 break; 6435 6436 case Instruction::Shl: 6437 // Turn shift left of a constant amount into a multiply. 6438 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) { 6439 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth(); 6440 6441 // If the shift count is not less than the bitwidth, the result of 6442 // the shift is undefined. Don't try to analyze it, because the 6443 // resolution chosen here may differ from the resolution chosen in 6444 // other parts of the compiler. 6445 if (SA->getValue().uge(BitWidth)) 6446 break; 6447 6448 // We can safely preserve the nuw flag in all cases. It's also safe to 6449 // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation 6450 // requires special handling. It can be preserved as long as we're not 6451 // left shifting by bitwidth - 1. 6452 auto Flags = SCEV::FlagAnyWrap; 6453 if (BO->Op) { 6454 auto MulFlags = getNoWrapFlagsFromUB(BO->Op); 6455 if ((MulFlags & SCEV::FlagNSW) && 6456 ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1))) 6457 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW); 6458 if (MulFlags & SCEV::FlagNUW) 6459 Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW); 6460 } 6461 6462 Constant *X = ConstantInt::get( 6463 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue())); 6464 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags); 6465 } 6466 break; 6467 6468 case Instruction::AShr: { 6469 // AShr X, C, where C is a constant. 6470 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS); 6471 if (!CI) 6472 break; 6473 6474 Type *OuterTy = BO->LHS->getType(); 6475 uint64_t BitWidth = getTypeSizeInBits(OuterTy); 6476 // If the shift count is not less than the bitwidth, the result of 6477 // the shift is undefined. Don't try to analyze it, because the 6478 // resolution chosen here may differ from the resolution chosen in 6479 // other parts of the compiler. 6480 if (CI->getValue().uge(BitWidth)) 6481 break; 6482 6483 if (CI->isZero()) 6484 return getSCEV(BO->LHS); // shift by zero --> noop 6485 6486 uint64_t AShrAmt = CI->getZExtValue(); 6487 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt); 6488 6489 Operator *L = dyn_cast<Operator>(BO->LHS); 6490 if (L && L->getOpcode() == Instruction::Shl) { 6491 // X = Shl A, n 6492 // Y = AShr X, m 6493 // Both n and m are constant. 6494 6495 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0)); 6496 if (L->getOperand(1) == BO->RHS) 6497 // For a two-shift sext-inreg, i.e. n = m, 6498 // use sext(trunc(x)) as the SCEV expression. 6499 return getSignExtendExpr( 6500 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy); 6501 6502 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1)); 6503 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) { 6504 uint64_t ShlAmt = ShlAmtCI->getZExtValue(); 6505 if (ShlAmt > AShrAmt) { 6506 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV 6507 // expression. We already checked that ShlAmt < BitWidth, so 6508 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as 6509 // ShlAmt - AShrAmt < Amt. 6510 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt, 6511 ShlAmt - AShrAmt); 6512 return getSignExtendExpr( 6513 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy), 6514 getConstant(Mul)), OuterTy); 6515 } 6516 } 6517 } 6518 if (BO->IsExact) { 6519 // Given exact arithmetic in-bounds right-shift by a constant, 6520 // we can lower it into: (abs(x) EXACT/u (1<<C)) * signum(x) 6521 const SCEV *X = getSCEV(BO->LHS); 6522 const SCEV *AbsX = getAbsExpr(X, /*IsNSW=*/false); 6523 APInt Mult = APInt::getOneBitSet(BitWidth, AShrAmt); 6524 const SCEV *Div = getUDivExactExpr(AbsX, getConstant(Mult)); 6525 return getMulExpr(Div, getSignumExpr(X), SCEV::FlagNSW); 6526 } 6527 break; 6528 } 6529 } 6530 } 6531 6532 switch (U->getOpcode()) { 6533 case Instruction::Trunc: 6534 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType()); 6535 6536 case Instruction::ZExt: 6537 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6538 6539 case Instruction::SExt: 6540 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) { 6541 // The NSW flag of a subtract does not always survive the conversion to 6542 // A + (-1)*B. By pushing sign extension onto its operands we are much 6543 // more likely to preserve NSW and allow later AddRec optimisations. 6544 // 6545 // NOTE: This is effectively duplicating this logic from getSignExtend: 6546 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw> 6547 // but by that point the NSW information has potentially been lost. 6548 if (BO->Opcode == Instruction::Sub && BO->IsNSW) { 6549 Type *Ty = U->getType(); 6550 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty); 6551 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty); 6552 return getMinusSCEV(V1, V2, SCEV::FlagNSW); 6553 } 6554 } 6555 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType()); 6556 6557 case Instruction::BitCast: 6558 // BitCasts are no-op casts so we just eliminate the cast. 6559 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) 6560 return getSCEV(U->getOperand(0)); 6561 break; 6562 6563 case Instruction::PtrToInt: { 6564 // Pointer to integer cast is straight-forward, so do model it. 6565 Value *Ptr = U->getOperand(0); 6566 const SCEV *Op = getSCEV(Ptr); 6567 Type *DstIntTy = U->getType(); 6568 // SCEV doesn't have constant pointer expression type, but it supports 6569 // nullptr constant (and only that one), which is modelled in SCEV as a 6570 // zero integer constant. So just skip the ptrtoint cast for constants. 6571 if (isa<SCEVConstant>(Op)) 6572 return getTruncateOrZeroExtend(Op, DstIntTy); 6573 Type *PtrTy = Ptr->getType(); 6574 Type *IntPtrTy = getDataLayout().getIntPtrType(PtrTy); 6575 // But only if effective SCEV (integer) type is wide enough to represent 6576 // all possible pointer values. 6577 if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(PtrTy)) != 6578 getDataLayout().getTypeSizeInBits(IntPtrTy)) 6579 return getUnknown(V); 6580 return getPtrToIntExpr(Op, DstIntTy); 6581 } 6582 case Instruction::IntToPtr: 6583 // Just don't deal with inttoptr casts. 6584 return getUnknown(V); 6585 6586 case Instruction::SDiv: 6587 // If both operands are non-negative, this is just an udiv. 6588 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6589 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6590 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6591 break; 6592 6593 case Instruction::SRem: 6594 // If both operands are non-negative, this is just an urem. 6595 if (isKnownNonNegative(getSCEV(U->getOperand(0))) && 6596 isKnownNonNegative(getSCEV(U->getOperand(1)))) 6597 return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1))); 6598 break; 6599 6600 case Instruction::GetElementPtr: 6601 return createNodeForGEP(cast<GEPOperator>(U)); 6602 6603 case Instruction::PHI: 6604 return createNodeForPHI(cast<PHINode>(U)); 6605 6606 case Instruction::Select: 6607 // U can also be a select constant expr, which let fall through. Since 6608 // createNodeForSelect only works for a condition that is an `ICmpInst`, and 6609 // constant expressions cannot have instructions as operands, we'd have 6610 // returned getUnknown for a select constant expressions anyway. 6611 if (isa<Instruction>(U)) 6612 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0), 6613 U->getOperand(1), U->getOperand(2)); 6614 break; 6615 6616 case Instruction::Call: 6617 case Instruction::Invoke: 6618 if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) 6619 return getSCEV(RV); 6620 6621 if (auto *II = dyn_cast<IntrinsicInst>(U)) { 6622 switch (II->getIntrinsicID()) { 6623 case Intrinsic::abs: 6624 return getAbsExpr( 6625 getSCEV(II->getArgOperand(0)), 6626 /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne()); 6627 case Intrinsic::umax: 6628 return getUMaxExpr(getSCEV(II->getArgOperand(0)), 6629 getSCEV(II->getArgOperand(1))); 6630 case Intrinsic::umin: 6631 return getUMinExpr(getSCEV(II->getArgOperand(0)), 6632 getSCEV(II->getArgOperand(1))); 6633 case Intrinsic::smax: 6634 return getSMaxExpr(getSCEV(II->getArgOperand(0)), 6635 getSCEV(II->getArgOperand(1))); 6636 case Intrinsic::smin: 6637 return getSMinExpr(getSCEV(II->getArgOperand(0)), 6638 getSCEV(II->getArgOperand(1))); 6639 case Intrinsic::usub_sat: { 6640 const SCEV *X = getSCEV(II->getArgOperand(0)); 6641 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6642 const SCEV *ClampedY = getUMinExpr(X, Y); 6643 return getMinusSCEV(X, ClampedY, SCEV::FlagNUW); 6644 } 6645 case Intrinsic::uadd_sat: { 6646 const SCEV *X = getSCEV(II->getArgOperand(0)); 6647 const SCEV *Y = getSCEV(II->getArgOperand(1)); 6648 const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y)); 6649 return getAddExpr(ClampedX, Y, SCEV::FlagNUW); 6650 } 6651 default: 6652 break; 6653 } 6654 } 6655 break; 6656 } 6657 6658 return getUnknown(V); 6659 } 6660 6661 //===----------------------------------------------------------------------===// 6662 // Iteration Count Computation Code 6663 // 6664 6665 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) { 6666 if (!ExitCount) 6667 return 0; 6668 6669 ConstantInt *ExitConst = ExitCount->getValue(); 6670 6671 // Guard against huge trip counts. 6672 if (ExitConst->getValue().getActiveBits() > 32) 6673 return 0; 6674 6675 // In case of integer overflow, this returns 0, which is correct. 6676 return ((unsigned)ExitConst->getZExtValue()) + 1; 6677 } 6678 6679 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) { 6680 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6681 return getSmallConstantTripCount(L, ExitingBB); 6682 6683 // No trip count information for multiple exits. 6684 return 0; 6685 } 6686 6687 unsigned 6688 ScalarEvolution::getSmallConstantTripCount(const Loop *L, 6689 const BasicBlock *ExitingBlock) { 6690 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6691 assert(L->isLoopExiting(ExitingBlock) && 6692 "Exiting block must actually branch out of the loop!"); 6693 const SCEVConstant *ExitCount = 6694 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock)); 6695 return getConstantTripCount(ExitCount); 6696 } 6697 6698 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) { 6699 const auto *MaxExitCount = 6700 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L)); 6701 return getConstantTripCount(MaxExitCount); 6702 } 6703 6704 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) { 6705 if (BasicBlock *ExitingBB = L->getExitingBlock()) 6706 return getSmallConstantTripMultiple(L, ExitingBB); 6707 6708 // No trip multiple information for multiple exits. 6709 return 0; 6710 } 6711 6712 /// Returns the largest constant divisor of the trip count of this loop as a 6713 /// normal unsigned value, if possible. This means that the actual trip count is 6714 /// always a multiple of the returned value (don't forget the trip count could 6715 /// very well be zero as well!). 6716 /// 6717 /// Returns 1 if the trip count is unknown or not guaranteed to be the 6718 /// multiple of a constant (which is also the case if the trip count is simply 6719 /// constant, use getSmallConstantTripCount for that case), Will also return 1 6720 /// if the trip count is very large (>= 2^32). 6721 /// 6722 /// As explained in the comments for getSmallConstantTripCount, this assumes 6723 /// that control exits the loop via ExitingBlock. 6724 unsigned 6725 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L, 6726 const BasicBlock *ExitingBlock) { 6727 assert(ExitingBlock && "Must pass a non-null exiting block!"); 6728 assert(L->isLoopExiting(ExitingBlock) && 6729 "Exiting block must actually branch out of the loop!"); 6730 const SCEV *ExitCount = getExitCount(L, ExitingBlock); 6731 if (ExitCount == getCouldNotCompute()) 6732 return 1; 6733 6734 // Get the trip count from the BE count by adding 1. 6735 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType())); 6736 6737 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr); 6738 if (!TC) 6739 // Attempt to factor more general cases. Returns the greatest power of 6740 // two divisor. If overflow happens, the trip count expression is still 6741 // divisible by the greatest power of 2 divisor returned. 6742 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr)); 6743 6744 ConstantInt *Result = TC->getValue(); 6745 6746 // Guard against huge trip counts (this requires checking 6747 // for zero to handle the case where the trip count == -1 and the 6748 // addition wraps). 6749 if (!Result || Result->getValue().getActiveBits() > 32 || 6750 Result->getValue().getActiveBits() == 0) 6751 return 1; 6752 6753 return (unsigned)Result->getZExtValue(); 6754 } 6755 6756 const SCEV *ScalarEvolution::getExitCount(const Loop *L, 6757 const BasicBlock *ExitingBlock, 6758 ExitCountKind Kind) { 6759 switch (Kind) { 6760 case Exact: 6761 case SymbolicMaximum: 6762 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this); 6763 case ConstantMaximum: 6764 return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this); 6765 }; 6766 llvm_unreachable("Invalid ExitCountKind!"); 6767 } 6768 6769 const SCEV * 6770 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L, 6771 SCEVUnionPredicate &Preds) { 6772 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds); 6773 } 6774 6775 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L, 6776 ExitCountKind Kind) { 6777 switch (Kind) { 6778 case Exact: 6779 return getBackedgeTakenInfo(L).getExact(L, this); 6780 case ConstantMaximum: 6781 return getBackedgeTakenInfo(L).getConstantMax(this); 6782 case SymbolicMaximum: 6783 return getBackedgeTakenInfo(L).getSymbolicMax(L, this); 6784 }; 6785 llvm_unreachable("Invalid ExitCountKind!"); 6786 } 6787 6788 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) { 6789 return getBackedgeTakenInfo(L).isConstantMaxOrZero(this); 6790 } 6791 6792 /// Push PHI nodes in the header of the given loop onto the given Worklist. 6793 static void 6794 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) { 6795 BasicBlock *Header = L->getHeader(); 6796 6797 // Push all Loop-header PHIs onto the Worklist stack. 6798 for (PHINode &PN : Header->phis()) 6799 Worklist.push_back(&PN); 6800 } 6801 6802 const ScalarEvolution::BackedgeTakenInfo & 6803 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) { 6804 auto &BTI = getBackedgeTakenInfo(L); 6805 if (BTI.hasFullInfo()) 6806 return BTI; 6807 6808 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6809 6810 if (!Pair.second) 6811 return Pair.first->second; 6812 6813 BackedgeTakenInfo Result = 6814 computeBackedgeTakenCount(L, /*AllowPredicates=*/true); 6815 6816 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result); 6817 } 6818 6819 ScalarEvolution::BackedgeTakenInfo & 6820 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) { 6821 // Initially insert an invalid entry for this loop. If the insertion 6822 // succeeds, proceed to actually compute a backedge-taken count and 6823 // update the value. The temporary CouldNotCompute value tells SCEV 6824 // code elsewhere that it shouldn't attempt to request a new 6825 // backedge-taken count, which could result in infinite recursion. 6826 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair = 6827 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()}); 6828 if (!Pair.second) 6829 return Pair.first->second; 6830 6831 // computeBackedgeTakenCount may allocate memory for its result. Inserting it 6832 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result 6833 // must be cleared in this scope. 6834 BackedgeTakenInfo Result = computeBackedgeTakenCount(L); 6835 6836 // In product build, there are no usage of statistic. 6837 (void)NumTripCountsComputed; 6838 (void)NumTripCountsNotComputed; 6839 #if LLVM_ENABLE_STATS || !defined(NDEBUG) 6840 const SCEV *BEExact = Result.getExact(L, this); 6841 if (BEExact != getCouldNotCompute()) { 6842 assert(isLoopInvariant(BEExact, L) && 6843 isLoopInvariant(Result.getConstantMax(this), L) && 6844 "Computed backedge-taken count isn't loop invariant for loop!"); 6845 ++NumTripCountsComputed; 6846 } else if (Result.getConstantMax(this) == getCouldNotCompute() && 6847 isa<PHINode>(L->getHeader()->begin())) { 6848 // Only count loops that have phi nodes as not being computable. 6849 ++NumTripCountsNotComputed; 6850 } 6851 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG) 6852 6853 // Now that we know more about the trip count for this loop, forget any 6854 // existing SCEV values for PHI nodes in this loop since they are only 6855 // conservative estimates made without the benefit of trip count 6856 // information. This is similar to the code in forgetLoop, except that 6857 // it handles SCEVUnknown PHI nodes specially. 6858 if (Result.hasAnyInfo()) { 6859 SmallVector<Instruction *, 16> Worklist; 6860 PushLoopPHIs(L, Worklist); 6861 6862 SmallPtrSet<Instruction *, 8> Discovered; 6863 while (!Worklist.empty()) { 6864 Instruction *I = Worklist.pop_back_val(); 6865 6866 ValueExprMapType::iterator It = 6867 ValueExprMap.find_as(static_cast<Value *>(I)); 6868 if (It != ValueExprMap.end()) { 6869 const SCEV *Old = It->second; 6870 6871 // SCEVUnknown for a PHI either means that it has an unrecognized 6872 // structure, or it's a PHI that's in the progress of being computed 6873 // by createNodeForPHI. In the former case, additional loop trip 6874 // count information isn't going to change anything. In the later 6875 // case, createNodeForPHI will perform the necessary updates on its 6876 // own when it gets to that point. 6877 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) { 6878 eraseValueFromMap(It->first); 6879 forgetMemoizedResults(Old); 6880 } 6881 if (PHINode *PN = dyn_cast<PHINode>(I)) 6882 ConstantEvolutionLoopExitValue.erase(PN); 6883 } 6884 6885 // Since we don't need to invalidate anything for correctness and we're 6886 // only invalidating to make SCEV's results more precise, we get to stop 6887 // early to avoid invalidating too much. This is especially important in 6888 // cases like: 6889 // 6890 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node 6891 // loop0: 6892 // %pn0 = phi 6893 // ... 6894 // loop1: 6895 // %pn1 = phi 6896 // ... 6897 // 6898 // where both loop0 and loop1's backedge taken count uses the SCEV 6899 // expression for %v. If we don't have the early stop below then in cases 6900 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip 6901 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip 6902 // count for loop1, effectively nullifying SCEV's trip count cache. 6903 for (auto *U : I->users()) 6904 if (auto *I = dyn_cast<Instruction>(U)) { 6905 auto *LoopForUser = LI.getLoopFor(I->getParent()); 6906 if (LoopForUser && L->contains(LoopForUser) && 6907 Discovered.insert(I).second) 6908 Worklist.push_back(I); 6909 } 6910 } 6911 } 6912 6913 // Re-lookup the insert position, since the call to 6914 // computeBackedgeTakenCount above could result in a 6915 // recusive call to getBackedgeTakenInfo (on a different 6916 // loop), which would invalidate the iterator computed 6917 // earlier. 6918 return BackedgeTakenCounts.find(L)->second = std::move(Result); 6919 } 6920 6921 void ScalarEvolution::forgetAllLoops() { 6922 // This method is intended to forget all info about loops. It should 6923 // invalidate caches as if the following happened: 6924 // - The trip counts of all loops have changed arbitrarily 6925 // - Every llvm::Value has been updated in place to produce a different 6926 // result. 6927 BackedgeTakenCounts.clear(); 6928 PredicatedBackedgeTakenCounts.clear(); 6929 LoopPropertiesCache.clear(); 6930 ConstantEvolutionLoopExitValue.clear(); 6931 ValueExprMap.clear(); 6932 ValuesAtScopes.clear(); 6933 LoopDispositions.clear(); 6934 BlockDispositions.clear(); 6935 UnsignedRanges.clear(); 6936 SignedRanges.clear(); 6937 ExprValueMap.clear(); 6938 HasRecMap.clear(); 6939 MinTrailingZerosCache.clear(); 6940 PredicatedSCEVRewrites.clear(); 6941 } 6942 6943 void ScalarEvolution::forgetLoop(const Loop *L) { 6944 // Drop any stored trip count value. 6945 auto RemoveLoopFromBackedgeMap = 6946 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) { 6947 auto BTCPos = Map.find(L); 6948 if (BTCPos != Map.end()) { 6949 BTCPos->second.clear(); 6950 Map.erase(BTCPos); 6951 } 6952 }; 6953 6954 SmallVector<const Loop *, 16> LoopWorklist(1, L); 6955 SmallVector<Instruction *, 32> Worklist; 6956 SmallPtrSet<Instruction *, 16> Visited; 6957 6958 // Iterate over all the loops and sub-loops to drop SCEV information. 6959 while (!LoopWorklist.empty()) { 6960 auto *CurrL = LoopWorklist.pop_back_val(); 6961 6962 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL); 6963 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL); 6964 6965 // Drop information about predicated SCEV rewrites for this loop. 6966 for (auto I = PredicatedSCEVRewrites.begin(); 6967 I != PredicatedSCEVRewrites.end();) { 6968 std::pair<const SCEV *, const Loop *> Entry = I->first; 6969 if (Entry.second == CurrL) 6970 PredicatedSCEVRewrites.erase(I++); 6971 else 6972 ++I; 6973 } 6974 6975 auto LoopUsersItr = LoopUsers.find(CurrL); 6976 if (LoopUsersItr != LoopUsers.end()) { 6977 for (auto *S : LoopUsersItr->second) 6978 forgetMemoizedResults(S); 6979 LoopUsers.erase(LoopUsersItr); 6980 } 6981 6982 // Drop information about expressions based on loop-header PHIs. 6983 PushLoopPHIs(CurrL, Worklist); 6984 6985 while (!Worklist.empty()) { 6986 Instruction *I = Worklist.pop_back_val(); 6987 if (!Visited.insert(I).second) 6988 continue; 6989 6990 ValueExprMapType::iterator It = 6991 ValueExprMap.find_as(static_cast<Value *>(I)); 6992 if (It != ValueExprMap.end()) { 6993 eraseValueFromMap(It->first); 6994 forgetMemoizedResults(It->second); 6995 if (PHINode *PN = dyn_cast<PHINode>(I)) 6996 ConstantEvolutionLoopExitValue.erase(PN); 6997 } 6998 6999 PushDefUseChildren(I, Worklist); 7000 } 7001 7002 LoopPropertiesCache.erase(CurrL); 7003 // Forget all contained loops too, to avoid dangling entries in the 7004 // ValuesAtScopes map. 7005 LoopWorklist.append(CurrL->begin(), CurrL->end()); 7006 } 7007 } 7008 7009 void ScalarEvolution::forgetTopmostLoop(const Loop *L) { 7010 while (Loop *Parent = L->getParentLoop()) 7011 L = Parent; 7012 forgetLoop(L); 7013 } 7014 7015 void ScalarEvolution::forgetValue(Value *V) { 7016 Instruction *I = dyn_cast<Instruction>(V); 7017 if (!I) return; 7018 7019 // Drop information about expressions based on loop-header PHIs. 7020 SmallVector<Instruction *, 16> Worklist; 7021 Worklist.push_back(I); 7022 7023 SmallPtrSet<Instruction *, 8> Visited; 7024 while (!Worklist.empty()) { 7025 I = Worklist.pop_back_val(); 7026 if (!Visited.insert(I).second) 7027 continue; 7028 7029 ValueExprMapType::iterator It = 7030 ValueExprMap.find_as(static_cast<Value *>(I)); 7031 if (It != ValueExprMap.end()) { 7032 eraseValueFromMap(It->first); 7033 forgetMemoizedResults(It->second); 7034 if (PHINode *PN = dyn_cast<PHINode>(I)) 7035 ConstantEvolutionLoopExitValue.erase(PN); 7036 } 7037 7038 PushDefUseChildren(I, Worklist); 7039 } 7040 } 7041 7042 void ScalarEvolution::forgetLoopDispositions(const Loop *L) { 7043 LoopDispositions.clear(); 7044 } 7045 7046 /// Get the exact loop backedge taken count considering all loop exits. A 7047 /// computable result can only be returned for loops with all exiting blocks 7048 /// dominating the latch. howFarToZero assumes that the limit of each loop test 7049 /// is never skipped. This is a valid assumption as long as the loop exits via 7050 /// that test. For precise results, it is the caller's responsibility to specify 7051 /// the relevant loop exiting block using getExact(ExitingBlock, SE). 7052 const SCEV * 7053 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE, 7054 SCEVUnionPredicate *Preds) const { 7055 // If any exits were not computable, the loop is not computable. 7056 if (!isComplete() || ExitNotTaken.empty()) 7057 return SE->getCouldNotCompute(); 7058 7059 const BasicBlock *Latch = L->getLoopLatch(); 7060 // All exiting blocks we have collected must dominate the only backedge. 7061 if (!Latch) 7062 return SE->getCouldNotCompute(); 7063 7064 // All exiting blocks we have gathered dominate loop's latch, so exact trip 7065 // count is simply a minimum out of all these calculated exit counts. 7066 SmallVector<const SCEV *, 2> Ops; 7067 for (auto &ENT : ExitNotTaken) { 7068 const SCEV *BECount = ENT.ExactNotTaken; 7069 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!"); 7070 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) && 7071 "We should only have known counts for exiting blocks that dominate " 7072 "latch!"); 7073 7074 Ops.push_back(BECount); 7075 7076 if (Preds && !ENT.hasAlwaysTruePredicate()) 7077 Preds->add(ENT.Predicate.get()); 7078 7079 assert((Preds || ENT.hasAlwaysTruePredicate()) && 7080 "Predicate should be always true!"); 7081 } 7082 7083 return SE->getUMinFromMismatchedTypes(Ops); 7084 } 7085 7086 /// Get the exact not taken count for this loop exit. 7087 const SCEV * 7088 ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock, 7089 ScalarEvolution *SE) const { 7090 for (auto &ENT : ExitNotTaken) 7091 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7092 return ENT.ExactNotTaken; 7093 7094 return SE->getCouldNotCompute(); 7095 } 7096 7097 const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax( 7098 const BasicBlock *ExitingBlock, ScalarEvolution *SE) const { 7099 for (auto &ENT : ExitNotTaken) 7100 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate()) 7101 return ENT.MaxNotTaken; 7102 7103 return SE->getCouldNotCompute(); 7104 } 7105 7106 /// getConstantMax - Get the constant max backedge taken count for the loop. 7107 const SCEV * 7108 ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const { 7109 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7110 return !ENT.hasAlwaysTruePredicate(); 7111 }; 7112 7113 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getConstantMax()) 7114 return SE->getCouldNotCompute(); 7115 7116 assert((isa<SCEVCouldNotCompute>(getConstantMax()) || 7117 isa<SCEVConstant>(getConstantMax())) && 7118 "No point in having a non-constant max backedge taken count!"); 7119 return getConstantMax(); 7120 } 7121 7122 const SCEV * 7123 ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L, 7124 ScalarEvolution *SE) { 7125 if (!SymbolicMax) 7126 SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L); 7127 return SymbolicMax; 7128 } 7129 7130 bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero( 7131 ScalarEvolution *SE) const { 7132 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) { 7133 return !ENT.hasAlwaysTruePredicate(); 7134 }; 7135 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue); 7136 } 7137 7138 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S, 7139 ScalarEvolution *SE) const { 7140 if (getConstantMax() && getConstantMax() != SE->getCouldNotCompute() && 7141 SE->hasOperand(getConstantMax(), S)) 7142 return true; 7143 7144 for (auto &ENT : ExitNotTaken) 7145 if (ENT.ExactNotTaken != SE->getCouldNotCompute() && 7146 SE->hasOperand(ENT.ExactNotTaken, S)) 7147 return true; 7148 7149 return false; 7150 } 7151 7152 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E) 7153 : ExactNotTaken(E), MaxNotTaken(E) { 7154 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7155 isa<SCEVConstant>(MaxNotTaken)) && 7156 "No point in having a non-constant max backedge taken count!"); 7157 } 7158 7159 ScalarEvolution::ExitLimit::ExitLimit( 7160 const SCEV *E, const SCEV *M, bool MaxOrZero, 7161 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList) 7162 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) { 7163 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) || 7164 !isa<SCEVCouldNotCompute>(MaxNotTaken)) && 7165 "Exact is not allowed to be less precise than Max"); 7166 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7167 isa<SCEVConstant>(MaxNotTaken)) && 7168 "No point in having a non-constant max backedge taken count!"); 7169 for (auto *PredSet : PredSetList) 7170 for (auto *P : *PredSet) 7171 addPredicate(P); 7172 } 7173 7174 ScalarEvolution::ExitLimit::ExitLimit( 7175 const SCEV *E, const SCEV *M, bool MaxOrZero, 7176 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet) 7177 : ExitLimit(E, M, MaxOrZero, {&PredSet}) { 7178 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7179 isa<SCEVConstant>(MaxNotTaken)) && 7180 "No point in having a non-constant max backedge taken count!"); 7181 } 7182 7183 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M, 7184 bool MaxOrZero) 7185 : ExitLimit(E, M, MaxOrZero, None) { 7186 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) || 7187 isa<SCEVConstant>(MaxNotTaken)) && 7188 "No point in having a non-constant max backedge taken count!"); 7189 } 7190 7191 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each 7192 /// computable exit into a persistent ExitNotTakenInfo array. 7193 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo( 7194 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts, 7195 bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero) 7196 : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) { 7197 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7198 7199 ExitNotTaken.reserve(ExitCounts.size()); 7200 std::transform( 7201 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken), 7202 [&](const EdgeExitInfo &EEI) { 7203 BasicBlock *ExitBB = EEI.first; 7204 const ExitLimit &EL = EEI.second; 7205 if (EL.Predicates.empty()) 7206 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7207 nullptr); 7208 7209 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate); 7210 for (auto *Pred : EL.Predicates) 7211 Predicate->add(Pred); 7212 7213 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, EL.MaxNotTaken, 7214 std::move(Predicate)); 7215 }); 7216 assert((isa<SCEVCouldNotCompute>(ConstantMax) || 7217 isa<SCEVConstant>(ConstantMax)) && 7218 "No point in having a non-constant max backedge taken count!"); 7219 } 7220 7221 /// Invalidate this result and free the ExitNotTakenInfo array. 7222 void ScalarEvolution::BackedgeTakenInfo::clear() { 7223 ExitNotTaken.clear(); 7224 } 7225 7226 /// Compute the number of times the backedge of the specified loop will execute. 7227 ScalarEvolution::BackedgeTakenInfo 7228 ScalarEvolution::computeBackedgeTakenCount(const Loop *L, 7229 bool AllowPredicates) { 7230 SmallVector<BasicBlock *, 8> ExitingBlocks; 7231 L->getExitingBlocks(ExitingBlocks); 7232 7233 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo; 7234 7235 SmallVector<EdgeExitInfo, 4> ExitCounts; 7236 bool CouldComputeBECount = true; 7237 BasicBlock *Latch = L->getLoopLatch(); // may be NULL. 7238 const SCEV *MustExitMaxBECount = nullptr; 7239 const SCEV *MayExitMaxBECount = nullptr; 7240 bool MustExitMaxOrZero = false; 7241 7242 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts 7243 // and compute maxBECount. 7244 // Do a union of all the predicates here. 7245 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 7246 BasicBlock *ExitBB = ExitingBlocks[i]; 7247 7248 // We canonicalize untaken exits to br (constant), ignore them so that 7249 // proving an exit untaken doesn't negatively impact our ability to reason 7250 // about the loop as whole. 7251 if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator())) 7252 if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) { 7253 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7254 if ((ExitIfTrue && CI->isZero()) || (!ExitIfTrue && CI->isOne())) 7255 continue; 7256 } 7257 7258 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates); 7259 7260 assert((AllowPredicates || EL.Predicates.empty()) && 7261 "Predicated exit limit when predicates are not allowed!"); 7262 7263 // 1. For each exit that can be computed, add an entry to ExitCounts. 7264 // CouldComputeBECount is true only if all exits can be computed. 7265 if (EL.ExactNotTaken == getCouldNotCompute()) 7266 // We couldn't compute an exact value for this exit, so 7267 // we won't be able to compute an exact value for the loop. 7268 CouldComputeBECount = false; 7269 else 7270 ExitCounts.emplace_back(ExitBB, EL); 7271 7272 // 2. Derive the loop's MaxBECount from each exit's max number of 7273 // non-exiting iterations. Partition the loop exits into two kinds: 7274 // LoopMustExits and LoopMayExits. 7275 // 7276 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it 7277 // is a LoopMayExit. If any computable LoopMustExit is found, then 7278 // MaxBECount is the minimum EL.MaxNotTaken of computable 7279 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum 7280 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any 7281 // computable EL.MaxNotTaken. 7282 if (EL.MaxNotTaken != getCouldNotCompute() && Latch && 7283 DT.dominates(ExitBB, Latch)) { 7284 if (!MustExitMaxBECount) { 7285 MustExitMaxBECount = EL.MaxNotTaken; 7286 MustExitMaxOrZero = EL.MaxOrZero; 7287 } else { 7288 MustExitMaxBECount = 7289 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken); 7290 } 7291 } else if (MayExitMaxBECount != getCouldNotCompute()) { 7292 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute()) 7293 MayExitMaxBECount = EL.MaxNotTaken; 7294 else { 7295 MayExitMaxBECount = 7296 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken); 7297 } 7298 } 7299 } 7300 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount : 7301 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute()); 7302 // The loop backedge will be taken the maximum or zero times if there's 7303 // a single exit that must be taken the maximum or zero times. 7304 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1); 7305 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount, 7306 MaxBECount, MaxOrZero); 7307 } 7308 7309 ScalarEvolution::ExitLimit 7310 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock, 7311 bool AllowPredicates) { 7312 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?"); 7313 // If our exiting block does not dominate the latch, then its connection with 7314 // loop's exit limit may be far from trivial. 7315 const BasicBlock *Latch = L->getLoopLatch(); 7316 if (!Latch || !DT.dominates(ExitingBlock, Latch)) 7317 return getCouldNotCompute(); 7318 7319 bool IsOnlyExit = (L->getExitingBlock() != nullptr); 7320 Instruction *Term = ExitingBlock->getTerminator(); 7321 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) { 7322 assert(BI->isConditional() && "If unconditional, it can't be in loop!"); 7323 bool ExitIfTrue = !L->contains(BI->getSuccessor(0)); 7324 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) && 7325 "It should have one successor in loop and one exit block!"); 7326 // Proceed to the next level to examine the exit condition expression. 7327 return computeExitLimitFromCond( 7328 L, BI->getCondition(), ExitIfTrue, 7329 /*ControlsExit=*/IsOnlyExit, AllowPredicates); 7330 } 7331 7332 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 7333 // For switch, make sure that there is a single exit from the loop. 7334 BasicBlock *Exit = nullptr; 7335 for (auto *SBB : successors(ExitingBlock)) 7336 if (!L->contains(SBB)) { 7337 if (Exit) // Multiple exit successors. 7338 return getCouldNotCompute(); 7339 Exit = SBB; 7340 } 7341 assert(Exit && "Exiting block must have at least one exit"); 7342 return computeExitLimitFromSingleExitSwitch(L, SI, Exit, 7343 /*ControlsExit=*/IsOnlyExit); 7344 } 7345 7346 return getCouldNotCompute(); 7347 } 7348 7349 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond( 7350 const Loop *L, Value *ExitCond, bool ExitIfTrue, 7351 bool ControlsExit, bool AllowPredicates) { 7352 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates); 7353 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue, 7354 ControlsExit, AllowPredicates); 7355 } 7356 7357 Optional<ScalarEvolution::ExitLimit> 7358 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond, 7359 bool ExitIfTrue, bool ControlsExit, 7360 bool AllowPredicates) { 7361 (void)this->L; 7362 (void)this->ExitIfTrue; 7363 (void)this->AllowPredicates; 7364 7365 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7366 this->AllowPredicates == AllowPredicates && 7367 "Variance in assumed invariant key components!"); 7368 auto Itr = TripCountMap.find({ExitCond, ControlsExit}); 7369 if (Itr == TripCountMap.end()) 7370 return None; 7371 return Itr->second; 7372 } 7373 7374 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond, 7375 bool ExitIfTrue, 7376 bool ControlsExit, 7377 bool AllowPredicates, 7378 const ExitLimit &EL) { 7379 assert(this->L == L && this->ExitIfTrue == ExitIfTrue && 7380 this->AllowPredicates == AllowPredicates && 7381 "Variance in assumed invariant key components!"); 7382 7383 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL}); 7384 assert(InsertResult.second && "Expected successful insertion!"); 7385 (void)InsertResult; 7386 (void)ExitIfTrue; 7387 } 7388 7389 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached( 7390 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7391 bool ControlsExit, bool AllowPredicates) { 7392 7393 if (auto MaybeEL = 7394 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates)) 7395 return *MaybeEL; 7396 7397 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue, 7398 ControlsExit, AllowPredicates); 7399 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL); 7400 return EL; 7401 } 7402 7403 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl( 7404 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue, 7405 bool ControlsExit, bool AllowPredicates) { 7406 // Check if the controlling expression for this loop is an And or Or. 7407 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) { 7408 if (BO->getOpcode() == Instruction::And) { 7409 // Recurse on the operands of the and. 7410 bool EitherMayExit = !ExitIfTrue; 7411 ExitLimit EL0 = computeExitLimitFromCondCached( 7412 Cache, L, BO->getOperand(0), ExitIfTrue, 7413 ControlsExit && !EitherMayExit, AllowPredicates); 7414 ExitLimit EL1 = computeExitLimitFromCondCached( 7415 Cache, L, BO->getOperand(1), ExitIfTrue, 7416 ControlsExit && !EitherMayExit, AllowPredicates); 7417 // Be robust against unsimplified IR for the form "and i1 X, true" 7418 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7419 return CI->isOne() ? EL0 : EL1; 7420 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7421 return CI->isOne() ? EL1 : EL0; 7422 const SCEV *BECount = getCouldNotCompute(); 7423 const SCEV *MaxBECount = getCouldNotCompute(); 7424 if (EitherMayExit) { 7425 // Both conditions must be true for the loop to continue executing. 7426 // Choose the less conservative count. 7427 if (EL0.ExactNotTaken == getCouldNotCompute() || 7428 EL1.ExactNotTaken == getCouldNotCompute()) 7429 BECount = getCouldNotCompute(); 7430 else 7431 BECount = 7432 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7433 if (EL0.MaxNotTaken == getCouldNotCompute()) 7434 MaxBECount = EL1.MaxNotTaken; 7435 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7436 MaxBECount = EL0.MaxNotTaken; 7437 else 7438 MaxBECount = 7439 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7440 } else { 7441 // Both conditions must be true at the same time for the loop to exit. 7442 // For now, be conservative. 7443 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7444 MaxBECount = EL0.MaxNotTaken; 7445 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7446 BECount = EL0.ExactNotTaken; 7447 } 7448 7449 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7450 // to be more aggressive when computing BECount than when computing 7451 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7452 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7453 // to not. 7454 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7455 !isa<SCEVCouldNotCompute>(BECount)) 7456 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7457 7458 return ExitLimit(BECount, MaxBECount, false, 7459 {&EL0.Predicates, &EL1.Predicates}); 7460 } 7461 if (BO->getOpcode() == Instruction::Or) { 7462 // Recurse on the operands of the or. 7463 bool EitherMayExit = ExitIfTrue; 7464 ExitLimit EL0 = computeExitLimitFromCondCached( 7465 Cache, L, BO->getOperand(0), ExitIfTrue, 7466 ControlsExit && !EitherMayExit, AllowPredicates); 7467 ExitLimit EL1 = computeExitLimitFromCondCached( 7468 Cache, L, BO->getOperand(1), ExitIfTrue, 7469 ControlsExit && !EitherMayExit, AllowPredicates); 7470 // Be robust against unsimplified IR for the form "or i1 X, true" 7471 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) 7472 return CI->isZero() ? EL0 : EL1; 7473 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(0))) 7474 return CI->isZero() ? EL1 : EL0; 7475 const SCEV *BECount = getCouldNotCompute(); 7476 const SCEV *MaxBECount = getCouldNotCompute(); 7477 if (EitherMayExit) { 7478 // Both conditions must be false for the loop to continue executing. 7479 // Choose the less conservative count. 7480 if (EL0.ExactNotTaken == getCouldNotCompute() || 7481 EL1.ExactNotTaken == getCouldNotCompute()) 7482 BECount = getCouldNotCompute(); 7483 else 7484 BECount = 7485 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken); 7486 if (EL0.MaxNotTaken == getCouldNotCompute()) 7487 MaxBECount = EL1.MaxNotTaken; 7488 else if (EL1.MaxNotTaken == getCouldNotCompute()) 7489 MaxBECount = EL0.MaxNotTaken; 7490 else 7491 MaxBECount = 7492 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken); 7493 } else { 7494 // Both conditions must be false at the same time for the loop to exit. 7495 // For now, be conservative. 7496 if (EL0.MaxNotTaken == EL1.MaxNotTaken) 7497 MaxBECount = EL0.MaxNotTaken; 7498 if (EL0.ExactNotTaken == EL1.ExactNotTaken) 7499 BECount = EL0.ExactNotTaken; 7500 } 7501 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able 7502 // to be more aggressive when computing BECount than when computing 7503 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and 7504 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken 7505 // to not. 7506 if (isa<SCEVCouldNotCompute>(MaxBECount) && 7507 !isa<SCEVCouldNotCompute>(BECount)) 7508 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 7509 7510 return ExitLimit(BECount, MaxBECount, false, 7511 {&EL0.Predicates, &EL1.Predicates}); 7512 } 7513 } 7514 7515 // With an icmp, it may be feasible to compute an exact backedge-taken count. 7516 // Proceed to the next level to examine the icmp. 7517 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) { 7518 ExitLimit EL = 7519 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit); 7520 if (EL.hasFullInfo() || !AllowPredicates) 7521 return EL; 7522 7523 // Try again, but use SCEV predicates this time. 7524 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit, 7525 /*AllowPredicates=*/true); 7526 } 7527 7528 // Check for a constant condition. These are normally stripped out by 7529 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to 7530 // preserve the CFG and is temporarily leaving constant conditions 7531 // in place. 7532 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) { 7533 if (ExitIfTrue == !CI->getZExtValue()) 7534 // The backedge is always taken. 7535 return getCouldNotCompute(); 7536 else 7537 // The backedge is never taken. 7538 return getZero(CI->getType()); 7539 } 7540 7541 // If it's not an integer or pointer comparison then compute it the hard way. 7542 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7543 } 7544 7545 ScalarEvolution::ExitLimit 7546 ScalarEvolution::computeExitLimitFromICmp(const Loop *L, 7547 ICmpInst *ExitCond, 7548 bool ExitIfTrue, 7549 bool ControlsExit, 7550 bool AllowPredicates) { 7551 // If the condition was exit on true, convert the condition to exit on false 7552 ICmpInst::Predicate Pred; 7553 if (!ExitIfTrue) 7554 Pred = ExitCond->getPredicate(); 7555 else 7556 Pred = ExitCond->getInversePredicate(); 7557 const ICmpInst::Predicate OriginalPred = Pred; 7558 7559 // Handle common loops like: for (X = "string"; *X; ++X) 7560 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0))) 7561 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) { 7562 ExitLimit ItCnt = 7563 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred); 7564 if (ItCnt.hasAnyInfo()) 7565 return ItCnt; 7566 } 7567 7568 const SCEV *LHS = getSCEV(ExitCond->getOperand(0)); 7569 const SCEV *RHS = getSCEV(ExitCond->getOperand(1)); 7570 7571 // Try to evaluate any dependencies out of the loop. 7572 LHS = getSCEVAtScope(LHS, L); 7573 RHS = getSCEVAtScope(RHS, L); 7574 7575 // At this point, we would like to compute how many iterations of the 7576 // loop the predicate will return true for these inputs. 7577 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) { 7578 // If there is a loop-invariant, force it into the RHS. 7579 std::swap(LHS, RHS); 7580 Pred = ICmpInst::getSwappedPredicate(Pred); 7581 } 7582 7583 // Simplify the operands before analyzing them. 7584 (void)SimplifyICmpOperands(Pred, LHS, RHS); 7585 7586 // If we have a comparison of a chrec against a constant, try to use value 7587 // ranges to answer this query. 7588 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) 7589 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS)) 7590 if (AddRec->getLoop() == L) { 7591 // Form the constant range. 7592 ConstantRange CompRange = 7593 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt()); 7594 7595 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this); 7596 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret; 7597 } 7598 7599 switch (Pred) { 7600 case ICmpInst::ICMP_NE: { // while (X != Y) 7601 // Convert to: while (X-Y != 0) 7602 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, 7603 AllowPredicates); 7604 if (EL.hasAnyInfo()) return EL; 7605 break; 7606 } 7607 case ICmpInst::ICMP_EQ: { // while (X == Y) 7608 // Convert to: while (X-Y == 0) 7609 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L); 7610 if (EL.hasAnyInfo()) return EL; 7611 break; 7612 } 7613 case ICmpInst::ICMP_SLT: 7614 case ICmpInst::ICMP_ULT: { // while (X < Y) 7615 bool IsSigned = Pred == ICmpInst::ICMP_SLT; 7616 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, 7617 AllowPredicates); 7618 if (EL.hasAnyInfo()) return EL; 7619 break; 7620 } 7621 case ICmpInst::ICMP_SGT: 7622 case ICmpInst::ICMP_UGT: { // while (X > Y) 7623 bool IsSigned = Pred == ICmpInst::ICMP_SGT; 7624 ExitLimit EL = 7625 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit, 7626 AllowPredicates); 7627 if (EL.hasAnyInfo()) return EL; 7628 break; 7629 } 7630 default: 7631 break; 7632 } 7633 7634 auto *ExhaustiveCount = 7635 computeExitCountExhaustively(L, ExitCond, ExitIfTrue); 7636 7637 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount)) 7638 return ExhaustiveCount; 7639 7640 return computeShiftCompareExitLimit(ExitCond->getOperand(0), 7641 ExitCond->getOperand(1), L, OriginalPred); 7642 } 7643 7644 ScalarEvolution::ExitLimit 7645 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L, 7646 SwitchInst *Switch, 7647 BasicBlock *ExitingBlock, 7648 bool ControlsExit) { 7649 assert(!L->contains(ExitingBlock) && "Not an exiting block!"); 7650 7651 // Give up if the exit is the default dest of a switch. 7652 if (Switch->getDefaultDest() == ExitingBlock) 7653 return getCouldNotCompute(); 7654 7655 assert(L->contains(Switch->getDefaultDest()) && 7656 "Default case must not exit the loop!"); 7657 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L); 7658 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock)); 7659 7660 // while (X != Y) --> while (X-Y != 0) 7661 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit); 7662 if (EL.hasAnyInfo()) 7663 return EL; 7664 7665 return getCouldNotCompute(); 7666 } 7667 7668 static ConstantInt * 7669 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C, 7670 ScalarEvolution &SE) { 7671 const SCEV *InVal = SE.getConstant(C); 7672 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE); 7673 assert(isa<SCEVConstant>(Val) && 7674 "Evaluation of SCEV at constant didn't fold correctly?"); 7675 return cast<SCEVConstant>(Val)->getValue(); 7676 } 7677 7678 /// Given an exit condition of 'icmp op load X, cst', try to see if we can 7679 /// compute the backedge execution count. 7680 ScalarEvolution::ExitLimit 7681 ScalarEvolution::computeLoadConstantCompareExitLimit( 7682 LoadInst *LI, 7683 Constant *RHS, 7684 const Loop *L, 7685 ICmpInst::Predicate predicate) { 7686 if (LI->isVolatile()) return getCouldNotCompute(); 7687 7688 // Check to see if the loaded pointer is a getelementptr of a global. 7689 // TODO: Use SCEV instead of manually grubbing with GEPs. 7690 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)); 7691 if (!GEP) return getCouldNotCompute(); 7692 7693 // Make sure that it is really a constant global we are gepping, with an 7694 // initializer, and make sure the first IDX is really 0. 7695 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)); 7696 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || 7697 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) || 7698 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 7699 return getCouldNotCompute(); 7700 7701 // Okay, we allow one non-constant index into the GEP instruction. 7702 Value *VarIdx = nullptr; 7703 std::vector<Constant*> Indexes; 7704 unsigned VarIdxNum = 0; 7705 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) 7706 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) { 7707 Indexes.push_back(CI); 7708 } else if (!isa<ConstantInt>(GEP->getOperand(i))) { 7709 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's. 7710 VarIdx = GEP->getOperand(i); 7711 VarIdxNum = i-2; 7712 Indexes.push_back(nullptr); 7713 } 7714 7715 // Loop-invariant loads may be a byproduct of loop optimization. Skip them. 7716 if (!VarIdx) 7717 return getCouldNotCompute(); 7718 7719 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant. 7720 // Check to see if X is a loop variant variable value now. 7721 const SCEV *Idx = getSCEV(VarIdx); 7722 Idx = getSCEVAtScope(Idx, L); 7723 7724 // We can only recognize very limited forms of loop index expressions, in 7725 // particular, only affine AddRec's like {C1,+,C2}. 7726 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx); 7727 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) || 7728 !isa<SCEVConstant>(IdxExpr->getOperand(0)) || 7729 !isa<SCEVConstant>(IdxExpr->getOperand(1))) 7730 return getCouldNotCompute(); 7731 7732 unsigned MaxSteps = MaxBruteForceIterations; 7733 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) { 7734 ConstantInt *ItCst = ConstantInt::get( 7735 cast<IntegerType>(IdxExpr->getType()), IterationNum); 7736 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this); 7737 7738 // Form the GEP offset. 7739 Indexes[VarIdxNum] = Val; 7740 7741 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(), 7742 Indexes); 7743 if (!Result) break; // Cannot compute! 7744 7745 // Evaluate the condition for this iteration. 7746 Result = ConstantExpr::getICmp(predicate, Result, RHS); 7747 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure 7748 if (cast<ConstantInt>(Result)->getValue().isMinValue()) { 7749 ++NumArrayLenItCounts; 7750 return getConstant(ItCst); // Found terminating iteration! 7751 } 7752 } 7753 return getCouldNotCompute(); 7754 } 7755 7756 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit( 7757 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) { 7758 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV); 7759 if (!RHS) 7760 return getCouldNotCompute(); 7761 7762 const BasicBlock *Latch = L->getLoopLatch(); 7763 if (!Latch) 7764 return getCouldNotCompute(); 7765 7766 const BasicBlock *Predecessor = L->getLoopPredecessor(); 7767 if (!Predecessor) 7768 return getCouldNotCompute(); 7769 7770 // Return true if V is of the form "LHS `shift_op` <positive constant>". 7771 // Return LHS in OutLHS and shift_opt in OutOpCode. 7772 auto MatchPositiveShift = 7773 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) { 7774 7775 using namespace PatternMatch; 7776 7777 ConstantInt *ShiftAmt; 7778 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7779 OutOpCode = Instruction::LShr; 7780 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7781 OutOpCode = Instruction::AShr; 7782 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt)))) 7783 OutOpCode = Instruction::Shl; 7784 else 7785 return false; 7786 7787 return ShiftAmt->getValue().isStrictlyPositive(); 7788 }; 7789 7790 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in 7791 // 7792 // loop: 7793 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ] 7794 // %iv.shifted = lshr i32 %iv, <positive constant> 7795 // 7796 // Return true on a successful match. Return the corresponding PHI node (%iv 7797 // above) in PNOut and the opcode of the shift operation in OpCodeOut. 7798 auto MatchShiftRecurrence = 7799 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) { 7800 Optional<Instruction::BinaryOps> PostShiftOpCode; 7801 7802 { 7803 Instruction::BinaryOps OpC; 7804 Value *V; 7805 7806 // If we encounter a shift instruction, "peel off" the shift operation, 7807 // and remember that we did so. Later when we inspect %iv's backedge 7808 // value, we will make sure that the backedge value uses the same 7809 // operation. 7810 // 7811 // Note: the peeled shift operation does not have to be the same 7812 // instruction as the one feeding into the PHI's backedge value. We only 7813 // really care about it being the same *kind* of shift instruction -- 7814 // that's all that is required for our later inferences to hold. 7815 if (MatchPositiveShift(LHS, V, OpC)) { 7816 PostShiftOpCode = OpC; 7817 LHS = V; 7818 } 7819 } 7820 7821 PNOut = dyn_cast<PHINode>(LHS); 7822 if (!PNOut || PNOut->getParent() != L->getHeader()) 7823 return false; 7824 7825 Value *BEValue = PNOut->getIncomingValueForBlock(Latch); 7826 Value *OpLHS; 7827 7828 return 7829 // The backedge value for the PHI node must be a shift by a positive 7830 // amount 7831 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) && 7832 7833 // of the PHI node itself 7834 OpLHS == PNOut && 7835 7836 // and the kind of shift should be match the kind of shift we peeled 7837 // off, if any. 7838 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut); 7839 }; 7840 7841 PHINode *PN; 7842 Instruction::BinaryOps OpCode; 7843 if (!MatchShiftRecurrence(LHS, PN, OpCode)) 7844 return getCouldNotCompute(); 7845 7846 const DataLayout &DL = getDataLayout(); 7847 7848 // The key rationale for this optimization is that for some kinds of shift 7849 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1 7850 // within a finite number of iterations. If the condition guarding the 7851 // backedge (in the sense that the backedge is taken if the condition is true) 7852 // is false for the value the shift recurrence stabilizes to, then we know 7853 // that the backedge is taken only a finite number of times. 7854 7855 ConstantInt *StableValue = nullptr; 7856 switch (OpCode) { 7857 default: 7858 llvm_unreachable("Impossible case!"); 7859 7860 case Instruction::AShr: { 7861 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most 7862 // bitwidth(K) iterations. 7863 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor); 7864 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr, 7865 Predecessor->getTerminator(), &DT); 7866 auto *Ty = cast<IntegerType>(RHS->getType()); 7867 if (Known.isNonNegative()) 7868 StableValue = ConstantInt::get(Ty, 0); 7869 else if (Known.isNegative()) 7870 StableValue = ConstantInt::get(Ty, -1, true); 7871 else 7872 return getCouldNotCompute(); 7873 7874 break; 7875 } 7876 case Instruction::LShr: 7877 case Instruction::Shl: 7878 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>} 7879 // stabilize to 0 in at most bitwidth(K) iterations. 7880 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0); 7881 break; 7882 } 7883 7884 auto *Result = 7885 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI); 7886 assert(Result->getType()->isIntegerTy(1) && 7887 "Otherwise cannot be an operand to a branch instruction"); 7888 7889 if (Result->isZeroValue()) { 7890 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 7891 const SCEV *UpperBound = 7892 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth); 7893 return ExitLimit(getCouldNotCompute(), UpperBound, false); 7894 } 7895 7896 return getCouldNotCompute(); 7897 } 7898 7899 /// Return true if we can constant fold an instruction of the specified type, 7900 /// assuming that all operands were constants. 7901 static bool CanConstantFold(const Instruction *I) { 7902 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) || 7903 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 7904 isa<LoadInst>(I) || isa<ExtractValueInst>(I)) 7905 return true; 7906 7907 if (const CallInst *CI = dyn_cast<CallInst>(I)) 7908 if (const Function *F = CI->getCalledFunction()) 7909 return canConstantFoldCallTo(CI, F); 7910 return false; 7911 } 7912 7913 /// Determine whether this instruction can constant evolve within this loop 7914 /// assuming its operands can all constant evolve. 7915 static bool canConstantEvolve(Instruction *I, const Loop *L) { 7916 // An instruction outside of the loop can't be derived from a loop PHI. 7917 if (!L->contains(I)) return false; 7918 7919 if (isa<PHINode>(I)) { 7920 // We don't currently keep track of the control flow needed to evaluate 7921 // PHIs, so we cannot handle PHIs inside of loops. 7922 return L->getHeader() == I->getParent(); 7923 } 7924 7925 // If we won't be able to constant fold this expression even if the operands 7926 // are constants, bail early. 7927 return CanConstantFold(I); 7928 } 7929 7930 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by 7931 /// recursing through each instruction operand until reaching a loop header phi. 7932 static PHINode * 7933 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L, 7934 DenseMap<Instruction *, PHINode *> &PHIMap, 7935 unsigned Depth) { 7936 if (Depth > MaxConstantEvolvingDepth) 7937 return nullptr; 7938 7939 // Otherwise, we can evaluate this instruction if all of its operands are 7940 // constant or derived from a PHI node themselves. 7941 PHINode *PHI = nullptr; 7942 for (Value *Op : UseInst->operands()) { 7943 if (isa<Constant>(Op)) continue; 7944 7945 Instruction *OpInst = dyn_cast<Instruction>(Op); 7946 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr; 7947 7948 PHINode *P = dyn_cast<PHINode>(OpInst); 7949 if (!P) 7950 // If this operand is already visited, reuse the prior result. 7951 // We may have P != PHI if this is the deepest point at which the 7952 // inconsistent paths meet. 7953 P = PHIMap.lookup(OpInst); 7954 if (!P) { 7955 // Recurse and memoize the results, whether a phi is found or not. 7956 // This recursive call invalidates pointers into PHIMap. 7957 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1); 7958 PHIMap[OpInst] = P; 7959 } 7960 if (!P) 7961 return nullptr; // Not evolving from PHI 7962 if (PHI && PHI != P) 7963 return nullptr; // Evolving from multiple different PHIs. 7964 PHI = P; 7965 } 7966 // This is a expression evolving from a constant PHI! 7967 return PHI; 7968 } 7969 7970 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node 7971 /// in the loop that V is derived from. We allow arbitrary operations along the 7972 /// way, but the operands of an operation must either be constants or a value 7973 /// derived from a constant PHI. If this expression does not fit with these 7974 /// constraints, return null. 7975 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) { 7976 Instruction *I = dyn_cast<Instruction>(V); 7977 if (!I || !canConstantEvolve(I, L)) return nullptr; 7978 7979 if (PHINode *PN = dyn_cast<PHINode>(I)) 7980 return PN; 7981 7982 // Record non-constant instructions contained by the loop. 7983 DenseMap<Instruction *, PHINode *> PHIMap; 7984 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0); 7985 } 7986 7987 /// EvaluateExpression - Given an expression that passes the 7988 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node 7989 /// in the loop has the value PHIVal. If we can't fold this expression for some 7990 /// reason, return null. 7991 static Constant *EvaluateExpression(Value *V, const Loop *L, 7992 DenseMap<Instruction *, Constant *> &Vals, 7993 const DataLayout &DL, 7994 const TargetLibraryInfo *TLI) { 7995 // Convenient constant check, but redundant for recursive calls. 7996 if (Constant *C = dyn_cast<Constant>(V)) return C; 7997 Instruction *I = dyn_cast<Instruction>(V); 7998 if (!I) return nullptr; 7999 8000 if (Constant *C = Vals.lookup(I)) return C; 8001 8002 // An instruction inside the loop depends on a value outside the loop that we 8003 // weren't given a mapping for, or a value such as a call inside the loop. 8004 if (!canConstantEvolve(I, L)) return nullptr; 8005 8006 // An unmapped PHI can be due to a branch or another loop inside this loop, 8007 // or due to this not being the initial iteration through a loop where we 8008 // couldn't compute the evolution of this particular PHI last time. 8009 if (isa<PHINode>(I)) return nullptr; 8010 8011 std::vector<Constant*> Operands(I->getNumOperands()); 8012 8013 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 8014 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i)); 8015 if (!Operand) { 8016 Operands[i] = dyn_cast<Constant>(I->getOperand(i)); 8017 if (!Operands[i]) return nullptr; 8018 continue; 8019 } 8020 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI); 8021 Vals[Operand] = C; 8022 if (!C) return nullptr; 8023 Operands[i] = C; 8024 } 8025 8026 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 8027 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8028 Operands[1], DL, TLI); 8029 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 8030 if (!LI->isVolatile()) 8031 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL); 8032 } 8033 return ConstantFoldInstOperands(I, Operands, DL, TLI); 8034 } 8035 8036 8037 // If every incoming value to PN except the one for BB is a specific Constant, 8038 // return that, else return nullptr. 8039 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) { 8040 Constant *IncomingVal = nullptr; 8041 8042 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 8043 if (PN->getIncomingBlock(i) == BB) 8044 continue; 8045 8046 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i)); 8047 if (!CurrentVal) 8048 return nullptr; 8049 8050 if (IncomingVal != CurrentVal) { 8051 if (IncomingVal) 8052 return nullptr; 8053 IncomingVal = CurrentVal; 8054 } 8055 } 8056 8057 return IncomingVal; 8058 } 8059 8060 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 8061 /// in the header of its containing loop, we know the loop executes a 8062 /// constant number of times, and the PHI node is just a recurrence 8063 /// involving constants, fold it. 8064 Constant * 8065 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN, 8066 const APInt &BEs, 8067 const Loop *L) { 8068 auto I = ConstantEvolutionLoopExitValue.find(PN); 8069 if (I != ConstantEvolutionLoopExitValue.end()) 8070 return I->second; 8071 8072 if (BEs.ugt(MaxBruteForceIterations)) 8073 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it. 8074 8075 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN]; 8076 8077 DenseMap<Instruction *, Constant *> CurrentIterVals; 8078 BasicBlock *Header = L->getHeader(); 8079 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8080 8081 BasicBlock *Latch = L->getLoopLatch(); 8082 if (!Latch) 8083 return nullptr; 8084 8085 for (PHINode &PHI : Header->phis()) { 8086 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8087 CurrentIterVals[&PHI] = StartCST; 8088 } 8089 if (!CurrentIterVals.count(PN)) 8090 return RetVal = nullptr; 8091 8092 Value *BEValue = PN->getIncomingValueForBlock(Latch); 8093 8094 // Execute the loop symbolically to determine the exit value. 8095 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) && 8096 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!"); 8097 8098 unsigned NumIterations = BEs.getZExtValue(); // must be in range 8099 unsigned IterationNum = 0; 8100 const DataLayout &DL = getDataLayout(); 8101 for (; ; ++IterationNum) { 8102 if (IterationNum == NumIterations) 8103 return RetVal = CurrentIterVals[PN]; // Got exit value! 8104 8105 // Compute the value of the PHIs for the next iteration. 8106 // EvaluateExpression adds non-phi values to the CurrentIterVals map. 8107 DenseMap<Instruction *, Constant *> NextIterVals; 8108 Constant *NextPHI = 8109 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8110 if (!NextPHI) 8111 return nullptr; // Couldn't evaluate! 8112 NextIterVals[PN] = NextPHI; 8113 8114 bool StoppedEvolving = NextPHI == CurrentIterVals[PN]; 8115 8116 // Also evaluate the other PHI nodes. However, we don't get to stop if we 8117 // cease to be able to evaluate one of them or if they stop evolving, 8118 // because that doesn't necessarily prevent us from computing PN. 8119 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute; 8120 for (const auto &I : CurrentIterVals) { 8121 PHINode *PHI = dyn_cast<PHINode>(I.first); 8122 if (!PHI || PHI == PN || PHI->getParent() != Header) continue; 8123 PHIsToCompute.emplace_back(PHI, I.second); 8124 } 8125 // We use two distinct loops because EvaluateExpression may invalidate any 8126 // iterators into CurrentIterVals. 8127 for (const auto &I : PHIsToCompute) { 8128 PHINode *PHI = I.first; 8129 Constant *&NextPHI = NextIterVals[PHI]; 8130 if (!NextPHI) { // Not already computed. 8131 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8132 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8133 } 8134 if (NextPHI != I.second) 8135 StoppedEvolving = false; 8136 } 8137 8138 // If all entries in CurrentIterVals == NextIterVals then we can stop 8139 // iterating, the loop can't continue to change. 8140 if (StoppedEvolving) 8141 return RetVal = CurrentIterVals[PN]; 8142 8143 CurrentIterVals.swap(NextIterVals); 8144 } 8145 } 8146 8147 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L, 8148 Value *Cond, 8149 bool ExitWhen) { 8150 PHINode *PN = getConstantEvolvingPHI(Cond, L); 8151 if (!PN) return getCouldNotCompute(); 8152 8153 // If the loop is canonicalized, the PHI will have exactly two entries. 8154 // That's the only form we support here. 8155 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute(); 8156 8157 DenseMap<Instruction *, Constant *> CurrentIterVals; 8158 BasicBlock *Header = L->getHeader(); 8159 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!"); 8160 8161 BasicBlock *Latch = L->getLoopLatch(); 8162 assert(Latch && "Should follow from NumIncomingValues == 2!"); 8163 8164 for (PHINode &PHI : Header->phis()) { 8165 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch)) 8166 CurrentIterVals[&PHI] = StartCST; 8167 } 8168 if (!CurrentIterVals.count(PN)) 8169 return getCouldNotCompute(); 8170 8171 // Okay, we find a PHI node that defines the trip count of this loop. Execute 8172 // the loop symbolically to determine when the condition gets a value of 8173 // "ExitWhen". 8174 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis. 8175 const DataLayout &DL = getDataLayout(); 8176 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){ 8177 auto *CondVal = dyn_cast_or_null<ConstantInt>( 8178 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI)); 8179 8180 // Couldn't symbolically evaluate. 8181 if (!CondVal) return getCouldNotCompute(); 8182 8183 if (CondVal->getValue() == uint64_t(ExitWhen)) { 8184 ++NumBruteForceTripCountsComputed; 8185 return getConstant(Type::getInt32Ty(getContext()), IterationNum); 8186 } 8187 8188 // Update all the PHI nodes for the next iteration. 8189 DenseMap<Instruction *, Constant *> NextIterVals; 8190 8191 // Create a list of which PHIs we need to compute. We want to do this before 8192 // calling EvaluateExpression on them because that may invalidate iterators 8193 // into CurrentIterVals. 8194 SmallVector<PHINode *, 8> PHIsToCompute; 8195 for (const auto &I : CurrentIterVals) { 8196 PHINode *PHI = dyn_cast<PHINode>(I.first); 8197 if (!PHI || PHI->getParent() != Header) continue; 8198 PHIsToCompute.push_back(PHI); 8199 } 8200 for (PHINode *PHI : PHIsToCompute) { 8201 Constant *&NextPHI = NextIterVals[PHI]; 8202 if (NextPHI) continue; // Already computed! 8203 8204 Value *BEValue = PHI->getIncomingValueForBlock(Latch); 8205 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI); 8206 } 8207 CurrentIterVals.swap(NextIterVals); 8208 } 8209 8210 // Too many iterations were needed to evaluate. 8211 return getCouldNotCompute(); 8212 } 8213 8214 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) { 8215 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = 8216 ValuesAtScopes[V]; 8217 // Check to see if we've folded this expression at this loop before. 8218 for (auto &LS : Values) 8219 if (LS.first == L) 8220 return LS.second ? LS.second : V; 8221 8222 Values.emplace_back(L, nullptr); 8223 8224 // Otherwise compute it. 8225 const SCEV *C = computeSCEVAtScope(V, L); 8226 for (auto &LS : reverse(ValuesAtScopes[V])) 8227 if (LS.first == L) { 8228 LS.second = C; 8229 break; 8230 } 8231 return C; 8232 } 8233 8234 /// This builds up a Constant using the ConstantExpr interface. That way, we 8235 /// will return Constants for objects which aren't represented by a 8236 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt. 8237 /// Returns NULL if the SCEV isn't representable as a Constant. 8238 static Constant *BuildConstantFromSCEV(const SCEV *V) { 8239 switch (V->getSCEVType()) { 8240 case scCouldNotCompute: 8241 case scAddRecExpr: 8242 return nullptr; 8243 case scConstant: 8244 return cast<SCEVConstant>(V)->getValue(); 8245 case scUnknown: 8246 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue()); 8247 case scSignExtend: { 8248 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V); 8249 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand())) 8250 return ConstantExpr::getSExt(CastOp, SS->getType()); 8251 return nullptr; 8252 } 8253 case scZeroExtend: { 8254 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V); 8255 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand())) 8256 return ConstantExpr::getZExt(CastOp, SZ->getType()); 8257 return nullptr; 8258 } 8259 case scPtrToInt: { 8260 const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V); 8261 if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand())) 8262 return ConstantExpr::getPtrToInt(CastOp, P2I->getType()); 8263 8264 return nullptr; 8265 } 8266 case scTruncate: { 8267 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V); 8268 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand())) 8269 return ConstantExpr::getTrunc(CastOp, ST->getType()); 8270 return nullptr; 8271 } 8272 case scAddExpr: { 8273 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V); 8274 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) { 8275 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8276 unsigned AS = PTy->getAddressSpace(); 8277 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8278 C = ConstantExpr::getBitCast(C, DestPtrTy); 8279 } 8280 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) { 8281 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i)); 8282 if (!C2) 8283 return nullptr; 8284 8285 // First pointer! 8286 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) { 8287 unsigned AS = C2->getType()->getPointerAddressSpace(); 8288 std::swap(C, C2); 8289 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS); 8290 // The offsets have been converted to bytes. We can add bytes to an 8291 // i8* by GEP with the byte count in the first index. 8292 C = ConstantExpr::getBitCast(C, DestPtrTy); 8293 } 8294 8295 // Don't bother trying to sum two pointers. We probably can't 8296 // statically compute a load that results from it anyway. 8297 if (C2->getType()->isPointerTy()) 8298 return nullptr; 8299 8300 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) { 8301 if (PTy->getElementType()->isStructTy()) 8302 C2 = ConstantExpr::getIntegerCast( 8303 C2, Type::getInt32Ty(C->getContext()), true); 8304 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2); 8305 } else 8306 C = ConstantExpr::getAdd(C, C2); 8307 } 8308 return C; 8309 } 8310 return nullptr; 8311 } 8312 case scMulExpr: { 8313 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V); 8314 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) { 8315 // Don't bother with pointers at all. 8316 if (C->getType()->isPointerTy()) 8317 return nullptr; 8318 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) { 8319 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i)); 8320 if (!C2 || C2->getType()->isPointerTy()) 8321 return nullptr; 8322 C = ConstantExpr::getMul(C, C2); 8323 } 8324 return C; 8325 } 8326 return nullptr; 8327 } 8328 case scUDivExpr: { 8329 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V); 8330 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS())) 8331 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS())) 8332 if (LHS->getType() == RHS->getType()) 8333 return ConstantExpr::getUDiv(LHS, RHS); 8334 return nullptr; 8335 } 8336 case scSMaxExpr: 8337 case scUMaxExpr: 8338 case scSMinExpr: 8339 case scUMinExpr: 8340 return nullptr; // TODO: smax, umax, smin, umax. 8341 } 8342 llvm_unreachable("Unknown SCEV kind!"); 8343 } 8344 8345 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) { 8346 if (isa<SCEVConstant>(V)) return V; 8347 8348 // If this instruction is evolved from a constant-evolving PHI, compute the 8349 // exit value from the loop without using SCEVs. 8350 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) { 8351 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) { 8352 if (PHINode *PN = dyn_cast<PHINode>(I)) { 8353 const Loop *CurrLoop = this->LI[I->getParent()]; 8354 // Looking for loop exit value. 8355 if (CurrLoop && CurrLoop->getParentLoop() == L && 8356 PN->getParent() == CurrLoop->getHeader()) { 8357 // Okay, there is no closed form solution for the PHI node. Check 8358 // to see if the loop that contains it has a known backedge-taken 8359 // count. If so, we may be able to force computation of the exit 8360 // value. 8361 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop); 8362 // This trivial case can show up in some degenerate cases where 8363 // the incoming IR has not yet been fully simplified. 8364 if (BackedgeTakenCount->isZero()) { 8365 Value *InitValue = nullptr; 8366 bool MultipleInitValues = false; 8367 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 8368 if (!CurrLoop->contains(PN->getIncomingBlock(i))) { 8369 if (!InitValue) 8370 InitValue = PN->getIncomingValue(i); 8371 else if (InitValue != PN->getIncomingValue(i)) { 8372 MultipleInitValues = true; 8373 break; 8374 } 8375 } 8376 } 8377 if (!MultipleInitValues && InitValue) 8378 return getSCEV(InitValue); 8379 } 8380 // Do we have a loop invariant value flowing around the backedge 8381 // for a loop which must execute the backedge? 8382 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && 8383 isKnownPositive(BackedgeTakenCount) && 8384 PN->getNumIncomingValues() == 2) { 8385 8386 unsigned InLoopPred = 8387 CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1; 8388 Value *BackedgeVal = PN->getIncomingValue(InLoopPred); 8389 if (CurrLoop->isLoopInvariant(BackedgeVal)) 8390 return getSCEV(BackedgeVal); 8391 } 8392 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) { 8393 // Okay, we know how many times the containing loop executes. If 8394 // this is a constant evolving PHI node, get the final value at 8395 // the specified iteration number. 8396 Constant *RV = getConstantEvolutionLoopExitValue( 8397 PN, BTCC->getAPInt(), CurrLoop); 8398 if (RV) return getSCEV(RV); 8399 } 8400 } 8401 8402 // If there is a single-input Phi, evaluate it at our scope. If we can 8403 // prove that this replacement does not break LCSSA form, use new value. 8404 if (PN->getNumOperands() == 1) { 8405 const SCEV *Input = getSCEV(PN->getOperand(0)); 8406 const SCEV *InputAtScope = getSCEVAtScope(Input, L); 8407 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm, 8408 // for the simplest case just support constants. 8409 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope; 8410 } 8411 } 8412 8413 // Okay, this is an expression that we cannot symbolically evaluate 8414 // into a SCEV. Check to see if it's possible to symbolically evaluate 8415 // the arguments into constants, and if so, try to constant propagate the 8416 // result. This is particularly useful for computing loop exit values. 8417 if (CanConstantFold(I)) { 8418 SmallVector<Constant *, 4> Operands; 8419 bool MadeImprovement = false; 8420 for (Value *Op : I->operands()) { 8421 if (Constant *C = dyn_cast<Constant>(Op)) { 8422 Operands.push_back(C); 8423 continue; 8424 } 8425 8426 // If any of the operands is non-constant and if they are 8427 // non-integer and non-pointer, don't even try to analyze them 8428 // with scev techniques. 8429 if (!isSCEVable(Op->getType())) 8430 return V; 8431 8432 const SCEV *OrigV = getSCEV(Op); 8433 const SCEV *OpV = getSCEVAtScope(OrigV, L); 8434 MadeImprovement |= OrigV != OpV; 8435 8436 Constant *C = BuildConstantFromSCEV(OpV); 8437 if (!C) return V; 8438 if (C->getType() != Op->getType()) 8439 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, 8440 Op->getType(), 8441 false), 8442 C, Op->getType()); 8443 Operands.push_back(C); 8444 } 8445 8446 // Check to see if getSCEVAtScope actually made an improvement. 8447 if (MadeImprovement) { 8448 Constant *C = nullptr; 8449 const DataLayout &DL = getDataLayout(); 8450 if (const CmpInst *CI = dyn_cast<CmpInst>(I)) 8451 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0], 8452 Operands[1], DL, &TLI); 8453 else if (const LoadInst *Load = dyn_cast<LoadInst>(I)) { 8454 if (!Load->isVolatile()) 8455 C = ConstantFoldLoadFromConstPtr(Operands[0], Load->getType(), 8456 DL); 8457 } else 8458 C = ConstantFoldInstOperands(I, Operands, DL, &TLI); 8459 if (!C) return V; 8460 return getSCEV(C); 8461 } 8462 } 8463 } 8464 8465 // This is some other type of SCEVUnknown, just return it. 8466 return V; 8467 } 8468 8469 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) { 8470 // Avoid performing the look-up in the common case where the specified 8471 // expression has no loop-variant portions. 8472 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) { 8473 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8474 if (OpAtScope != Comm->getOperand(i)) { 8475 // Okay, at least one of these operands is loop variant but might be 8476 // foldable. Build a new instance of the folded commutative expression. 8477 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(), 8478 Comm->op_begin()+i); 8479 NewOps.push_back(OpAtScope); 8480 8481 for (++i; i != e; ++i) { 8482 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L); 8483 NewOps.push_back(OpAtScope); 8484 } 8485 if (isa<SCEVAddExpr>(Comm)) 8486 return getAddExpr(NewOps, Comm->getNoWrapFlags()); 8487 if (isa<SCEVMulExpr>(Comm)) 8488 return getMulExpr(NewOps, Comm->getNoWrapFlags()); 8489 if (isa<SCEVMinMaxExpr>(Comm)) 8490 return getMinMaxExpr(Comm->getSCEVType(), NewOps); 8491 llvm_unreachable("Unknown commutative SCEV type!"); 8492 } 8493 } 8494 // If we got here, all operands are loop invariant. 8495 return Comm; 8496 } 8497 8498 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) { 8499 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L); 8500 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L); 8501 if (LHS == Div->getLHS() && RHS == Div->getRHS()) 8502 return Div; // must be loop invariant 8503 return getUDivExpr(LHS, RHS); 8504 } 8505 8506 // If this is a loop recurrence for a loop that does not contain L, then we 8507 // are dealing with the final value computed by the loop. 8508 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) { 8509 // First, attempt to evaluate each operand. 8510 // Avoid performing the look-up in the common case where the specified 8511 // expression has no loop-variant portions. 8512 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) { 8513 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L); 8514 if (OpAtScope == AddRec->getOperand(i)) 8515 continue; 8516 8517 // Okay, at least one of these operands is loop variant but might be 8518 // foldable. Build a new instance of the folded commutative expression. 8519 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(), 8520 AddRec->op_begin()+i); 8521 NewOps.push_back(OpAtScope); 8522 for (++i; i != e; ++i) 8523 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L)); 8524 8525 const SCEV *FoldedRec = 8526 getAddRecExpr(NewOps, AddRec->getLoop(), 8527 AddRec->getNoWrapFlags(SCEV::FlagNW)); 8528 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec); 8529 // The addrec may be folded to a nonrecurrence, for example, if the 8530 // induction variable is multiplied by zero after constant folding. Go 8531 // ahead and return the folded value. 8532 if (!AddRec) 8533 return FoldedRec; 8534 break; 8535 } 8536 8537 // If the scope is outside the addrec's loop, evaluate it by using the 8538 // loop exit value of the addrec. 8539 if (!AddRec->getLoop()->contains(L)) { 8540 // To evaluate this recurrence, we need to know how many times the AddRec 8541 // loop iterates. Compute this now. 8542 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop()); 8543 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec; 8544 8545 // Then, evaluate the AddRec. 8546 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this); 8547 } 8548 8549 return AddRec; 8550 } 8551 8552 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) { 8553 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8554 if (Op == Cast->getOperand()) 8555 return Cast; // must be loop invariant 8556 return getZeroExtendExpr(Op, Cast->getType()); 8557 } 8558 8559 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) { 8560 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8561 if (Op == Cast->getOperand()) 8562 return Cast; // must be loop invariant 8563 return getSignExtendExpr(Op, Cast->getType()); 8564 } 8565 8566 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) { 8567 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8568 if (Op == Cast->getOperand()) 8569 return Cast; // must be loop invariant 8570 return getTruncateExpr(Op, Cast->getType()); 8571 } 8572 8573 if (const SCEVPtrToIntExpr *Cast = dyn_cast<SCEVPtrToIntExpr>(V)) { 8574 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L); 8575 if (Op == Cast->getOperand()) 8576 return Cast; // must be loop invariant 8577 return getPtrToIntExpr(Op, Cast->getType()); 8578 } 8579 8580 llvm_unreachable("Unknown SCEV type!"); 8581 } 8582 8583 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) { 8584 return getSCEVAtScope(getSCEV(V), L); 8585 } 8586 8587 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const { 8588 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) 8589 return stripInjectiveFunctions(ZExt->getOperand()); 8590 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) 8591 return stripInjectiveFunctions(SExt->getOperand()); 8592 return S; 8593 } 8594 8595 /// Finds the minimum unsigned root of the following equation: 8596 /// 8597 /// A * X = B (mod N) 8598 /// 8599 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of 8600 /// A and B isn't important. 8601 /// 8602 /// If the equation does not have a solution, SCEVCouldNotCompute is returned. 8603 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B, 8604 ScalarEvolution &SE) { 8605 uint32_t BW = A.getBitWidth(); 8606 assert(BW == SE.getTypeSizeInBits(B->getType())); 8607 assert(A != 0 && "A must be non-zero."); 8608 8609 // 1. D = gcd(A, N) 8610 // 8611 // The gcd of A and N may have only one prime factor: 2. The number of 8612 // trailing zeros in A is its multiplicity 8613 uint32_t Mult2 = A.countTrailingZeros(); 8614 // D = 2^Mult2 8615 8616 // 2. Check if B is divisible by D. 8617 // 8618 // B is divisible by D if and only if the multiplicity of prime factor 2 for B 8619 // is not less than multiplicity of this prime factor for D. 8620 if (SE.GetMinTrailingZeros(B) < Mult2) 8621 return SE.getCouldNotCompute(); 8622 8623 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic 8624 // modulo (N / D). 8625 // 8626 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent 8627 // (N / D) in general. The inverse itself always fits into BW bits, though, 8628 // so we immediately truncate it. 8629 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D 8630 APInt Mod(BW + 1, 0); 8631 Mod.setBit(BW - Mult2); // Mod = N / D 8632 APInt I = AD.multiplicativeInverse(Mod).trunc(BW); 8633 8634 // 4. Compute the minimum unsigned root of the equation: 8635 // I * (B / D) mod (N / D) 8636 // To simplify the computation, we factor out the divide by D: 8637 // (I * B mod N) / D 8638 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2)); 8639 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D); 8640 } 8641 8642 /// For a given quadratic addrec, generate coefficients of the corresponding 8643 /// quadratic equation, multiplied by a common value to ensure that they are 8644 /// integers. 8645 /// The returned value is a tuple { A, B, C, M, BitWidth }, where 8646 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C 8647 /// were multiplied by, and BitWidth is the bit width of the original addrec 8648 /// coefficients. 8649 /// This function returns None if the addrec coefficients are not compile- 8650 /// time constants. 8651 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>> 8652 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) { 8653 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!"); 8654 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0)); 8655 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1)); 8656 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2)); 8657 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: " 8658 << *AddRec << '\n'); 8659 8660 // We currently can only solve this if the coefficients are constants. 8661 if (!LC || !MC || !NC) { 8662 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n"); 8663 return None; 8664 } 8665 8666 APInt L = LC->getAPInt(); 8667 APInt M = MC->getAPInt(); 8668 APInt N = NC->getAPInt(); 8669 assert(!N.isNullValue() && "This is not a quadratic addrec"); 8670 8671 unsigned BitWidth = LC->getAPInt().getBitWidth(); 8672 unsigned NewWidth = BitWidth + 1; 8673 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: " 8674 << BitWidth << '\n'); 8675 // The sign-extension (as opposed to a zero-extension) here matches the 8676 // extension used in SolveQuadraticEquationWrap (with the same motivation). 8677 N = N.sext(NewWidth); 8678 M = M.sext(NewWidth); 8679 L = L.sext(NewWidth); 8680 8681 // The increments are M, M+N, M+2N, ..., so the accumulated values are 8682 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is, 8683 // L+M, L+2M+N, L+3M+3N, ... 8684 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N. 8685 // 8686 // The equation Acc = 0 is then 8687 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0. 8688 // In a quadratic form it becomes: 8689 // N n^2 + (2M-N) n + 2L = 0. 8690 8691 APInt A = N; 8692 APInt B = 2 * M - A; 8693 APInt C = 2 * L; 8694 APInt T = APInt(NewWidth, 2); 8695 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B 8696 << "x + " << C << ", coeff bw: " << NewWidth 8697 << ", multiplied by " << T << '\n'); 8698 return std::make_tuple(A, B, C, T, BitWidth); 8699 } 8700 8701 /// Helper function to compare optional APInts: 8702 /// (a) if X and Y both exist, return min(X, Y), 8703 /// (b) if neither X nor Y exist, return None, 8704 /// (c) if exactly one of X and Y exists, return that value. 8705 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) { 8706 if (X.hasValue() && Y.hasValue()) { 8707 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth()); 8708 APInt XW = X->sextOrSelf(W); 8709 APInt YW = Y->sextOrSelf(W); 8710 return XW.slt(YW) ? *X : *Y; 8711 } 8712 if (!X.hasValue() && !Y.hasValue()) 8713 return None; 8714 return X.hasValue() ? *X : *Y; 8715 } 8716 8717 /// Helper function to truncate an optional APInt to a given BitWidth. 8718 /// When solving addrec-related equations, it is preferable to return a value 8719 /// that has the same bit width as the original addrec's coefficients. If the 8720 /// solution fits in the original bit width, truncate it (except for i1). 8721 /// Returning a value of a different bit width may inhibit some optimizations. 8722 /// 8723 /// In general, a solution to a quadratic equation generated from an addrec 8724 /// may require BW+1 bits, where BW is the bit width of the addrec's 8725 /// coefficients. The reason is that the coefficients of the quadratic 8726 /// equation are BW+1 bits wide (to avoid truncation when converting from 8727 /// the addrec to the equation). 8728 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) { 8729 if (!X.hasValue()) 8730 return None; 8731 unsigned W = X->getBitWidth(); 8732 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth)) 8733 return X->trunc(BitWidth); 8734 return X; 8735 } 8736 8737 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n 8738 /// iterations. The values L, M, N are assumed to be signed, and they 8739 /// should all have the same bit widths. 8740 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW, 8741 /// where BW is the bit width of the addrec's coefficients. 8742 /// If the calculated value is a BW-bit integer (for BW > 1), it will be 8743 /// returned as such, otherwise the bit width of the returned value may 8744 /// be greater than BW. 8745 /// 8746 /// This function returns None if 8747 /// (a) the addrec coefficients are not constant, or 8748 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases 8749 /// like x^2 = 5, no integer solutions exist, in other cases an integer 8750 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it. 8751 static Optional<APInt> 8752 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) { 8753 APInt A, B, C, M; 8754 unsigned BitWidth; 8755 auto T = GetQuadraticEquation(AddRec); 8756 if (!T.hasValue()) 8757 return None; 8758 8759 std::tie(A, B, C, M, BitWidth) = *T; 8760 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n"); 8761 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1); 8762 if (!X.hasValue()) 8763 return None; 8764 8765 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X); 8766 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE); 8767 if (!V->isZero()) 8768 return None; 8769 8770 return TruncIfPossible(X, BitWidth); 8771 } 8772 8773 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n 8774 /// iterations. The values M, N are assumed to be signed, and they 8775 /// should all have the same bit widths. 8776 /// Find the least n such that c(n) does not belong to the given range, 8777 /// while c(n-1) does. 8778 /// 8779 /// This function returns None if 8780 /// (a) the addrec coefficients are not constant, or 8781 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the 8782 /// bounds of the range. 8783 static Optional<APInt> 8784 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec, 8785 const ConstantRange &Range, ScalarEvolution &SE) { 8786 assert(AddRec->getOperand(0)->isZero() && 8787 "Starting value of addrec should be 0"); 8788 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range " 8789 << Range << ", addrec " << *AddRec << '\n'); 8790 // This case is handled in getNumIterationsInRange. Here we can assume that 8791 // we start in the range. 8792 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) && 8793 "Addrec's initial value should be in range"); 8794 8795 APInt A, B, C, M; 8796 unsigned BitWidth; 8797 auto T = GetQuadraticEquation(AddRec); 8798 if (!T.hasValue()) 8799 return None; 8800 8801 // Be careful about the return value: there can be two reasons for not 8802 // returning an actual number. First, if no solutions to the equations 8803 // were found, and second, if the solutions don't leave the given range. 8804 // The first case means that the actual solution is "unknown", the second 8805 // means that it's known, but not valid. If the solution is unknown, we 8806 // cannot make any conclusions. 8807 // Return a pair: the optional solution and a flag indicating if the 8808 // solution was found. 8809 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> { 8810 // Solve for signed overflow and unsigned overflow, pick the lower 8811 // solution. 8812 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary " 8813 << Bound << " (before multiplying by " << M << ")\n"); 8814 Bound *= M; // The quadratic equation multiplier. 8815 8816 Optional<APInt> SO = None; 8817 if (BitWidth > 1) { 8818 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8819 "signed overflow\n"); 8820 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth); 8821 } 8822 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for " 8823 "unsigned overflow\n"); 8824 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, 8825 BitWidth+1); 8826 8827 auto LeavesRange = [&] (const APInt &X) { 8828 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X); 8829 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE); 8830 if (Range.contains(V0->getValue())) 8831 return false; 8832 // X should be at least 1, so X-1 is non-negative. 8833 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1); 8834 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE); 8835 if (Range.contains(V1->getValue())) 8836 return true; 8837 return false; 8838 }; 8839 8840 // If SolveQuadraticEquationWrap returns None, it means that there can 8841 // be a solution, but the function failed to find it. We cannot treat it 8842 // as "no solution". 8843 if (!SO.hasValue() || !UO.hasValue()) 8844 return { None, false }; 8845 8846 // Check the smaller value first to see if it leaves the range. 8847 // At this point, both SO and UO must have values. 8848 Optional<APInt> Min = MinOptional(SO, UO); 8849 if (LeavesRange(*Min)) 8850 return { Min, true }; 8851 Optional<APInt> Max = Min == SO ? UO : SO; 8852 if (LeavesRange(*Max)) 8853 return { Max, true }; 8854 8855 // Solutions were found, but were eliminated, hence the "true". 8856 return { None, true }; 8857 }; 8858 8859 std::tie(A, B, C, M, BitWidth) = *T; 8860 // Lower bound is inclusive, subtract 1 to represent the exiting value. 8861 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1; 8862 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth()); 8863 auto SL = SolveForBoundary(Lower); 8864 auto SU = SolveForBoundary(Upper); 8865 // If any of the solutions was unknown, no meaninigful conclusions can 8866 // be made. 8867 if (!SL.second || !SU.second) 8868 return None; 8869 8870 // Claim: The correct solution is not some value between Min and Max. 8871 // 8872 // Justification: Assuming that Min and Max are different values, one of 8873 // them is when the first signed overflow happens, the other is when the 8874 // first unsigned overflow happens. Crossing the range boundary is only 8875 // possible via an overflow (treating 0 as a special case of it, modeling 8876 // an overflow as crossing k*2^W for some k). 8877 // 8878 // The interesting case here is when Min was eliminated as an invalid 8879 // solution, but Max was not. The argument is that if there was another 8880 // overflow between Min and Max, it would also have been eliminated if 8881 // it was considered. 8882 // 8883 // For a given boundary, it is possible to have two overflows of the same 8884 // type (signed/unsigned) without having the other type in between: this 8885 // can happen when the vertex of the parabola is between the iterations 8886 // corresponding to the overflows. This is only possible when the two 8887 // overflows cross k*2^W for the same k. In such case, if the second one 8888 // left the range (and was the first one to do so), the first overflow 8889 // would have to enter the range, which would mean that either we had left 8890 // the range before or that we started outside of it. Both of these cases 8891 // are contradictions. 8892 // 8893 // Claim: In the case where SolveForBoundary returns None, the correct 8894 // solution is not some value between the Max for this boundary and the 8895 // Min of the other boundary. 8896 // 8897 // Justification: Assume that we had such Max_A and Min_B corresponding 8898 // to range boundaries A and B and such that Max_A < Min_B. If there was 8899 // a solution between Max_A and Min_B, it would have to be caused by an 8900 // overflow corresponding to either A or B. It cannot correspond to B, 8901 // since Min_B is the first occurrence of such an overflow. If it 8902 // corresponded to A, it would have to be either a signed or an unsigned 8903 // overflow that is larger than both eliminated overflows for A. But 8904 // between the eliminated overflows and this overflow, the values would 8905 // cover the entire value space, thus crossing the other boundary, which 8906 // is a contradiction. 8907 8908 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth); 8909 } 8910 8911 ScalarEvolution::ExitLimit 8912 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit, 8913 bool AllowPredicates) { 8914 8915 // This is only used for loops with a "x != y" exit test. The exit condition 8916 // is now expressed as a single expression, V = x-y. So the exit test is 8917 // effectively V != 0. We know and take advantage of the fact that this 8918 // expression only being used in a comparison by zero context. 8919 8920 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 8921 // If the value is a constant 8922 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 8923 // If the value is already zero, the branch will execute zero times. 8924 if (C->getValue()->isZero()) return C; 8925 return getCouldNotCompute(); // Otherwise it will loop infinitely. 8926 } 8927 8928 const SCEVAddRecExpr *AddRec = 8929 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V)); 8930 8931 if (!AddRec && AllowPredicates) 8932 // Try to make this an AddRec using runtime tests, in the first X 8933 // iterations of this loop, where X is the SCEV expression found by the 8934 // algorithm below. 8935 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates); 8936 8937 if (!AddRec || AddRec->getLoop() != L) 8938 return getCouldNotCompute(); 8939 8940 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of 8941 // the quadratic equation to solve it. 8942 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) { 8943 // We can only use this value if the chrec ends up with an exact zero 8944 // value at this index. When solving for "X*X != 5", for example, we 8945 // should not accept a root of 2. 8946 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) { 8947 const auto *R = cast<SCEVConstant>(getConstant(S.getValue())); 8948 return ExitLimit(R, R, false, Predicates); 8949 } 8950 return getCouldNotCompute(); 8951 } 8952 8953 // Otherwise we can only handle this if it is affine. 8954 if (!AddRec->isAffine()) 8955 return getCouldNotCompute(); 8956 8957 // If this is an affine expression, the execution count of this branch is 8958 // the minimum unsigned root of the following equation: 8959 // 8960 // Start + Step*N = 0 (mod 2^BW) 8961 // 8962 // equivalent to: 8963 // 8964 // Step*N = -Start (mod 2^BW) 8965 // 8966 // where BW is the common bit width of Start and Step. 8967 8968 // Get the initial value for the loop. 8969 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop()); 8970 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop()); 8971 8972 // For now we handle only constant steps. 8973 // 8974 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the 8975 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap 8976 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step. 8977 // We have not yet seen any such cases. 8978 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step); 8979 if (!StepC || StepC->getValue()->isZero()) 8980 return getCouldNotCompute(); 8981 8982 // For positive steps (counting up until unsigned overflow): 8983 // N = -Start/Step (as unsigned) 8984 // For negative steps (counting down to zero): 8985 // N = Start/-Step 8986 // First compute the unsigned distance from zero in the direction of Step. 8987 bool CountDown = StepC->getAPInt().isNegative(); 8988 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start); 8989 8990 // Handle unitary steps, which cannot wraparound. 8991 // 1*N = -Start; -1*N = Start (mod 2^BW), so: 8992 // N = Distance (as unsigned) 8993 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) { 8994 APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L)); 8995 APInt MaxBECountBase = getUnsignedRangeMax(Distance); 8996 if (MaxBECountBase.ult(MaxBECount)) 8997 MaxBECount = MaxBECountBase; 8998 8999 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated, 9000 // we end up with a loop whose backedge-taken count is n - 1. Detect this 9001 // case, and see if we can improve the bound. 9002 // 9003 // Explicitly handling this here is necessary because getUnsignedRange 9004 // isn't context-sensitive; it doesn't know that we only care about the 9005 // range inside the loop. 9006 const SCEV *Zero = getZero(Distance->getType()); 9007 const SCEV *One = getOne(Distance->getType()); 9008 const SCEV *DistancePlusOne = getAddExpr(Distance, One); 9009 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) { 9010 // If Distance + 1 doesn't overflow, we can compute the maximum distance 9011 // as "unsigned_max(Distance + 1) - 1". 9012 ConstantRange CR = getUnsignedRange(DistancePlusOne); 9013 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1); 9014 } 9015 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates); 9016 } 9017 9018 // If the condition controls loop exit (the loop exits only if the expression 9019 // is true) and the addition is no-wrap we can use unsigned divide to 9020 // compute the backedge count. In this case, the step may not divide the 9021 // distance, but we don't care because if the condition is "missed" the loop 9022 // will have undefined behavior due to wrapping. 9023 if (ControlsExit && AddRec->hasNoSelfWrap() && 9024 loopHasNoAbnormalExits(AddRec->getLoop())) { 9025 const SCEV *Exact = 9026 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step); 9027 const SCEV *Max = 9028 Exact == getCouldNotCompute() 9029 ? Exact 9030 : getConstant(getUnsignedRangeMax(Exact)); 9031 return ExitLimit(Exact, Max, false, Predicates); 9032 } 9033 9034 // Solve the general equation. 9035 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), 9036 getNegativeSCEV(Start), *this); 9037 const SCEV *M = E == getCouldNotCompute() 9038 ? E 9039 : getConstant(getUnsignedRangeMax(E)); 9040 return ExitLimit(E, M, false, Predicates); 9041 } 9042 9043 ScalarEvolution::ExitLimit 9044 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) { 9045 // Loops that look like: while (X == 0) are very strange indeed. We don't 9046 // handle them yet except for the trivial case. This could be expanded in the 9047 // future as needed. 9048 9049 // If the value is a constant, check to see if it is known to be non-zero 9050 // already. If so, the backedge will execute zero times. 9051 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) { 9052 if (!C->getValue()->isZero()) 9053 return getZero(C->getType()); 9054 return getCouldNotCompute(); // Otherwise it will loop infinitely. 9055 } 9056 9057 // We could implement others, but I really doubt anyone writes loops like 9058 // this, and if they did, they would already be constant folded. 9059 return getCouldNotCompute(); 9060 } 9061 9062 std::pair<const BasicBlock *, const BasicBlock *> 9063 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) 9064 const { 9065 // If the block has a unique predecessor, then there is no path from the 9066 // predecessor to the block that does not go through the direct edge 9067 // from the predecessor to the block. 9068 if (const BasicBlock *Pred = BB->getSinglePredecessor()) 9069 return {Pred, BB}; 9070 9071 // A loop's header is defined to be a block that dominates the loop. 9072 // If the header has a unique predecessor outside the loop, it must be 9073 // a block that has exactly one successor that can reach the loop. 9074 if (const Loop *L = LI.getLoopFor(BB)) 9075 return {L->getLoopPredecessor(), L->getHeader()}; 9076 9077 return {nullptr, nullptr}; 9078 } 9079 9080 /// SCEV structural equivalence is usually sufficient for testing whether two 9081 /// expressions are equal, however for the purposes of looking for a condition 9082 /// guarding a loop, it can be useful to be a little more general, since a 9083 /// front-end may have replicated the controlling expression. 9084 static bool HasSameValue(const SCEV *A, const SCEV *B) { 9085 // Quick check to see if they are the same SCEV. 9086 if (A == B) return true; 9087 9088 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) { 9089 // Not all instructions that are "identical" compute the same value. For 9090 // instance, two distinct alloca instructions allocating the same type are 9091 // identical and do not read memory; but compute distinct values. 9092 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A)); 9093 }; 9094 9095 // Otherwise, if they're both SCEVUnknown, it's possible that they hold 9096 // two different instructions with the same value. Check for this case. 9097 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A)) 9098 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B)) 9099 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue())) 9100 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue())) 9101 if (ComputesEqualValues(AI, BI)) 9102 return true; 9103 9104 // Otherwise assume they may have a different value. 9105 return false; 9106 } 9107 9108 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred, 9109 const SCEV *&LHS, const SCEV *&RHS, 9110 unsigned Depth) { 9111 bool Changed = false; 9112 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or 9113 // '0 != 0'. 9114 auto TrivialCase = [&](bool TriviallyTrue) { 9115 LHS = RHS = getConstant(ConstantInt::getFalse(getContext())); 9116 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE; 9117 return true; 9118 }; 9119 // If we hit the max recursion limit bail out. 9120 if (Depth >= 3) 9121 return false; 9122 9123 // Canonicalize a constant to the right side. 9124 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) { 9125 // Check for both operands constant. 9126 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) { 9127 if (ConstantExpr::getICmp(Pred, 9128 LHSC->getValue(), 9129 RHSC->getValue())->isNullValue()) 9130 return TrivialCase(false); 9131 else 9132 return TrivialCase(true); 9133 } 9134 // Otherwise swap the operands to put the constant on the right. 9135 std::swap(LHS, RHS); 9136 Pred = ICmpInst::getSwappedPredicate(Pred); 9137 Changed = true; 9138 } 9139 9140 // If we're comparing an addrec with a value which is loop-invariant in the 9141 // addrec's loop, put the addrec on the left. Also make a dominance check, 9142 // as both operands could be addrecs loop-invariant in each other's loop. 9143 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) { 9144 const Loop *L = AR->getLoop(); 9145 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) { 9146 std::swap(LHS, RHS); 9147 Pred = ICmpInst::getSwappedPredicate(Pred); 9148 Changed = true; 9149 } 9150 } 9151 9152 // If there's a constant operand, canonicalize comparisons with boundary 9153 // cases, and canonicalize *-or-equal comparisons to regular comparisons. 9154 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) { 9155 const APInt &RA = RC->getAPInt(); 9156 9157 bool SimplifiedByConstantRange = false; 9158 9159 if (!ICmpInst::isEquality(Pred)) { 9160 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA); 9161 if (ExactCR.isFullSet()) 9162 return TrivialCase(true); 9163 else if (ExactCR.isEmptySet()) 9164 return TrivialCase(false); 9165 9166 APInt NewRHS; 9167 CmpInst::Predicate NewPred; 9168 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) && 9169 ICmpInst::isEquality(NewPred)) { 9170 // We were able to convert an inequality to an equality. 9171 Pred = NewPred; 9172 RHS = getConstant(NewRHS); 9173 Changed = SimplifiedByConstantRange = true; 9174 } 9175 } 9176 9177 if (!SimplifiedByConstantRange) { 9178 switch (Pred) { 9179 default: 9180 break; 9181 case ICmpInst::ICMP_EQ: 9182 case ICmpInst::ICMP_NE: 9183 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b. 9184 if (!RA) 9185 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS)) 9186 if (const SCEVMulExpr *ME = 9187 dyn_cast<SCEVMulExpr>(AE->getOperand(0))) 9188 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 && 9189 ME->getOperand(0)->isAllOnesValue()) { 9190 RHS = AE->getOperand(1); 9191 LHS = ME->getOperand(1); 9192 Changed = true; 9193 } 9194 break; 9195 9196 9197 // The "Should have been caught earlier!" messages refer to the fact 9198 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above 9199 // should have fired on the corresponding cases, and canonicalized the 9200 // check to trivial case. 9201 9202 case ICmpInst::ICMP_UGE: 9203 assert(!RA.isMinValue() && "Should have been caught earlier!"); 9204 Pred = ICmpInst::ICMP_UGT; 9205 RHS = getConstant(RA - 1); 9206 Changed = true; 9207 break; 9208 case ICmpInst::ICMP_ULE: 9209 assert(!RA.isMaxValue() && "Should have been caught earlier!"); 9210 Pred = ICmpInst::ICMP_ULT; 9211 RHS = getConstant(RA + 1); 9212 Changed = true; 9213 break; 9214 case ICmpInst::ICMP_SGE: 9215 assert(!RA.isMinSignedValue() && "Should have been caught earlier!"); 9216 Pred = ICmpInst::ICMP_SGT; 9217 RHS = getConstant(RA - 1); 9218 Changed = true; 9219 break; 9220 case ICmpInst::ICMP_SLE: 9221 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!"); 9222 Pred = ICmpInst::ICMP_SLT; 9223 RHS = getConstant(RA + 1); 9224 Changed = true; 9225 break; 9226 } 9227 } 9228 } 9229 9230 // Check for obvious equality. 9231 if (HasSameValue(LHS, RHS)) { 9232 if (ICmpInst::isTrueWhenEqual(Pred)) 9233 return TrivialCase(true); 9234 if (ICmpInst::isFalseWhenEqual(Pred)) 9235 return TrivialCase(false); 9236 } 9237 9238 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by 9239 // adding or subtracting 1 from one of the operands. 9240 switch (Pred) { 9241 case ICmpInst::ICMP_SLE: 9242 if (!getSignedRangeMax(RHS).isMaxSignedValue()) { 9243 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9244 SCEV::FlagNSW); 9245 Pred = ICmpInst::ICMP_SLT; 9246 Changed = true; 9247 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) { 9248 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS, 9249 SCEV::FlagNSW); 9250 Pred = ICmpInst::ICMP_SLT; 9251 Changed = true; 9252 } 9253 break; 9254 case ICmpInst::ICMP_SGE: 9255 if (!getSignedRangeMin(RHS).isMinSignedValue()) { 9256 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS, 9257 SCEV::FlagNSW); 9258 Pred = ICmpInst::ICMP_SGT; 9259 Changed = true; 9260 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) { 9261 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9262 SCEV::FlagNSW); 9263 Pred = ICmpInst::ICMP_SGT; 9264 Changed = true; 9265 } 9266 break; 9267 case ICmpInst::ICMP_ULE: 9268 if (!getUnsignedRangeMax(RHS).isMaxValue()) { 9269 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS, 9270 SCEV::FlagNUW); 9271 Pred = ICmpInst::ICMP_ULT; 9272 Changed = true; 9273 } else if (!getUnsignedRangeMin(LHS).isMinValue()) { 9274 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS); 9275 Pred = ICmpInst::ICMP_ULT; 9276 Changed = true; 9277 } 9278 break; 9279 case ICmpInst::ICMP_UGE: 9280 if (!getUnsignedRangeMin(RHS).isMinValue()) { 9281 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS); 9282 Pred = ICmpInst::ICMP_UGT; 9283 Changed = true; 9284 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) { 9285 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS, 9286 SCEV::FlagNUW); 9287 Pred = ICmpInst::ICMP_UGT; 9288 Changed = true; 9289 } 9290 break; 9291 default: 9292 break; 9293 } 9294 9295 // TODO: More simplifications are possible here. 9296 9297 // Recursively simplify until we either hit a recursion limit or nothing 9298 // changes. 9299 if (Changed) 9300 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1); 9301 9302 return Changed; 9303 } 9304 9305 bool ScalarEvolution::isKnownNegative(const SCEV *S) { 9306 return getSignedRangeMax(S).isNegative(); 9307 } 9308 9309 bool ScalarEvolution::isKnownPositive(const SCEV *S) { 9310 return getSignedRangeMin(S).isStrictlyPositive(); 9311 } 9312 9313 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) { 9314 return !getSignedRangeMin(S).isNegative(); 9315 } 9316 9317 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) { 9318 return !getSignedRangeMax(S).isStrictlyPositive(); 9319 } 9320 9321 bool ScalarEvolution::isKnownNonZero(const SCEV *S) { 9322 return isKnownNegative(S) || isKnownPositive(S); 9323 } 9324 9325 std::pair<const SCEV *, const SCEV *> 9326 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) { 9327 // Compute SCEV on entry of loop L. 9328 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this); 9329 if (Start == getCouldNotCompute()) 9330 return { Start, Start }; 9331 // Compute post increment SCEV for loop L. 9332 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this); 9333 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute"); 9334 return { Start, PostInc }; 9335 } 9336 9337 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred, 9338 const SCEV *LHS, const SCEV *RHS) { 9339 // First collect all loops. 9340 SmallPtrSet<const Loop *, 8> LoopsUsed; 9341 getUsedLoops(LHS, LoopsUsed); 9342 getUsedLoops(RHS, LoopsUsed); 9343 9344 if (LoopsUsed.empty()) 9345 return false; 9346 9347 // Domination relationship must be a linear order on collected loops. 9348 #ifndef NDEBUG 9349 for (auto *L1 : LoopsUsed) 9350 for (auto *L2 : LoopsUsed) 9351 assert((DT.dominates(L1->getHeader(), L2->getHeader()) || 9352 DT.dominates(L2->getHeader(), L1->getHeader())) && 9353 "Domination relationship is not a linear order"); 9354 #endif 9355 9356 const Loop *MDL = 9357 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(), 9358 [&](const Loop *L1, const Loop *L2) { 9359 return DT.properlyDominates(L1->getHeader(), L2->getHeader()); 9360 }); 9361 9362 // Get init and post increment value for LHS. 9363 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS); 9364 // if LHS contains unknown non-invariant SCEV then bail out. 9365 if (SplitLHS.first == getCouldNotCompute()) 9366 return false; 9367 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC"); 9368 // Get init and post increment value for RHS. 9369 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS); 9370 // if RHS contains unknown non-invariant SCEV then bail out. 9371 if (SplitRHS.first == getCouldNotCompute()) 9372 return false; 9373 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC"); 9374 // It is possible that init SCEV contains an invariant load but it does 9375 // not dominate MDL and is not available at MDL loop entry, so we should 9376 // check it here. 9377 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) || 9378 !isAvailableAtLoopEntry(SplitRHS.first, MDL)) 9379 return false; 9380 9381 // It seems backedge guard check is faster than entry one so in some cases 9382 // it can speed up whole estimation by short circuit 9383 return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second, 9384 SplitRHS.second) && 9385 isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first); 9386 } 9387 9388 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred, 9389 const SCEV *LHS, const SCEV *RHS) { 9390 // Canonicalize the inputs first. 9391 (void)SimplifyICmpOperands(Pred, LHS, RHS); 9392 9393 if (isKnownViaInduction(Pred, LHS, RHS)) 9394 return true; 9395 9396 if (isKnownPredicateViaSplitting(Pred, LHS, RHS)) 9397 return true; 9398 9399 // Otherwise see what can be done with some simple reasoning. 9400 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS); 9401 } 9402 9403 bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred, 9404 const SCEV *LHS, const SCEV *RHS, 9405 const Instruction *Context) { 9406 // TODO: Analyze guards and assumes from Context's block. 9407 return isKnownPredicate(Pred, LHS, RHS) || 9408 isBasicBlockEntryGuardedByCond(Context->getParent(), Pred, LHS, RHS); 9409 } 9410 9411 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred, 9412 const SCEVAddRecExpr *LHS, 9413 const SCEV *RHS) { 9414 const Loop *L = LHS->getLoop(); 9415 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) && 9416 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS); 9417 } 9418 9419 Optional<ScalarEvolution::MonotonicPredicateType> 9420 ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS, 9421 ICmpInst::Predicate Pred) { 9422 auto Result = getMonotonicPredicateTypeImpl(LHS, Pred); 9423 9424 #ifndef NDEBUG 9425 // Verify an invariant: inverting the predicate should turn a monotonically 9426 // increasing change to a monotonically decreasing one, and vice versa. 9427 if (Result) { 9428 auto ResultSwapped = 9429 getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred)); 9430 9431 assert(ResultSwapped.hasValue() && "should be able to analyze both!"); 9432 assert(ResultSwapped.getValue() != Result.getValue() && 9433 "monotonicity should flip as we flip the predicate"); 9434 } 9435 #endif 9436 9437 return Result; 9438 } 9439 9440 Optional<ScalarEvolution::MonotonicPredicateType> 9441 ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS, 9442 ICmpInst::Predicate Pred) { 9443 // A zero step value for LHS means the induction variable is essentially a 9444 // loop invariant value. We don't really depend on the predicate actually 9445 // flipping from false to true (for increasing predicates, and the other way 9446 // around for decreasing predicates), all we care about is that *if* the 9447 // predicate changes then it only changes from false to true. 9448 // 9449 // A zero step value in itself is not very useful, but there may be places 9450 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be 9451 // as general as possible. 9452 9453 // Only handle LE/LT/GE/GT predicates. 9454 if (!ICmpInst::isRelational(Pred)) 9455 return None; 9456 9457 bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred); 9458 assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) && 9459 "Should be greater or less!"); 9460 9461 // Check that AR does not wrap. 9462 if (ICmpInst::isUnsigned(Pred)) { 9463 if (!LHS->hasNoUnsignedWrap()) 9464 return None; 9465 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9466 } else { 9467 assert(ICmpInst::isSigned(Pred) && 9468 "Relational predicate is either signed or unsigned!"); 9469 if (!LHS->hasNoSignedWrap()) 9470 return None; 9471 9472 const SCEV *Step = LHS->getStepRecurrence(*this); 9473 9474 if (isKnownNonNegative(Step)) 9475 return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9476 9477 if (isKnownNonPositive(Step)) 9478 return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing; 9479 9480 return None; 9481 } 9482 } 9483 9484 bool ScalarEvolution::isLoopInvariantPredicate( 9485 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9486 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9487 const SCEV *&InvariantRHS) { 9488 9489 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9490 if (!isLoopInvariant(RHS, L)) { 9491 if (!isLoopInvariant(LHS, L)) 9492 return false; 9493 9494 std::swap(LHS, RHS); 9495 Pred = ICmpInst::getSwappedPredicate(Pred); 9496 } 9497 9498 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS); 9499 if (!ArLHS || ArLHS->getLoop() != L) 9500 return false; 9501 9502 auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred); 9503 if (!MonotonicType) 9504 return false; 9505 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to 9506 // true as the loop iterates, and the backedge is control dependent on 9507 // "ArLHS `Pred` RHS" == true then we can reason as follows: 9508 // 9509 // * if the predicate was false in the first iteration then the predicate 9510 // is never evaluated again, since the loop exits without taking the 9511 // backedge. 9512 // * if the predicate was true in the first iteration then it will 9513 // continue to be true for all future iterations since it is 9514 // monotonically increasing. 9515 // 9516 // For both the above possibilities, we can replace the loop varying 9517 // predicate with its value on the first iteration of the loop (which is 9518 // loop invariant). 9519 // 9520 // A similar reasoning applies for a monotonically decreasing predicate, by 9521 // replacing true with false and false with true in the above two bullets. 9522 bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing; 9523 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred); 9524 9525 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS)) 9526 return false; 9527 9528 InvariantPred = Pred; 9529 InvariantLHS = ArLHS->getStart(); 9530 InvariantRHS = RHS; 9531 return true; 9532 } 9533 9534 bool ScalarEvolution::isLoopInvariantExitCondDuringFirstIterations( 9535 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, 9536 const Instruction *Context, const SCEV *MaxIter, 9537 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS, 9538 const SCEV *&InvariantRHS) { 9539 // Try to prove the following set of facts: 9540 // - The predicate is monotonic. 9541 // - If the check does not fail on the 1st iteration: 9542 // - No overflow will happen during first MaxIter iterations; 9543 // - It will not fail on the MaxIter'th iteration. 9544 // If the check does fail on the 1st iteration, we leave the loop and no 9545 // other checks matter. 9546 9547 // If there is a loop-invariant, force it into the RHS, otherwise bail out. 9548 if (!isLoopInvariant(RHS, L)) { 9549 if (!isLoopInvariant(LHS, L)) 9550 return false; 9551 9552 std::swap(LHS, RHS); 9553 Pred = ICmpInst::getSwappedPredicate(Pred); 9554 } 9555 9556 auto *AR = dyn_cast<SCEVAddRecExpr>(LHS); 9557 // TODO: Lift affinity limitation in the future. 9558 if (!AR || AR->getLoop() != L || !AR->isAffine()) 9559 return false; 9560 9561 // The predicate must be relational (i.e. <, <=, >=, >). 9562 if (!ICmpInst::isRelational(Pred)) 9563 return false; 9564 9565 // TODO: Support steps other than +/- 1. 9566 const SCEV *Step = AR->getOperand(1); 9567 auto *One = getOne(Step->getType()); 9568 auto *MinusOne = getNegativeSCEV(One); 9569 if (Step != One && Step != MinusOne) 9570 return false; 9571 9572 // Type mismatch here means that MaxIter is potentially larger than max 9573 // unsigned value in start type, which mean we cannot prove no wrap for the 9574 // indvar. 9575 if (AR->getType() != MaxIter->getType()) 9576 return false; 9577 9578 // Value of IV on suggested last iteration. 9579 const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this); 9580 // Does it still meet the requirement? 9581 if (!isKnownPredicateAt(Pred, Last, RHS, Context)) 9582 return false; 9583 // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does 9584 // not exceed max unsigned value of this type), this effectively proves 9585 // that there is no wrap during the iteration. To prove that there is no 9586 // signed/unsigned wrap, we need to check that 9587 // Start <= Last for step = 1 or Start >= Last for step = -1. 9588 ICmpInst::Predicate NoOverflowPred = 9589 CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; 9590 if (Step == MinusOne) 9591 NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred); 9592 const SCEV *Start = AR->getStart(); 9593 if (!isKnownPredicateAt(NoOverflowPred, Start, Last, Context)) 9594 return false; 9595 9596 // Everything is fine. 9597 InvariantPred = Pred; 9598 InvariantLHS = Start; 9599 InvariantRHS = RHS; 9600 return true; 9601 } 9602 9603 bool ScalarEvolution::isKnownPredicateViaConstantRanges( 9604 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) { 9605 if (HasSameValue(LHS, RHS)) 9606 return ICmpInst::isTrueWhenEqual(Pred); 9607 9608 // This code is split out from isKnownPredicate because it is called from 9609 // within isLoopEntryGuardedByCond. 9610 9611 auto CheckRanges = 9612 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) { 9613 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS) 9614 .contains(RangeLHS); 9615 }; 9616 9617 // The check at the top of the function catches the case where the values are 9618 // known to be equal. 9619 if (Pred == CmpInst::ICMP_EQ) 9620 return false; 9621 9622 if (Pred == CmpInst::ICMP_NE) 9623 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) || 9624 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) || 9625 isKnownNonZero(getMinusSCEV(LHS, RHS)); 9626 9627 if (CmpInst::isSigned(Pred)) 9628 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)); 9629 9630 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)); 9631 } 9632 9633 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, 9634 const SCEV *LHS, 9635 const SCEV *RHS) { 9636 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer. 9637 // Return Y via OutY. 9638 auto MatchBinaryAddToConst = 9639 [this](const SCEV *Result, const SCEV *X, APInt &OutY, 9640 SCEV::NoWrapFlags ExpectedFlags) { 9641 const SCEV *NonConstOp, *ConstOp; 9642 SCEV::NoWrapFlags FlagsPresent; 9643 9644 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) || 9645 !isa<SCEVConstant>(ConstOp) || NonConstOp != X) 9646 return false; 9647 9648 OutY = cast<SCEVConstant>(ConstOp)->getAPInt(); 9649 return (FlagsPresent & ExpectedFlags) == ExpectedFlags; 9650 }; 9651 9652 APInt C; 9653 9654 switch (Pred) { 9655 default: 9656 break; 9657 9658 case ICmpInst::ICMP_SGE: 9659 std::swap(LHS, RHS); 9660 LLVM_FALLTHROUGH; 9661 case ICmpInst::ICMP_SLE: 9662 // X s<= (X + C)<nsw> if C >= 0 9663 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative()) 9664 return true; 9665 9666 // (X + C)<nsw> s<= X if C <= 0 9667 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && 9668 !C.isStrictlyPositive()) 9669 return true; 9670 break; 9671 9672 case ICmpInst::ICMP_SGT: 9673 std::swap(LHS, RHS); 9674 LLVM_FALLTHROUGH; 9675 case ICmpInst::ICMP_SLT: 9676 // X s< (X + C)<nsw> if C > 0 9677 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && 9678 C.isStrictlyPositive()) 9679 return true; 9680 9681 // (X + C)<nsw> s< X if C < 0 9682 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative()) 9683 return true; 9684 break; 9685 9686 case ICmpInst::ICMP_UGE: 9687 std::swap(LHS, RHS); 9688 LLVM_FALLTHROUGH; 9689 case ICmpInst::ICMP_ULE: 9690 // X u<= (X + C)<nuw> for any C 9691 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW)) 9692 return true; 9693 break; 9694 9695 case ICmpInst::ICMP_UGT: 9696 std::swap(LHS, RHS); 9697 LLVM_FALLTHROUGH; 9698 case ICmpInst::ICMP_ULT: 9699 // X u< (X + C)<nuw> if C != 0 9700 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNUW) && !C.isNullValue()) 9701 return true; 9702 break; 9703 } 9704 9705 return false; 9706 } 9707 9708 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, 9709 const SCEV *LHS, 9710 const SCEV *RHS) { 9711 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate) 9712 return false; 9713 9714 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on 9715 // the stack can result in exponential time complexity. 9716 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true); 9717 9718 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L 9719 // 9720 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use 9721 // isKnownPredicate. isKnownPredicate is more powerful, but also more 9722 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the 9723 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to 9724 // use isKnownPredicate later if needed. 9725 return isKnownNonNegative(RHS) && 9726 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) && 9727 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS); 9728 } 9729 9730 bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB, 9731 ICmpInst::Predicate Pred, 9732 const SCEV *LHS, const SCEV *RHS) { 9733 // No need to even try if we know the module has no guards. 9734 if (!HasGuards) 9735 return false; 9736 9737 return any_of(*BB, [&](const Instruction &I) { 9738 using namespace llvm::PatternMatch; 9739 9740 Value *Condition; 9741 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>( 9742 m_Value(Condition))) && 9743 isImpliedCond(Pred, LHS, RHS, Condition, false); 9744 }); 9745 } 9746 9747 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 9748 /// protected by a conditional between LHS and RHS. This is used to 9749 /// to eliminate casts. 9750 bool 9751 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L, 9752 ICmpInst::Predicate Pred, 9753 const SCEV *LHS, const SCEV *RHS) { 9754 // Interpret a null as meaning no loop, where there is obviously no guard 9755 // (interprocedural conditions notwithstanding). 9756 if (!L) return true; 9757 9758 if (VerifyIR) 9759 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) && 9760 "This cannot be done on broken IR!"); 9761 9762 9763 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9764 return true; 9765 9766 BasicBlock *Latch = L->getLoopLatch(); 9767 if (!Latch) 9768 return false; 9769 9770 BranchInst *LoopContinuePredicate = 9771 dyn_cast<BranchInst>(Latch->getTerminator()); 9772 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() && 9773 isImpliedCond(Pred, LHS, RHS, 9774 LoopContinuePredicate->getCondition(), 9775 LoopContinuePredicate->getSuccessor(0) != L->getHeader())) 9776 return true; 9777 9778 // We don't want more than one activation of the following loops on the stack 9779 // -- that can lead to O(n!) time complexity. 9780 if (WalkingBEDominatingConds) 9781 return false; 9782 9783 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true); 9784 9785 // See if we can exploit a trip count to prove the predicate. 9786 const auto &BETakenInfo = getBackedgeTakenInfo(L); 9787 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this); 9788 if (LatchBECount != getCouldNotCompute()) { 9789 // We know that Latch branches back to the loop header exactly 9790 // LatchBECount times. This means the backdege condition at Latch is 9791 // equivalent to "{0,+,1} u< LatchBECount". 9792 Type *Ty = LatchBECount->getType(); 9793 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW); 9794 const SCEV *LoopCounter = 9795 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags); 9796 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter, 9797 LatchBECount)) 9798 return true; 9799 } 9800 9801 // Check conditions due to any @llvm.assume intrinsics. 9802 for (auto &AssumeVH : AC.assumptions()) { 9803 if (!AssumeVH) 9804 continue; 9805 auto *CI = cast<CallInst>(AssumeVH); 9806 if (!DT.dominates(CI, Latch->getTerminator())) 9807 continue; 9808 9809 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false)) 9810 return true; 9811 } 9812 9813 // If the loop is not reachable from the entry block, we risk running into an 9814 // infinite loop as we walk up into the dom tree. These loops do not matter 9815 // anyway, so we just return a conservative answer when we see them. 9816 if (!DT.isReachableFromEntry(L->getHeader())) 9817 return false; 9818 9819 if (isImpliedViaGuard(Latch, Pred, LHS, RHS)) 9820 return true; 9821 9822 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()]; 9823 DTN != HeaderDTN; DTN = DTN->getIDom()) { 9824 assert(DTN && "should reach the loop header before reaching the root!"); 9825 9826 BasicBlock *BB = DTN->getBlock(); 9827 if (isImpliedViaGuard(BB, Pred, LHS, RHS)) 9828 return true; 9829 9830 BasicBlock *PBB = BB->getSinglePredecessor(); 9831 if (!PBB) 9832 continue; 9833 9834 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator()); 9835 if (!ContinuePredicate || !ContinuePredicate->isConditional()) 9836 continue; 9837 9838 Value *Condition = ContinuePredicate->getCondition(); 9839 9840 // If we have an edge `E` within the loop body that dominates the only 9841 // latch, the condition guarding `E` also guards the backedge. This 9842 // reasoning works only for loops with a single latch. 9843 9844 BasicBlockEdge DominatingEdge(PBB, BB); 9845 if (DominatingEdge.isSingleEdge()) { 9846 // We're constructively (and conservatively) enumerating edges within the 9847 // loop body that dominate the latch. The dominator tree better agree 9848 // with us on this: 9849 assert(DT.dominates(DominatingEdge, Latch) && "should be!"); 9850 9851 if (isImpliedCond(Pred, LHS, RHS, Condition, 9852 BB != ContinuePredicate->getSuccessor(0))) 9853 return true; 9854 } 9855 } 9856 9857 return false; 9858 } 9859 9860 bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB, 9861 ICmpInst::Predicate Pred, 9862 const SCEV *LHS, 9863 const SCEV *RHS) { 9864 if (VerifyIR) 9865 assert(!verifyFunction(*BB->getParent(), &dbgs()) && 9866 "This cannot be done on broken IR!"); 9867 9868 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS)) 9869 return true; 9870 9871 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove 9872 // the facts (a >= b && a != b) separately. A typical situation is when the 9873 // non-strict comparison is known from ranges and non-equality is known from 9874 // dominating predicates. If we are proving strict comparison, we always try 9875 // to prove non-equality and non-strict comparison separately. 9876 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred); 9877 const bool ProvingStrictComparison = (Pred != NonStrictPredicate); 9878 bool ProvedNonStrictComparison = false; 9879 bool ProvedNonEquality = false; 9880 9881 if (ProvingStrictComparison) { 9882 ProvedNonStrictComparison = 9883 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS); 9884 ProvedNonEquality = 9885 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS); 9886 if (ProvedNonStrictComparison && ProvedNonEquality) 9887 return true; 9888 } 9889 9890 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard. 9891 auto ProveViaGuard = [&](const BasicBlock *Block) { 9892 if (isImpliedViaGuard(Block, Pred, LHS, RHS)) 9893 return true; 9894 if (ProvingStrictComparison) { 9895 if (!ProvedNonStrictComparison) 9896 ProvedNonStrictComparison = 9897 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS); 9898 if (!ProvedNonEquality) 9899 ProvedNonEquality = 9900 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS); 9901 if (ProvedNonStrictComparison && ProvedNonEquality) 9902 return true; 9903 } 9904 return false; 9905 }; 9906 9907 // Try to prove (Pred, LHS, RHS) using isImpliedCond. 9908 auto ProveViaCond = [&](const Value *Condition, bool Inverse) { 9909 const Instruction *Context = &BB->front(); 9910 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, Context)) 9911 return true; 9912 if (ProvingStrictComparison) { 9913 if (!ProvedNonStrictComparison) 9914 ProvedNonStrictComparison = isImpliedCond(NonStrictPredicate, LHS, RHS, 9915 Condition, Inverse, Context); 9916 if (!ProvedNonEquality) 9917 ProvedNonEquality = isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, 9918 Condition, Inverse, Context); 9919 if (ProvedNonStrictComparison && ProvedNonEquality) 9920 return true; 9921 } 9922 return false; 9923 }; 9924 9925 // Starting at the block's predecessor, climb up the predecessor chain, as long 9926 // as there are predecessors that can be found that have unique successors 9927 // leading to the original block. 9928 const Loop *ContainingLoop = LI.getLoopFor(BB); 9929 const BasicBlock *PredBB; 9930 if (ContainingLoop && ContainingLoop->getHeader() == BB) 9931 PredBB = ContainingLoop->getLoopPredecessor(); 9932 else 9933 PredBB = BB->getSinglePredecessor(); 9934 for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB); 9935 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 9936 if (ProveViaGuard(Pair.first)) 9937 return true; 9938 9939 const BranchInst *LoopEntryPredicate = 9940 dyn_cast<BranchInst>(Pair.first->getTerminator()); 9941 if (!LoopEntryPredicate || 9942 LoopEntryPredicate->isUnconditional()) 9943 continue; 9944 9945 if (ProveViaCond(LoopEntryPredicate->getCondition(), 9946 LoopEntryPredicate->getSuccessor(0) != Pair.second)) 9947 return true; 9948 } 9949 9950 // Check conditions due to any @llvm.assume intrinsics. 9951 for (auto &AssumeVH : AC.assumptions()) { 9952 if (!AssumeVH) 9953 continue; 9954 auto *CI = cast<CallInst>(AssumeVH); 9955 if (!DT.dominates(CI, BB)) 9956 continue; 9957 9958 if (ProveViaCond(CI->getArgOperand(0), false)) 9959 return true; 9960 } 9961 9962 return false; 9963 } 9964 9965 bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L, 9966 ICmpInst::Predicate Pred, 9967 const SCEV *LHS, 9968 const SCEV *RHS) { 9969 // Interpret a null as meaning no loop, where there is obviously no guard 9970 // (interprocedural conditions notwithstanding). 9971 if (!L) 9972 return false; 9973 9974 // Both LHS and RHS must be available at loop entry. 9975 assert(isAvailableAtLoopEntry(LHS, L) && 9976 "LHS is not available at Loop Entry"); 9977 assert(isAvailableAtLoopEntry(RHS, L) && 9978 "RHS is not available at Loop Entry"); 9979 return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS); 9980 } 9981 9982 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 9983 const SCEV *RHS, 9984 const Value *FoundCondValue, bool Inverse, 9985 const Instruction *Context) { 9986 if (!PendingLoopPredicates.insert(FoundCondValue).second) 9987 return false; 9988 9989 auto ClearOnExit = 9990 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); }); 9991 9992 // Recursively handle And and Or conditions. 9993 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) { 9994 if (BO->getOpcode() == Instruction::And) { 9995 if (!Inverse) 9996 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 9997 Context) || 9998 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 9999 Context); 10000 } else if (BO->getOpcode() == Instruction::Or) { 10001 if (Inverse) 10002 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse, 10003 Context) || 10004 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse, 10005 Context); 10006 } 10007 } 10008 10009 const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue); 10010 if (!ICI) return false; 10011 10012 // Now that we found a conditional branch that dominates the loop or controls 10013 // the loop latch. Check to see if it is the comparison we are looking for. 10014 ICmpInst::Predicate FoundPred; 10015 if (Inverse) 10016 FoundPred = ICI->getInversePredicate(); 10017 else 10018 FoundPred = ICI->getPredicate(); 10019 10020 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0)); 10021 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1)); 10022 10023 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, Context); 10024 } 10025 10026 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, 10027 const SCEV *RHS, 10028 ICmpInst::Predicate FoundPred, 10029 const SCEV *FoundLHS, const SCEV *FoundRHS, 10030 const Instruction *Context) { 10031 // Balance the types. 10032 if (getTypeSizeInBits(LHS->getType()) < 10033 getTypeSizeInBits(FoundLHS->getType())) { 10034 // For unsigned and equality predicates, try to prove that both found 10035 // operands fit into narrow unsigned range. If so, try to prove facts in 10036 // narrow types. 10037 if (!CmpInst::isSigned(FoundPred)) { 10038 auto *NarrowType = LHS->getType(); 10039 auto *WideType = FoundLHS->getType(); 10040 auto BitWidth = getTypeSizeInBits(NarrowType); 10041 const SCEV *MaxValue = getZeroExtendExpr( 10042 getConstant(APInt::getMaxValue(BitWidth)), WideType); 10043 if (isKnownPredicate(ICmpInst::ICMP_ULE, FoundLHS, MaxValue) && 10044 isKnownPredicate(ICmpInst::ICMP_ULE, FoundRHS, MaxValue)) { 10045 const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType); 10046 const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType); 10047 if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS, 10048 TruncFoundRHS, Context)) 10049 return true; 10050 } 10051 } 10052 10053 if (CmpInst::isSigned(Pred)) { 10054 LHS = getSignExtendExpr(LHS, FoundLHS->getType()); 10055 RHS = getSignExtendExpr(RHS, FoundLHS->getType()); 10056 } else { 10057 LHS = getZeroExtendExpr(LHS, FoundLHS->getType()); 10058 RHS = getZeroExtendExpr(RHS, FoundLHS->getType()); 10059 } 10060 } else if (getTypeSizeInBits(LHS->getType()) > 10061 getTypeSizeInBits(FoundLHS->getType())) { 10062 if (CmpInst::isSigned(FoundPred)) { 10063 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType()); 10064 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType()); 10065 } else { 10066 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType()); 10067 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType()); 10068 } 10069 } 10070 return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS, 10071 FoundRHS, Context); 10072 } 10073 10074 bool ScalarEvolution::isImpliedCondBalancedTypes( 10075 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10076 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS, 10077 const Instruction *Context) { 10078 assert(getTypeSizeInBits(LHS->getType()) == 10079 getTypeSizeInBits(FoundLHS->getType()) && 10080 "Types should be balanced!"); 10081 // Canonicalize the query to match the way instcombine will have 10082 // canonicalized the comparison. 10083 if (SimplifyICmpOperands(Pred, LHS, RHS)) 10084 if (LHS == RHS) 10085 return CmpInst::isTrueWhenEqual(Pred); 10086 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS)) 10087 if (FoundLHS == FoundRHS) 10088 return CmpInst::isFalseWhenEqual(FoundPred); 10089 10090 // Check to see if we can make the LHS or RHS match. 10091 if (LHS == FoundRHS || RHS == FoundLHS) { 10092 if (isa<SCEVConstant>(RHS)) { 10093 std::swap(FoundLHS, FoundRHS); 10094 FoundPred = ICmpInst::getSwappedPredicate(FoundPred); 10095 } else { 10096 std::swap(LHS, RHS); 10097 Pred = ICmpInst::getSwappedPredicate(Pred); 10098 } 10099 } 10100 10101 // Check whether the found predicate is the same as the desired predicate. 10102 if (FoundPred == Pred) 10103 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10104 10105 // Check whether swapping the found predicate makes it the same as the 10106 // desired predicate. 10107 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) { 10108 if (isa<SCEVConstant>(RHS)) 10109 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, Context); 10110 else 10111 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred), RHS, 10112 LHS, FoundLHS, FoundRHS, Context); 10113 } 10114 10115 // Unsigned comparison is the same as signed comparison when both the operands 10116 // are non-negative. 10117 if (CmpInst::isUnsigned(FoundPred) && 10118 CmpInst::getSignedPredicate(FoundPred) == Pred && 10119 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) 10120 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context); 10121 10122 // Check if we can make progress by sharpening ranges. 10123 if (FoundPred == ICmpInst::ICMP_NE && 10124 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) { 10125 10126 const SCEVConstant *C = nullptr; 10127 const SCEV *V = nullptr; 10128 10129 if (isa<SCEVConstant>(FoundLHS)) { 10130 C = cast<SCEVConstant>(FoundLHS); 10131 V = FoundRHS; 10132 } else { 10133 C = cast<SCEVConstant>(FoundRHS); 10134 V = FoundLHS; 10135 } 10136 10137 // The guarding predicate tells us that C != V. If the known range 10138 // of V is [C, t), we can sharpen the range to [C + 1, t). The 10139 // range we consider has to correspond to same signedness as the 10140 // predicate we're interested in folding. 10141 10142 APInt Min = ICmpInst::isSigned(Pred) ? 10143 getSignedRangeMin(V) : getUnsignedRangeMin(V); 10144 10145 if (Min == C->getAPInt()) { 10146 // Given (V >= Min && V != Min) we conclude V >= (Min + 1). 10147 // This is true even if (Min + 1) wraps around -- in case of 10148 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)). 10149 10150 APInt SharperMin = Min + 1; 10151 10152 switch (Pred) { 10153 case ICmpInst::ICMP_SGE: 10154 case ICmpInst::ICMP_UGE: 10155 // We know V `Pred` SharperMin. If this implies LHS `Pred` 10156 // RHS, we're done. 10157 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin), 10158 Context)) 10159 return true; 10160 LLVM_FALLTHROUGH; 10161 10162 case ICmpInst::ICMP_SGT: 10163 case ICmpInst::ICMP_UGT: 10164 // We know from the range information that (V `Pred` Min || 10165 // V == Min). We know from the guarding condition that !(V 10166 // == Min). This gives us 10167 // 10168 // V `Pred` Min || V == Min && !(V == Min) 10169 // => V `Pred` Min 10170 // 10171 // If V `Pred` Min implies LHS `Pred` RHS, we're done. 10172 10173 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), 10174 Context)) 10175 return true; 10176 break; 10177 10178 // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively. 10179 case ICmpInst::ICMP_SLE: 10180 case ICmpInst::ICMP_ULE: 10181 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10182 LHS, V, getConstant(SharperMin), Context)) 10183 return true; 10184 LLVM_FALLTHROUGH; 10185 10186 case ICmpInst::ICMP_SLT: 10187 case ICmpInst::ICMP_ULT: 10188 if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS, 10189 LHS, V, getConstant(Min), Context)) 10190 return true; 10191 break; 10192 10193 default: 10194 // No change 10195 break; 10196 } 10197 } 10198 } 10199 10200 // Check whether the actual condition is beyond sufficient. 10201 if (FoundPred == ICmpInst::ICMP_EQ) 10202 if (ICmpInst::isTrueWhenEqual(Pred)) 10203 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, Context)) 10204 return true; 10205 if (Pred == ICmpInst::ICMP_NE) 10206 if (!ICmpInst::isTrueWhenEqual(FoundPred)) 10207 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, 10208 Context)) 10209 return true; 10210 10211 // Otherwise assume the worst. 10212 return false; 10213 } 10214 10215 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr, 10216 const SCEV *&L, const SCEV *&R, 10217 SCEV::NoWrapFlags &Flags) { 10218 const auto *AE = dyn_cast<SCEVAddExpr>(Expr); 10219 if (!AE || AE->getNumOperands() != 2) 10220 return false; 10221 10222 L = AE->getOperand(0); 10223 R = AE->getOperand(1); 10224 Flags = AE->getNoWrapFlags(); 10225 return true; 10226 } 10227 10228 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More, 10229 const SCEV *Less) { 10230 // We avoid subtracting expressions here because this function is usually 10231 // fairly deep in the call stack (i.e. is called many times). 10232 10233 // X - X = 0. 10234 if (More == Less) 10235 return APInt(getTypeSizeInBits(More->getType()), 0); 10236 10237 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) { 10238 const auto *LAR = cast<SCEVAddRecExpr>(Less); 10239 const auto *MAR = cast<SCEVAddRecExpr>(More); 10240 10241 if (LAR->getLoop() != MAR->getLoop()) 10242 return None; 10243 10244 // We look at affine expressions only; not for correctness but to keep 10245 // getStepRecurrence cheap. 10246 if (!LAR->isAffine() || !MAR->isAffine()) 10247 return None; 10248 10249 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this)) 10250 return None; 10251 10252 Less = LAR->getStart(); 10253 More = MAR->getStart(); 10254 10255 // fall through 10256 } 10257 10258 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) { 10259 const auto &M = cast<SCEVConstant>(More)->getAPInt(); 10260 const auto &L = cast<SCEVConstant>(Less)->getAPInt(); 10261 return M - L; 10262 } 10263 10264 SCEV::NoWrapFlags Flags; 10265 const SCEV *LLess = nullptr, *RLess = nullptr; 10266 const SCEV *LMore = nullptr, *RMore = nullptr; 10267 const SCEVConstant *C1 = nullptr, *C2 = nullptr; 10268 // Compare (X + C1) vs X. 10269 if (splitBinaryAdd(Less, LLess, RLess, Flags)) 10270 if ((C1 = dyn_cast<SCEVConstant>(LLess))) 10271 if (RLess == More) 10272 return -(C1->getAPInt()); 10273 10274 // Compare X vs (X + C2). 10275 if (splitBinaryAdd(More, LMore, RMore, Flags)) 10276 if ((C2 = dyn_cast<SCEVConstant>(LMore))) 10277 if (RMore == Less) 10278 return C2->getAPInt(); 10279 10280 // Compare (X + C1) vs (X + C2). 10281 if (C1 && C2 && RLess == RMore) 10282 return C2->getAPInt() - C1->getAPInt(); 10283 10284 return None; 10285 } 10286 10287 bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart( 10288 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10289 const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *Context) { 10290 // Try to recognize the following pattern: 10291 // 10292 // FoundRHS = ... 10293 // ... 10294 // loop: 10295 // FoundLHS = {Start,+,W} 10296 // context_bb: // Basic block from the same loop 10297 // known(Pred, FoundLHS, FoundRHS) 10298 // 10299 // If some predicate is known in the context of a loop, it is also known on 10300 // each iteration of this loop, including the first iteration. Therefore, in 10301 // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to 10302 // prove the original pred using this fact. 10303 if (!Context) 10304 return false; 10305 const BasicBlock *ContextBB = Context->getParent(); 10306 // Make sure AR varies in the context block. 10307 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) { 10308 const Loop *L = AR->getLoop(); 10309 // Make sure that context belongs to the loop and executes on 1st iteration 10310 // (if it ever executes at all). 10311 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10312 return false; 10313 if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop())) 10314 return false; 10315 return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS); 10316 } 10317 10318 if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) { 10319 const Loop *L = AR->getLoop(); 10320 // Make sure that context belongs to the loop and executes on 1st iteration 10321 // (if it ever executes at all). 10322 if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch())) 10323 return false; 10324 if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop())) 10325 return false; 10326 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart()); 10327 } 10328 10329 return false; 10330 } 10331 10332 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow( 10333 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, 10334 const SCEV *FoundLHS, const SCEV *FoundRHS) { 10335 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT) 10336 return false; 10337 10338 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS); 10339 if (!AddRecLHS) 10340 return false; 10341 10342 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS); 10343 if (!AddRecFoundLHS) 10344 return false; 10345 10346 // We'd like to let SCEV reason about control dependencies, so we constrain 10347 // both the inequalities to be about add recurrences on the same loop. This 10348 // way we can use isLoopEntryGuardedByCond later. 10349 10350 const Loop *L = AddRecFoundLHS->getLoop(); 10351 if (L != AddRecLHS->getLoop()) 10352 return false; 10353 10354 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1) 10355 // 10356 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C) 10357 // ... (2) 10358 // 10359 // Informal proof for (2), assuming (1) [*]: 10360 // 10361 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**] 10362 // 10363 // Then 10364 // 10365 // FoundLHS s< FoundRHS s< INT_MIN - C 10366 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ] 10367 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ] 10368 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s< 10369 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ] 10370 // <=> FoundLHS + C s< FoundRHS + C 10371 // 10372 // [*]: (1) can be proved by ruling out overflow. 10373 // 10374 // [**]: This can be proved by analyzing all the four possibilities: 10375 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and 10376 // (A s>= 0, B s>= 0). 10377 // 10378 // Note: 10379 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C" 10380 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS 10381 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS 10382 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is 10383 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS + 10384 // C)". 10385 10386 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS); 10387 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS); 10388 if (!LDiff || !RDiff || *LDiff != *RDiff) 10389 return false; 10390 10391 if (LDiff->isMinValue()) 10392 return true; 10393 10394 APInt FoundRHSLimit; 10395 10396 if (Pred == CmpInst::ICMP_ULT) { 10397 FoundRHSLimit = -(*RDiff); 10398 } else { 10399 assert(Pred == CmpInst::ICMP_SLT && "Checked above!"); 10400 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff; 10401 } 10402 10403 // Try to prove (1) or (2), as needed. 10404 return isAvailableAtLoopEntry(FoundRHS, L) && 10405 isLoopEntryGuardedByCond(L, Pred, FoundRHS, 10406 getConstant(FoundRHSLimit)); 10407 } 10408 10409 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred, 10410 const SCEV *LHS, const SCEV *RHS, 10411 const SCEV *FoundLHS, 10412 const SCEV *FoundRHS, unsigned Depth) { 10413 const PHINode *LPhi = nullptr, *RPhi = nullptr; 10414 10415 auto ClearOnExit = make_scope_exit([&]() { 10416 if (LPhi) { 10417 bool Erased = PendingMerges.erase(LPhi); 10418 assert(Erased && "Failed to erase LPhi!"); 10419 (void)Erased; 10420 } 10421 if (RPhi) { 10422 bool Erased = PendingMerges.erase(RPhi); 10423 assert(Erased && "Failed to erase RPhi!"); 10424 (void)Erased; 10425 } 10426 }); 10427 10428 // Find respective Phis and check that they are not being pending. 10429 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) 10430 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) { 10431 if (!PendingMerges.insert(Phi).second) 10432 return false; 10433 LPhi = Phi; 10434 } 10435 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS)) 10436 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) { 10437 // If we detect a loop of Phi nodes being processed by this method, for 10438 // example: 10439 // 10440 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ] 10441 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ] 10442 // 10443 // we don't want to deal with a case that complex, so return conservative 10444 // answer false. 10445 if (!PendingMerges.insert(Phi).second) 10446 return false; 10447 RPhi = Phi; 10448 } 10449 10450 // If none of LHS, RHS is a Phi, nothing to do here. 10451 if (!LPhi && !RPhi) 10452 return false; 10453 10454 // If there is a SCEVUnknown Phi we are interested in, make it left. 10455 if (!LPhi) { 10456 std::swap(LHS, RHS); 10457 std::swap(FoundLHS, FoundRHS); 10458 std::swap(LPhi, RPhi); 10459 Pred = ICmpInst::getSwappedPredicate(Pred); 10460 } 10461 10462 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!"); 10463 const BasicBlock *LBB = LPhi->getParent(); 10464 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10465 10466 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) { 10467 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) || 10468 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) || 10469 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth); 10470 }; 10471 10472 if (RPhi && RPhi->getParent() == LBB) { 10473 // Case one: RHS is also a SCEVUnknown Phi from the same basic block. 10474 // If we compare two Phis from the same block, and for each entry block 10475 // the predicate is true for incoming values from this block, then the 10476 // predicate is also true for the Phis. 10477 for (const BasicBlock *IncBB : predecessors(LBB)) { 10478 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10479 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB)); 10480 if (!ProvedEasily(L, R)) 10481 return false; 10482 } 10483 } else if (RAR && RAR->getLoop()->getHeader() == LBB) { 10484 // Case two: RHS is also a Phi from the same basic block, and it is an 10485 // AddRec. It means that there is a loop which has both AddRec and Unknown 10486 // PHIs, for it we can compare incoming values of AddRec from above the loop 10487 // and latch with their respective incoming values of LPhi. 10488 // TODO: Generalize to handle loops with many inputs in a header. 10489 if (LPhi->getNumIncomingValues() != 2) return false; 10490 10491 auto *RLoop = RAR->getLoop(); 10492 auto *Predecessor = RLoop->getLoopPredecessor(); 10493 assert(Predecessor && "Loop with AddRec with no predecessor?"); 10494 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor)); 10495 if (!ProvedEasily(L1, RAR->getStart())) 10496 return false; 10497 auto *Latch = RLoop->getLoopLatch(); 10498 assert(Latch && "Loop with AddRec with no latch?"); 10499 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch)); 10500 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this))) 10501 return false; 10502 } else { 10503 // In all other cases go over inputs of LHS and compare each of them to RHS, 10504 // the predicate is true for (LHS, RHS) if it is true for all such pairs. 10505 // At this point RHS is either a non-Phi, or it is a Phi from some block 10506 // different from LBB. 10507 for (const BasicBlock *IncBB : predecessors(LBB)) { 10508 // Check that RHS is available in this block. 10509 if (!dominates(RHS, IncBB)) 10510 return false; 10511 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB)); 10512 if (!ProvedEasily(L, RHS)) 10513 return false; 10514 } 10515 } 10516 return true; 10517 } 10518 10519 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred, 10520 const SCEV *LHS, const SCEV *RHS, 10521 const SCEV *FoundLHS, 10522 const SCEV *FoundRHS, 10523 const Instruction *Context) { 10524 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10525 return true; 10526 10527 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10528 return true; 10529 10530 if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS, 10531 Context)) 10532 return true; 10533 10534 return isImpliedCondOperandsHelper(Pred, LHS, RHS, 10535 FoundLHS, FoundRHS) || 10536 // ~x < ~y --> x > y 10537 isImpliedCondOperandsHelper(Pred, LHS, RHS, 10538 getNotSCEV(FoundRHS), 10539 getNotSCEV(FoundLHS)); 10540 } 10541 10542 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values? 10543 template <typename MinMaxExprType> 10544 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr, 10545 const SCEV *Candidate) { 10546 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr); 10547 if (!MinMaxExpr) 10548 return false; 10549 10550 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end(); 10551 } 10552 10553 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE, 10554 ICmpInst::Predicate Pred, 10555 const SCEV *LHS, const SCEV *RHS) { 10556 // If both sides are affine addrecs for the same loop, with equal 10557 // steps, and we know the recurrences don't wrap, then we only 10558 // need to check the predicate on the starting values. 10559 10560 if (!ICmpInst::isRelational(Pred)) 10561 return false; 10562 10563 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS); 10564 if (!LAR) 10565 return false; 10566 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS); 10567 if (!RAR) 10568 return false; 10569 if (LAR->getLoop() != RAR->getLoop()) 10570 return false; 10571 if (!LAR->isAffine() || !RAR->isAffine()) 10572 return false; 10573 10574 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE)) 10575 return false; 10576 10577 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ? 10578 SCEV::FlagNSW : SCEV::FlagNUW; 10579 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW)) 10580 return false; 10581 10582 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart()); 10583 } 10584 10585 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max 10586 /// expression? 10587 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE, 10588 ICmpInst::Predicate Pred, 10589 const SCEV *LHS, const SCEV *RHS) { 10590 switch (Pred) { 10591 default: 10592 return false; 10593 10594 case ICmpInst::ICMP_SGE: 10595 std::swap(LHS, RHS); 10596 LLVM_FALLTHROUGH; 10597 case ICmpInst::ICMP_SLE: 10598 return 10599 // min(A, ...) <= A 10600 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) || 10601 // A <= max(A, ...) 10602 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS); 10603 10604 case ICmpInst::ICMP_UGE: 10605 std::swap(LHS, RHS); 10606 LLVM_FALLTHROUGH; 10607 case ICmpInst::ICMP_ULE: 10608 return 10609 // min(A, ...) <= A 10610 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) || 10611 // A <= max(A, ...) 10612 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS); 10613 } 10614 10615 llvm_unreachable("covered switch fell through?!"); 10616 } 10617 10618 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred, 10619 const SCEV *LHS, const SCEV *RHS, 10620 const SCEV *FoundLHS, 10621 const SCEV *FoundRHS, 10622 unsigned Depth) { 10623 assert(getTypeSizeInBits(LHS->getType()) == 10624 getTypeSizeInBits(RHS->getType()) && 10625 "LHS and RHS have different sizes?"); 10626 assert(getTypeSizeInBits(FoundLHS->getType()) == 10627 getTypeSizeInBits(FoundRHS->getType()) && 10628 "FoundLHS and FoundRHS have different sizes?"); 10629 // We want to avoid hurting the compile time with analysis of too big trees. 10630 if (Depth > MaxSCEVOperationsImplicationDepth) 10631 return false; 10632 10633 // We only want to work with GT comparison so far. 10634 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) { 10635 Pred = CmpInst::getSwappedPredicate(Pred); 10636 std::swap(LHS, RHS); 10637 std::swap(FoundLHS, FoundRHS); 10638 } 10639 10640 // For unsigned, try to reduce it to corresponding signed comparison. 10641 if (Pred == ICmpInst::ICMP_UGT) 10642 // We can replace unsigned predicate with its signed counterpart if all 10643 // involved values are non-negative. 10644 // TODO: We could have better support for unsigned. 10645 if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) { 10646 // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing 10647 // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us 10648 // use this fact to prove that LHS and RHS are non-negative. 10649 const SCEV *MinusOne = getMinusOne(LHS->getType()); 10650 if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS, 10651 FoundRHS) && 10652 isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS, 10653 FoundRHS)) 10654 Pred = ICmpInst::ICMP_SGT; 10655 } 10656 10657 if (Pred != ICmpInst::ICMP_SGT) 10658 return false; 10659 10660 auto GetOpFromSExt = [&](const SCEV *S) { 10661 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S)) 10662 return Ext->getOperand(); 10663 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off 10664 // the constant in some cases. 10665 return S; 10666 }; 10667 10668 // Acquire values from extensions. 10669 auto *OrigLHS = LHS; 10670 auto *OrigFoundLHS = FoundLHS; 10671 LHS = GetOpFromSExt(LHS); 10672 FoundLHS = GetOpFromSExt(FoundLHS); 10673 10674 // Is the SGT predicate can be proved trivially or using the found context. 10675 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) { 10676 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) || 10677 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS, 10678 FoundRHS, Depth + 1); 10679 }; 10680 10681 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) { 10682 // We want to avoid creation of any new non-constant SCEV. Since we are 10683 // going to compare the operands to RHS, we should be certain that we don't 10684 // need any size extensions for this. So let's decline all cases when the 10685 // sizes of types of LHS and RHS do not match. 10686 // TODO: Maybe try to get RHS from sext to catch more cases? 10687 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType())) 10688 return false; 10689 10690 // Should not overflow. 10691 if (!LHSAddExpr->hasNoSignedWrap()) 10692 return false; 10693 10694 auto *LL = LHSAddExpr->getOperand(0); 10695 auto *LR = LHSAddExpr->getOperand(1); 10696 auto *MinusOne = getMinusOne(RHS->getType()); 10697 10698 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context. 10699 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) { 10700 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS); 10701 }; 10702 // Try to prove the following rule: 10703 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS). 10704 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS). 10705 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL)) 10706 return true; 10707 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) { 10708 Value *LL, *LR; 10709 // FIXME: Once we have SDiv implemented, we can get rid of this matching. 10710 10711 using namespace llvm::PatternMatch; 10712 10713 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) { 10714 // Rules for division. 10715 // We are going to perform some comparisons with Denominator and its 10716 // derivative expressions. In general case, creating a SCEV for it may 10717 // lead to a complex analysis of the entire graph, and in particular it 10718 // can request trip count recalculation for the same loop. This would 10719 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid 10720 // this, we only want to create SCEVs that are constants in this section. 10721 // So we bail if Denominator is not a constant. 10722 if (!isa<ConstantInt>(LR)) 10723 return false; 10724 10725 auto *Denominator = cast<SCEVConstant>(getSCEV(LR)); 10726 10727 // We want to make sure that LHS = FoundLHS / Denominator. If it is so, 10728 // then a SCEV for the numerator already exists and matches with FoundLHS. 10729 auto *Numerator = getExistingSCEV(LL); 10730 if (!Numerator || Numerator->getType() != FoundLHS->getType()) 10731 return false; 10732 10733 // Make sure that the numerator matches with FoundLHS and the denominator 10734 // is positive. 10735 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator)) 10736 return false; 10737 10738 auto *DTy = Denominator->getType(); 10739 auto *FRHSTy = FoundRHS->getType(); 10740 if (DTy->isPointerTy() != FRHSTy->isPointerTy()) 10741 // One of types is a pointer and another one is not. We cannot extend 10742 // them properly to a wider type, so let us just reject this case. 10743 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help 10744 // to avoid this check. 10745 return false; 10746 10747 // Given that: 10748 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0. 10749 auto *WTy = getWiderType(DTy, FRHSTy); 10750 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy); 10751 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy); 10752 10753 // Try to prove the following rule: 10754 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS). 10755 // For example, given that FoundLHS > 2. It means that FoundLHS is at 10756 // least 3. If we divide it by Denominator < 4, we will have at least 1. 10757 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2)); 10758 if (isKnownNonPositive(RHS) && 10759 IsSGTViaContext(FoundRHSExt, DenomMinusTwo)) 10760 return true; 10761 10762 // Try to prove the following rule: 10763 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS). 10764 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2. 10765 // If we divide it by Denominator > 2, then: 10766 // 1. If FoundLHS is negative, then the result is 0. 10767 // 2. If FoundLHS is non-negative, then the result is non-negative. 10768 // Anyways, the result is non-negative. 10769 auto *MinusOne = getMinusOne(WTy); 10770 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt); 10771 if (isKnownNegative(RHS) && 10772 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne)) 10773 return true; 10774 } 10775 } 10776 10777 // If our expression contained SCEVUnknown Phis, and we split it down and now 10778 // need to prove something for them, try to prove the predicate for every 10779 // possible incoming values of those Phis. 10780 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1)) 10781 return true; 10782 10783 return false; 10784 } 10785 10786 static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred, 10787 const SCEV *LHS, const SCEV *RHS) { 10788 // zext x u<= sext x, sext x s<= zext x 10789 switch (Pred) { 10790 case ICmpInst::ICMP_SGE: 10791 std::swap(LHS, RHS); 10792 LLVM_FALLTHROUGH; 10793 case ICmpInst::ICMP_SLE: { 10794 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt. 10795 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS); 10796 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS); 10797 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10798 return true; 10799 break; 10800 } 10801 case ICmpInst::ICMP_UGE: 10802 std::swap(LHS, RHS); 10803 LLVM_FALLTHROUGH; 10804 case ICmpInst::ICMP_ULE: { 10805 // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt. 10806 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS); 10807 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS); 10808 if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand()) 10809 return true; 10810 break; 10811 } 10812 default: 10813 break; 10814 }; 10815 return false; 10816 } 10817 10818 bool 10819 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred, 10820 const SCEV *LHS, const SCEV *RHS) { 10821 return isKnownPredicateExtendIdiom(Pred, LHS, RHS) || 10822 isKnownPredicateViaConstantRanges(Pred, LHS, RHS) || 10823 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) || 10824 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) || 10825 isKnownPredicateViaNoOverflow(Pred, LHS, RHS); 10826 } 10827 10828 bool 10829 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 10830 const SCEV *LHS, const SCEV *RHS, 10831 const SCEV *FoundLHS, 10832 const SCEV *FoundRHS) { 10833 switch (Pred) { 10834 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!"); 10835 case ICmpInst::ICMP_EQ: 10836 case ICmpInst::ICMP_NE: 10837 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS)) 10838 return true; 10839 break; 10840 case ICmpInst::ICMP_SLT: 10841 case ICmpInst::ICMP_SLE: 10842 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) && 10843 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS)) 10844 return true; 10845 break; 10846 case ICmpInst::ICMP_SGT: 10847 case ICmpInst::ICMP_SGE: 10848 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) && 10849 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS)) 10850 return true; 10851 break; 10852 case ICmpInst::ICMP_ULT: 10853 case ICmpInst::ICMP_ULE: 10854 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) && 10855 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS)) 10856 return true; 10857 break; 10858 case ICmpInst::ICMP_UGT: 10859 case ICmpInst::ICMP_UGE: 10860 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) && 10861 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS)) 10862 return true; 10863 break; 10864 } 10865 10866 // Maybe it can be proved via operations? 10867 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS)) 10868 return true; 10869 10870 return false; 10871 } 10872 10873 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, 10874 const SCEV *LHS, 10875 const SCEV *RHS, 10876 const SCEV *FoundLHS, 10877 const SCEV *FoundRHS) { 10878 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS)) 10879 // The restriction on `FoundRHS` be lifted easily -- it exists only to 10880 // reduce the compile time impact of this optimization. 10881 return false; 10882 10883 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS); 10884 if (!Addend) 10885 return false; 10886 10887 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt(); 10888 10889 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the 10890 // antecedent "`FoundLHS` `Pred` `FoundRHS`". 10891 ConstantRange FoundLHSRange = 10892 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS); 10893 10894 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`: 10895 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend)); 10896 10897 // We can also compute the range of values for `LHS` that satisfy the 10898 // consequent, "`LHS` `Pred` `RHS`": 10899 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt(); 10900 ConstantRange SatisfyingLHSRange = 10901 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS); 10902 10903 // The antecedent implies the consequent if every value of `LHS` that 10904 // satisfies the antecedent also satisfies the consequent. 10905 return SatisfyingLHSRange.contains(LHSRange); 10906 } 10907 10908 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 10909 bool IsSigned, bool NoWrap) { 10910 assert(isKnownPositive(Stride) && "Positive stride expected!"); 10911 10912 if (NoWrap) return false; 10913 10914 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10915 const SCEV *One = getOne(Stride->getType()); 10916 10917 if (IsSigned) { 10918 APInt MaxRHS = getSignedRangeMax(RHS); 10919 APInt MaxValue = APInt::getSignedMaxValue(BitWidth); 10920 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10921 10922 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow! 10923 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS); 10924 } 10925 10926 APInt MaxRHS = getUnsignedRangeMax(RHS); 10927 APInt MaxValue = APInt::getMaxValue(BitWidth); 10928 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10929 10930 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow! 10931 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS); 10932 } 10933 10934 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 10935 bool IsSigned, bool NoWrap) { 10936 if (NoWrap) return false; 10937 10938 unsigned BitWidth = getTypeSizeInBits(RHS->getType()); 10939 const SCEV *One = getOne(Stride->getType()); 10940 10941 if (IsSigned) { 10942 APInt MinRHS = getSignedRangeMin(RHS); 10943 APInt MinValue = APInt::getSignedMinValue(BitWidth); 10944 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One)); 10945 10946 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow! 10947 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS); 10948 } 10949 10950 APInt MinRHS = getUnsignedRangeMin(RHS); 10951 APInt MinValue = APInt::getMinValue(BitWidth); 10952 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One)); 10953 10954 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow! 10955 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS); 10956 } 10957 10958 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step, 10959 bool Equality) { 10960 const SCEV *One = getOne(Step->getType()); 10961 Delta = Equality ? getAddExpr(Delta, Step) 10962 : getAddExpr(Delta, getMinusSCEV(Step, One)); 10963 return getUDivExpr(Delta, Step); 10964 } 10965 10966 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start, 10967 const SCEV *Stride, 10968 const SCEV *End, 10969 unsigned BitWidth, 10970 bool IsSigned) { 10971 10972 assert(!isKnownNonPositive(Stride) && 10973 "Stride is expected strictly positive!"); 10974 // Calculate the maximum backedge count based on the range of values 10975 // permitted by Start, End, and Stride. 10976 const SCEV *MaxBECount; 10977 APInt MinStart = 10978 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start); 10979 10980 APInt StrideForMaxBECount = 10981 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride); 10982 10983 // We already know that the stride is positive, so we paper over conservatism 10984 // in our range computation by forcing StrideForMaxBECount to be at least one. 10985 // In theory this is unnecessary, but we expect MaxBECount to be a 10986 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there 10987 // is nothing to constant fold it to). 10988 APInt One(BitWidth, 1, IsSigned); 10989 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount); 10990 10991 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth) 10992 : APInt::getMaxValue(BitWidth); 10993 APInt Limit = MaxValue - (StrideForMaxBECount - 1); 10994 10995 // Although End can be a MAX expression we estimate MaxEnd considering only 10996 // the case End = RHS of the loop termination condition. This is safe because 10997 // in the other case (End - Start) is zero, leading to a zero maximum backedge 10998 // taken count. 10999 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit) 11000 : APIntOps::umin(getUnsignedRangeMax(End), Limit); 11001 11002 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */, 11003 getConstant(StrideForMaxBECount) /* Step */, 11004 false /* Equality */); 11005 11006 return MaxBECount; 11007 } 11008 11009 ScalarEvolution::ExitLimit 11010 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS, 11011 const Loop *L, bool IsSigned, 11012 bool ControlsExit, bool AllowPredicates) { 11013 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11014 11015 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11016 bool PredicatedIV = false; 11017 11018 if (!IV && AllowPredicates) { 11019 // Try to make this an AddRec using runtime tests, in the first X 11020 // iterations of this loop, where X is the SCEV expression found by the 11021 // algorithm below. 11022 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11023 PredicatedIV = true; 11024 } 11025 11026 // Avoid weird loops 11027 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11028 return getCouldNotCompute(); 11029 11030 bool NoWrap = ControlsExit && 11031 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11032 11033 const SCEV *Stride = IV->getStepRecurrence(*this); 11034 11035 bool PositiveStride = isKnownPositive(Stride); 11036 11037 // Avoid negative or zero stride values. 11038 if (!PositiveStride) { 11039 // We can compute the correct backedge taken count for loops with unknown 11040 // strides if we can prove that the loop is not an infinite loop with side 11041 // effects. Here's the loop structure we are trying to handle - 11042 // 11043 // i = start 11044 // do { 11045 // A[i] = i; 11046 // i += s; 11047 // } while (i < end); 11048 // 11049 // The backedge taken count for such loops is evaluated as - 11050 // (max(end, start + stride) - start - 1) /u stride 11051 // 11052 // The additional preconditions that we need to check to prove correctness 11053 // of the above formula is as follows - 11054 // 11055 // a) IV is either nuw or nsw depending upon signedness (indicated by the 11056 // NoWrap flag). 11057 // b) loop is single exit with no side effects. 11058 // 11059 // 11060 // Precondition a) implies that if the stride is negative, this is a single 11061 // trip loop. The backedge taken count formula reduces to zero in this case. 11062 // 11063 // Precondition b) implies that the unknown stride cannot be zero otherwise 11064 // we have UB. 11065 // 11066 // The positive stride case is the same as isKnownPositive(Stride) returning 11067 // true (original behavior of the function). 11068 // 11069 // We want to make sure that the stride is truly unknown as there are edge 11070 // cases where ScalarEvolution propagates no wrap flags to the 11071 // post-increment/decrement IV even though the increment/decrement operation 11072 // itself is wrapping. The computed backedge taken count may be wrong in 11073 // such cases. This is prevented by checking that the stride is not known to 11074 // be either positive or non-positive. For example, no wrap flags are 11075 // propagated to the post-increment IV of this loop with a trip count of 2 - 11076 // 11077 // unsigned char i; 11078 // for(i=127; i<128; i+=129) 11079 // A[i] = i; 11080 // 11081 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) || 11082 !loopHasNoSideEffects(L)) 11083 return getCouldNotCompute(); 11084 } else if (!Stride->isOne() && 11085 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap)) 11086 // Avoid proven overflow cases: this will ensure that the backedge taken 11087 // count will not generate any unsigned overflow. Relaxed no-overflow 11088 // conditions exploit NoWrapFlags, allowing to optimize in presence of 11089 // undefined behaviors like the case of C language. 11090 return getCouldNotCompute(); 11091 11092 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT 11093 : ICmpInst::ICMP_ULT; 11094 const SCEV *Start = IV->getStart(); 11095 const SCEV *End = RHS; 11096 // When the RHS is not invariant, we do not know the end bound of the loop and 11097 // cannot calculate the ExactBECount needed by ExitLimit. However, we can 11098 // calculate the MaxBECount, given the start, stride and max value for the end 11099 // bound of the loop (RHS), and the fact that IV does not overflow (which is 11100 // checked above). 11101 if (!isLoopInvariant(RHS, L)) { 11102 const SCEV *MaxBECount = computeMaxBECountForLT( 11103 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11104 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount, 11105 false /*MaxOrZero*/, Predicates); 11106 } 11107 // If the backedge is taken at least once, then it will be taken 11108 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start 11109 // is the LHS value of the less-than comparison the first time it is evaluated 11110 // and End is the RHS. 11111 const SCEV *BECountIfBackedgeTaken = 11112 computeBECount(getMinusSCEV(End, Start), Stride, false); 11113 // If the loop entry is guarded by the result of the backedge test of the 11114 // first loop iteration, then we know the backedge will be taken at least 11115 // once and so the backedge taken count is as above. If not then we use the 11116 // expression (max(End,Start)-Start)/Stride to describe the backedge count, 11117 // as if the backedge is taken at least once max(End,Start) is End and so the 11118 // result is as above, and if not max(End,Start) is Start so we get a backedge 11119 // count of zero. 11120 const SCEV *BECount; 11121 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) 11122 BECount = BECountIfBackedgeTaken; 11123 else { 11124 // If we know that RHS >= Start in the context of loop, then we know that 11125 // max(RHS, Start) = RHS at this point. 11126 if (isLoopEntryGuardedByCond( 11127 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, RHS, Start)) 11128 End = RHS; 11129 else 11130 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start); 11131 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false); 11132 } 11133 11134 const SCEV *MaxBECount; 11135 bool MaxOrZero = false; 11136 if (isa<SCEVConstant>(BECount)) 11137 MaxBECount = BECount; 11138 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) { 11139 // If we know exactly how many times the backedge will be taken if it's 11140 // taken at least once, then the backedge count will either be that or 11141 // zero. 11142 MaxBECount = BECountIfBackedgeTaken; 11143 MaxOrZero = true; 11144 } else { 11145 MaxBECount = computeMaxBECountForLT( 11146 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned); 11147 } 11148 11149 if (isa<SCEVCouldNotCompute>(MaxBECount) && 11150 !isa<SCEVCouldNotCompute>(BECount)) 11151 MaxBECount = getConstant(getUnsignedRangeMax(BECount)); 11152 11153 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates); 11154 } 11155 11156 ScalarEvolution::ExitLimit 11157 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 11158 const Loop *L, bool IsSigned, 11159 bool ControlsExit, bool AllowPredicates) { 11160 SmallPtrSet<const SCEVPredicate *, 4> Predicates; 11161 // We handle only IV > Invariant 11162 if (!isLoopInvariant(RHS, L)) 11163 return getCouldNotCompute(); 11164 11165 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS); 11166 if (!IV && AllowPredicates) 11167 // Try to make this an AddRec using runtime tests, in the first X 11168 // iterations of this loop, where X is the SCEV expression found by the 11169 // algorithm below. 11170 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates); 11171 11172 // Avoid weird loops 11173 if (!IV || IV->getLoop() != L || !IV->isAffine()) 11174 return getCouldNotCompute(); 11175 11176 bool NoWrap = ControlsExit && 11177 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW); 11178 11179 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this)); 11180 11181 // Avoid negative or zero stride values 11182 if (!isKnownPositive(Stride)) 11183 return getCouldNotCompute(); 11184 11185 // Avoid proven overflow cases: this will ensure that the backedge taken count 11186 // will not generate any unsigned overflow. Relaxed no-overflow conditions 11187 // exploit NoWrapFlags, allowing to optimize in presence of undefined 11188 // behaviors like the case of C language. 11189 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap)) 11190 return getCouldNotCompute(); 11191 11192 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT 11193 : ICmpInst::ICMP_UGT; 11194 11195 const SCEV *Start = IV->getStart(); 11196 const SCEV *End = RHS; 11197 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) { 11198 // If we know that Start >= RHS in the context of loop, then we know that 11199 // min(RHS, Start) = RHS at this point. 11200 if (isLoopEntryGuardedByCond( 11201 L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS)) 11202 End = RHS; 11203 else 11204 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start); 11205 } 11206 11207 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false); 11208 11209 APInt MaxStart = IsSigned ? getSignedRangeMax(Start) 11210 : getUnsignedRangeMax(Start); 11211 11212 APInt MinStride = IsSigned ? getSignedRangeMin(Stride) 11213 : getUnsignedRangeMin(Stride); 11214 11215 unsigned BitWidth = getTypeSizeInBits(LHS->getType()); 11216 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1) 11217 : APInt::getMinValue(BitWidth) + (MinStride - 1); 11218 11219 // Although End can be a MIN expression we estimate MinEnd considering only 11220 // the case End = RHS. This is safe because in the other case (Start - End) 11221 // is zero, leading to a zero maximum backedge taken count. 11222 APInt MinEnd = 11223 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit) 11224 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit); 11225 11226 const SCEV *MaxBECount = isa<SCEVConstant>(BECount) 11227 ? BECount 11228 : computeBECount(getConstant(MaxStart - MinEnd), 11229 getConstant(MinStride), false); 11230 11231 if (isa<SCEVCouldNotCompute>(MaxBECount)) 11232 MaxBECount = BECount; 11233 11234 return ExitLimit(BECount, MaxBECount, false, Predicates); 11235 } 11236 11237 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range, 11238 ScalarEvolution &SE) const { 11239 if (Range.isFullSet()) // Infinite loop. 11240 return SE.getCouldNotCompute(); 11241 11242 // If the start is a non-zero constant, shift the range to simplify things. 11243 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart())) 11244 if (!SC->getValue()->isZero()) { 11245 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end()); 11246 Operands[0] = SE.getZero(SC->getType()); 11247 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(), 11248 getNoWrapFlags(FlagNW)); 11249 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted)) 11250 return ShiftedAddRec->getNumIterationsInRange( 11251 Range.subtract(SC->getAPInt()), SE); 11252 // This is strange and shouldn't happen. 11253 return SE.getCouldNotCompute(); 11254 } 11255 11256 // The only time we can solve this is when we have all constant indices. 11257 // Otherwise, we cannot determine the overflow conditions. 11258 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); })) 11259 return SE.getCouldNotCompute(); 11260 11261 // Okay at this point we know that all elements of the chrec are constants and 11262 // that the start element is zero. 11263 11264 // First check to see if the range contains zero. If not, the first 11265 // iteration exits. 11266 unsigned BitWidth = SE.getTypeSizeInBits(getType()); 11267 if (!Range.contains(APInt(BitWidth, 0))) 11268 return SE.getZero(getType()); 11269 11270 if (isAffine()) { 11271 // If this is an affine expression then we have this situation: 11272 // Solve {0,+,A} in Range === Ax in Range 11273 11274 // We know that zero is in the range. If A is positive then we know that 11275 // the upper value of the range must be the first possible exit value. 11276 // If A is negative then the lower of the range is the last possible loop 11277 // value. Also note that we already checked for a full range. 11278 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt(); 11279 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower(); 11280 11281 // The exit value should be (End+A)/A. 11282 APInt ExitVal = (End + A).udiv(A); 11283 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal); 11284 11285 // Evaluate at the exit value. If we really did fall out of the valid 11286 // range, then we computed our trip count, otherwise wrap around or other 11287 // things must have happened. 11288 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE); 11289 if (Range.contains(Val->getValue())) 11290 return SE.getCouldNotCompute(); // Something strange happened 11291 11292 // Ensure that the previous value is in the range. This is a sanity check. 11293 assert(Range.contains( 11294 EvaluateConstantChrecAtConstant(this, 11295 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) && 11296 "Linear scev computation is off in a bad way!"); 11297 return SE.getConstant(ExitValue); 11298 } 11299 11300 if (isQuadratic()) { 11301 if (auto S = SolveQuadraticAddRecRange(this, Range, SE)) 11302 return SE.getConstant(S.getValue()); 11303 } 11304 11305 return SE.getCouldNotCompute(); 11306 } 11307 11308 const SCEVAddRecExpr * 11309 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const { 11310 assert(getNumOperands() > 1 && "AddRec with zero step?"); 11311 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)), 11312 // but in this case we cannot guarantee that the value returned will be an 11313 // AddRec because SCEV does not have a fixed point where it stops 11314 // simplification: it is legal to return ({rec1} + {rec2}). For example, it 11315 // may happen if we reach arithmetic depth limit while simplifying. So we 11316 // construct the returned value explicitly. 11317 SmallVector<const SCEV *, 3> Ops; 11318 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and 11319 // (this + Step) is {A+B,+,B+C,+...,+,N}. 11320 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i) 11321 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1))); 11322 // We know that the last operand is not a constant zero (otherwise it would 11323 // have been popped out earlier). This guarantees us that if the result has 11324 // the same last operand, then it will also not be popped out, meaning that 11325 // the returned value will be an AddRec. 11326 const SCEV *Last = getOperand(getNumOperands() - 1); 11327 assert(!Last->isZero() && "Recurrency with zero step?"); 11328 Ops.push_back(Last); 11329 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(), 11330 SCEV::FlagAnyWrap)); 11331 } 11332 11333 // Return true when S contains at least an undef value. 11334 static inline bool containsUndefs(const SCEV *S) { 11335 return SCEVExprContains(S, [](const SCEV *S) { 11336 if (const auto *SU = dyn_cast<SCEVUnknown>(S)) 11337 return isa<UndefValue>(SU->getValue()); 11338 return false; 11339 }); 11340 } 11341 11342 namespace { 11343 11344 // Collect all steps of SCEV expressions. 11345 struct SCEVCollectStrides { 11346 ScalarEvolution &SE; 11347 SmallVectorImpl<const SCEV *> &Strides; 11348 11349 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S) 11350 : SE(SE), Strides(S) {} 11351 11352 bool follow(const SCEV *S) { 11353 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) 11354 Strides.push_back(AR->getStepRecurrence(SE)); 11355 return true; 11356 } 11357 11358 bool isDone() const { return false; } 11359 }; 11360 11361 // Collect all SCEVUnknown and SCEVMulExpr expressions. 11362 struct SCEVCollectTerms { 11363 SmallVectorImpl<const SCEV *> &Terms; 11364 11365 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {} 11366 11367 bool follow(const SCEV *S) { 11368 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) || 11369 isa<SCEVSignExtendExpr>(S)) { 11370 if (!containsUndefs(S)) 11371 Terms.push_back(S); 11372 11373 // Stop recursion: once we collected a term, do not walk its operands. 11374 return false; 11375 } 11376 11377 // Keep looking. 11378 return true; 11379 } 11380 11381 bool isDone() const { return false; } 11382 }; 11383 11384 // Check if a SCEV contains an AddRecExpr. 11385 struct SCEVHasAddRec { 11386 bool &ContainsAddRec; 11387 11388 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) { 11389 ContainsAddRec = false; 11390 } 11391 11392 bool follow(const SCEV *S) { 11393 if (isa<SCEVAddRecExpr>(S)) { 11394 ContainsAddRec = true; 11395 11396 // Stop recursion: once we collected a term, do not walk its operands. 11397 return false; 11398 } 11399 11400 // Keep looking. 11401 return true; 11402 } 11403 11404 bool isDone() const { return false; } 11405 }; 11406 11407 // Find factors that are multiplied with an expression that (possibly as a 11408 // subexpression) contains an AddRecExpr. In the expression: 11409 // 11410 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop)) 11411 // 11412 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)" 11413 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size 11414 // parameters as they form a product with an induction variable. 11415 // 11416 // This collector expects all array size parameters to be in the same MulExpr. 11417 // It might be necessary to later add support for collecting parameters that are 11418 // spread over different nested MulExpr. 11419 struct SCEVCollectAddRecMultiplies { 11420 SmallVectorImpl<const SCEV *> &Terms; 11421 ScalarEvolution &SE; 11422 11423 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE) 11424 : Terms(T), SE(SE) {} 11425 11426 bool follow(const SCEV *S) { 11427 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) { 11428 bool HasAddRec = false; 11429 SmallVector<const SCEV *, 0> Operands; 11430 for (auto Op : Mul->operands()) { 11431 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op); 11432 if (Unknown && !isa<CallInst>(Unknown->getValue())) { 11433 Operands.push_back(Op); 11434 } else if (Unknown) { 11435 HasAddRec = true; 11436 } else { 11437 bool ContainsAddRec = false; 11438 SCEVHasAddRec ContiansAddRec(ContainsAddRec); 11439 visitAll(Op, ContiansAddRec); 11440 HasAddRec |= ContainsAddRec; 11441 } 11442 } 11443 if (Operands.size() == 0) 11444 return true; 11445 11446 if (!HasAddRec) 11447 return false; 11448 11449 Terms.push_back(SE.getMulExpr(Operands)); 11450 // Stop recursion: once we collected a term, do not walk its operands. 11451 return false; 11452 } 11453 11454 // Keep looking. 11455 return true; 11456 } 11457 11458 bool isDone() const { return false; } 11459 }; 11460 11461 } // end anonymous namespace 11462 11463 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in 11464 /// two places: 11465 /// 1) The strides of AddRec expressions. 11466 /// 2) Unknowns that are multiplied with AddRec expressions. 11467 void ScalarEvolution::collectParametricTerms(const SCEV *Expr, 11468 SmallVectorImpl<const SCEV *> &Terms) { 11469 SmallVector<const SCEV *, 4> Strides; 11470 SCEVCollectStrides StrideCollector(*this, Strides); 11471 visitAll(Expr, StrideCollector); 11472 11473 LLVM_DEBUG({ 11474 dbgs() << "Strides:\n"; 11475 for (const SCEV *S : Strides) 11476 dbgs() << *S << "\n"; 11477 }); 11478 11479 for (const SCEV *S : Strides) { 11480 SCEVCollectTerms TermCollector(Terms); 11481 visitAll(S, TermCollector); 11482 } 11483 11484 LLVM_DEBUG({ 11485 dbgs() << "Terms:\n"; 11486 for (const SCEV *T : Terms) 11487 dbgs() << *T << "\n"; 11488 }); 11489 11490 SCEVCollectAddRecMultiplies MulCollector(Terms, *this); 11491 visitAll(Expr, MulCollector); 11492 } 11493 11494 static bool findArrayDimensionsRec(ScalarEvolution &SE, 11495 SmallVectorImpl<const SCEV *> &Terms, 11496 SmallVectorImpl<const SCEV *> &Sizes) { 11497 int Last = Terms.size() - 1; 11498 const SCEV *Step = Terms[Last]; 11499 11500 // End of recursion. 11501 if (Last == 0) { 11502 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) { 11503 SmallVector<const SCEV *, 2> Qs; 11504 for (const SCEV *Op : M->operands()) 11505 if (!isa<SCEVConstant>(Op)) 11506 Qs.push_back(Op); 11507 11508 Step = SE.getMulExpr(Qs); 11509 } 11510 11511 Sizes.push_back(Step); 11512 return true; 11513 } 11514 11515 for (const SCEV *&Term : Terms) { 11516 // Normalize the terms before the next call to findArrayDimensionsRec. 11517 const SCEV *Q, *R; 11518 SCEVDivision::divide(SE, Term, Step, &Q, &R); 11519 11520 // Bail out when GCD does not evenly divide one of the terms. 11521 if (!R->isZero()) 11522 return false; 11523 11524 Term = Q; 11525 } 11526 11527 // Remove all SCEVConstants. 11528 Terms.erase( 11529 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }), 11530 Terms.end()); 11531 11532 if (Terms.size() > 0) 11533 if (!findArrayDimensionsRec(SE, Terms, Sizes)) 11534 return false; 11535 11536 Sizes.push_back(Step); 11537 return true; 11538 } 11539 11540 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter. 11541 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) { 11542 for (const SCEV *T : Terms) 11543 if (SCEVExprContains(T, [](const SCEV *S) { return isa<SCEVUnknown>(S); })) 11544 return true; 11545 11546 return false; 11547 } 11548 11549 // Return the number of product terms in S. 11550 static inline int numberOfTerms(const SCEV *S) { 11551 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S)) 11552 return Expr->getNumOperands(); 11553 return 1; 11554 } 11555 11556 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) { 11557 if (isa<SCEVConstant>(T)) 11558 return nullptr; 11559 11560 if (isa<SCEVUnknown>(T)) 11561 return T; 11562 11563 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) { 11564 SmallVector<const SCEV *, 2> Factors; 11565 for (const SCEV *Op : M->operands()) 11566 if (!isa<SCEVConstant>(Op)) 11567 Factors.push_back(Op); 11568 11569 return SE.getMulExpr(Factors); 11570 } 11571 11572 return T; 11573 } 11574 11575 /// Return the size of an element read or written by Inst. 11576 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) { 11577 Type *Ty; 11578 if (StoreInst *Store = dyn_cast<StoreInst>(Inst)) 11579 Ty = Store->getValueOperand()->getType(); 11580 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) 11581 Ty = Load->getType(); 11582 else 11583 return nullptr; 11584 11585 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty)); 11586 return getSizeOfExpr(ETy, Ty); 11587 } 11588 11589 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 11590 SmallVectorImpl<const SCEV *> &Sizes, 11591 const SCEV *ElementSize) { 11592 if (Terms.size() < 1 || !ElementSize) 11593 return; 11594 11595 // Early return when Terms do not contain parameters: we do not delinearize 11596 // non parametric SCEVs. 11597 if (!containsParameters(Terms)) 11598 return; 11599 11600 LLVM_DEBUG({ 11601 dbgs() << "Terms:\n"; 11602 for (const SCEV *T : Terms) 11603 dbgs() << *T << "\n"; 11604 }); 11605 11606 // Remove duplicates. 11607 array_pod_sort(Terms.begin(), Terms.end()); 11608 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end()); 11609 11610 // Put larger terms first. 11611 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) { 11612 return numberOfTerms(LHS) > numberOfTerms(RHS); 11613 }); 11614 11615 // Try to divide all terms by the element size. If term is not divisible by 11616 // element size, proceed with the original term. 11617 for (const SCEV *&Term : Terms) { 11618 const SCEV *Q, *R; 11619 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R); 11620 if (!Q->isZero()) 11621 Term = Q; 11622 } 11623 11624 SmallVector<const SCEV *, 4> NewTerms; 11625 11626 // Remove constant factors. 11627 for (const SCEV *T : Terms) 11628 if (const SCEV *NewT = removeConstantFactors(*this, T)) 11629 NewTerms.push_back(NewT); 11630 11631 LLVM_DEBUG({ 11632 dbgs() << "Terms after sorting:\n"; 11633 for (const SCEV *T : NewTerms) 11634 dbgs() << *T << "\n"; 11635 }); 11636 11637 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) { 11638 Sizes.clear(); 11639 return; 11640 } 11641 11642 // The last element to be pushed into Sizes is the size of an element. 11643 Sizes.push_back(ElementSize); 11644 11645 LLVM_DEBUG({ 11646 dbgs() << "Sizes:\n"; 11647 for (const SCEV *S : Sizes) 11648 dbgs() << *S << "\n"; 11649 }); 11650 } 11651 11652 void ScalarEvolution::computeAccessFunctions( 11653 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts, 11654 SmallVectorImpl<const SCEV *> &Sizes) { 11655 // Early exit in case this SCEV is not an affine multivariate function. 11656 if (Sizes.empty()) 11657 return; 11658 11659 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr)) 11660 if (!AR->isAffine()) 11661 return; 11662 11663 const SCEV *Res = Expr; 11664 int Last = Sizes.size() - 1; 11665 for (int i = Last; i >= 0; i--) { 11666 const SCEV *Q, *R; 11667 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R); 11668 11669 LLVM_DEBUG({ 11670 dbgs() << "Res: " << *Res << "\n"; 11671 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n"; 11672 dbgs() << "Res divided by Sizes[i]:\n"; 11673 dbgs() << "Quotient: " << *Q << "\n"; 11674 dbgs() << "Remainder: " << *R << "\n"; 11675 }); 11676 11677 Res = Q; 11678 11679 // Do not record the last subscript corresponding to the size of elements in 11680 // the array. 11681 if (i == Last) { 11682 11683 // Bail out if the remainder is too complex. 11684 if (isa<SCEVAddRecExpr>(R)) { 11685 Subscripts.clear(); 11686 Sizes.clear(); 11687 return; 11688 } 11689 11690 continue; 11691 } 11692 11693 // Record the access function for the current subscript. 11694 Subscripts.push_back(R); 11695 } 11696 11697 // Also push in last position the remainder of the last division: it will be 11698 // the access function of the innermost dimension. 11699 Subscripts.push_back(Res); 11700 11701 std::reverse(Subscripts.begin(), Subscripts.end()); 11702 11703 LLVM_DEBUG({ 11704 dbgs() << "Subscripts:\n"; 11705 for (const SCEV *S : Subscripts) 11706 dbgs() << *S << "\n"; 11707 }); 11708 } 11709 11710 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and 11711 /// sizes of an array access. Returns the remainder of the delinearization that 11712 /// is the offset start of the array. The SCEV->delinearize algorithm computes 11713 /// the multiples of SCEV coefficients: that is a pattern matching of sub 11714 /// expressions in the stride and base of a SCEV corresponding to the 11715 /// computation of a GCD (greatest common divisor) of base and stride. When 11716 /// SCEV->delinearize fails, it returns the SCEV unchanged. 11717 /// 11718 /// For example: when analyzing the memory access A[i][j][k] in this loop nest 11719 /// 11720 /// void foo(long n, long m, long o, double A[n][m][o]) { 11721 /// 11722 /// for (long i = 0; i < n; i++) 11723 /// for (long j = 0; j < m; j++) 11724 /// for (long k = 0; k < o; k++) 11725 /// A[i][j][k] = 1.0; 11726 /// } 11727 /// 11728 /// the delinearization input is the following AddRec SCEV: 11729 /// 11730 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k> 11731 /// 11732 /// From this SCEV, we are able to say that the base offset of the access is %A 11733 /// because it appears as an offset that does not divide any of the strides in 11734 /// the loops: 11735 /// 11736 /// CHECK: Base offset: %A 11737 /// 11738 /// and then SCEV->delinearize determines the size of some of the dimensions of 11739 /// the array as these are the multiples by which the strides are happening: 11740 /// 11741 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes. 11742 /// 11743 /// Note that the outermost dimension remains of UnknownSize because there are 11744 /// no strides that would help identifying the size of the last dimension: when 11745 /// the array has been statically allocated, one could compute the size of that 11746 /// dimension by dividing the overall size of the array by the size of the known 11747 /// dimensions: %m * %o * 8. 11748 /// 11749 /// Finally delinearize provides the access functions for the array reference 11750 /// that does correspond to A[i][j][k] of the above C testcase: 11751 /// 11752 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>] 11753 /// 11754 /// The testcases are checking the output of a function pass: 11755 /// DelinearizationPass that walks through all loads and stores of a function 11756 /// asking for the SCEV of the memory access with respect to all enclosing 11757 /// loops, calling SCEV->delinearize on that and printing the results. 11758 void ScalarEvolution::delinearize(const SCEV *Expr, 11759 SmallVectorImpl<const SCEV *> &Subscripts, 11760 SmallVectorImpl<const SCEV *> &Sizes, 11761 const SCEV *ElementSize) { 11762 // First step: collect parametric terms. 11763 SmallVector<const SCEV *, 4> Terms; 11764 collectParametricTerms(Expr, Terms); 11765 11766 if (Terms.empty()) 11767 return; 11768 11769 // Second step: find subscript sizes. 11770 findArrayDimensions(Terms, Sizes, ElementSize); 11771 11772 if (Sizes.empty()) 11773 return; 11774 11775 // Third step: compute the access functions for each subscript. 11776 computeAccessFunctions(Expr, Subscripts, Sizes); 11777 11778 if (Subscripts.empty()) 11779 return; 11780 11781 LLVM_DEBUG({ 11782 dbgs() << "succeeded to delinearize " << *Expr << "\n"; 11783 dbgs() << "ArrayDecl[UnknownSize]"; 11784 for (const SCEV *S : Sizes) 11785 dbgs() << "[" << *S << "]"; 11786 11787 dbgs() << "\nArrayRef"; 11788 for (const SCEV *S : Subscripts) 11789 dbgs() << "[" << *S << "]"; 11790 dbgs() << "\n"; 11791 }); 11792 } 11793 11794 bool ScalarEvolution::getIndexExpressionsFromGEP( 11795 const GetElementPtrInst *GEP, SmallVectorImpl<const SCEV *> &Subscripts, 11796 SmallVectorImpl<int> &Sizes) { 11797 assert(Subscripts.empty() && Sizes.empty() && 11798 "Expected output lists to be empty on entry to this function."); 11799 assert(GEP && "getIndexExpressionsFromGEP called with a null GEP"); 11800 Type *Ty = GEP->getPointerOperandType(); 11801 bool DroppedFirstDim = false; 11802 for (unsigned i = 1; i < GEP->getNumOperands(); i++) { 11803 const SCEV *Expr = getSCEV(GEP->getOperand(i)); 11804 if (i == 1) { 11805 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) { 11806 Ty = PtrTy->getElementType(); 11807 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) { 11808 Ty = ArrayTy->getElementType(); 11809 } else { 11810 Subscripts.clear(); 11811 Sizes.clear(); 11812 return false; 11813 } 11814 if (auto *Const = dyn_cast<SCEVConstant>(Expr)) 11815 if (Const->getValue()->isZero()) { 11816 DroppedFirstDim = true; 11817 continue; 11818 } 11819 Subscripts.push_back(Expr); 11820 continue; 11821 } 11822 11823 auto *ArrayTy = dyn_cast<ArrayType>(Ty); 11824 if (!ArrayTy) { 11825 Subscripts.clear(); 11826 Sizes.clear(); 11827 return false; 11828 } 11829 11830 Subscripts.push_back(Expr); 11831 if (!(DroppedFirstDim && i == 2)) 11832 Sizes.push_back(ArrayTy->getNumElements()); 11833 11834 Ty = ArrayTy->getElementType(); 11835 } 11836 return !Subscripts.empty(); 11837 } 11838 11839 //===----------------------------------------------------------------------===// 11840 // SCEVCallbackVH Class Implementation 11841 //===----------------------------------------------------------------------===// 11842 11843 void ScalarEvolution::SCEVCallbackVH::deleted() { 11844 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11845 if (PHINode *PN = dyn_cast<PHINode>(getValPtr())) 11846 SE->ConstantEvolutionLoopExitValue.erase(PN); 11847 SE->eraseValueFromMap(getValPtr()); 11848 // this now dangles! 11849 } 11850 11851 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) { 11852 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!"); 11853 11854 // Forget all the expressions associated with users of the old value, 11855 // so that future queries will recompute the expressions using the new 11856 // value. 11857 Value *Old = getValPtr(); 11858 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end()); 11859 SmallPtrSet<User *, 8> Visited; 11860 while (!Worklist.empty()) { 11861 User *U = Worklist.pop_back_val(); 11862 // Deleting the Old value will cause this to dangle. Postpone 11863 // that until everything else is done. 11864 if (U == Old) 11865 continue; 11866 if (!Visited.insert(U).second) 11867 continue; 11868 if (PHINode *PN = dyn_cast<PHINode>(U)) 11869 SE->ConstantEvolutionLoopExitValue.erase(PN); 11870 SE->eraseValueFromMap(U); 11871 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end()); 11872 } 11873 // Delete the Old value. 11874 if (PHINode *PN = dyn_cast<PHINode>(Old)) 11875 SE->ConstantEvolutionLoopExitValue.erase(PN); 11876 SE->eraseValueFromMap(Old); 11877 // this now dangles! 11878 } 11879 11880 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se) 11881 : CallbackVH(V), SE(se) {} 11882 11883 //===----------------------------------------------------------------------===// 11884 // ScalarEvolution Class Implementation 11885 //===----------------------------------------------------------------------===// 11886 11887 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI, 11888 AssumptionCache &AC, DominatorTree &DT, 11889 LoopInfo &LI) 11890 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI), 11891 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64), 11892 LoopDispositions(64), BlockDispositions(64) { 11893 // To use guards for proving predicates, we need to scan every instruction in 11894 // relevant basic blocks, and not just terminators. Doing this is a waste of 11895 // time if the IR does not actually contain any calls to 11896 // @llvm.experimental.guard, so do a quick check and remember this beforehand. 11897 // 11898 // This pessimizes the case where a pass that preserves ScalarEvolution wants 11899 // to _add_ guards to the module when there weren't any before, and wants 11900 // ScalarEvolution to optimize based on those guards. For now we prefer to be 11901 // efficient in lieu of being smart in that rather obscure case. 11902 11903 auto *GuardDecl = F.getParent()->getFunction( 11904 Intrinsic::getName(Intrinsic::experimental_guard)); 11905 HasGuards = GuardDecl && !GuardDecl->use_empty(); 11906 } 11907 11908 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg) 11909 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), 11910 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)), 11911 ValueExprMap(std::move(Arg.ValueExprMap)), 11912 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)), 11913 PendingPhiRanges(std::move(Arg.PendingPhiRanges)), 11914 PendingMerges(std::move(Arg.PendingMerges)), 11915 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)), 11916 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)), 11917 PredicatedBackedgeTakenCounts( 11918 std::move(Arg.PredicatedBackedgeTakenCounts)), 11919 ConstantEvolutionLoopExitValue( 11920 std::move(Arg.ConstantEvolutionLoopExitValue)), 11921 ValuesAtScopes(std::move(Arg.ValuesAtScopes)), 11922 LoopDispositions(std::move(Arg.LoopDispositions)), 11923 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)), 11924 BlockDispositions(std::move(Arg.BlockDispositions)), 11925 UnsignedRanges(std::move(Arg.UnsignedRanges)), 11926 SignedRanges(std::move(Arg.SignedRanges)), 11927 UniqueSCEVs(std::move(Arg.UniqueSCEVs)), 11928 UniquePreds(std::move(Arg.UniquePreds)), 11929 SCEVAllocator(std::move(Arg.SCEVAllocator)), 11930 LoopUsers(std::move(Arg.LoopUsers)), 11931 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)), 11932 FirstUnknown(Arg.FirstUnknown) { 11933 Arg.FirstUnknown = nullptr; 11934 } 11935 11936 ScalarEvolution::~ScalarEvolution() { 11937 // Iterate through all the SCEVUnknown instances and call their 11938 // destructors, so that they release their references to their values. 11939 for (SCEVUnknown *U = FirstUnknown; U;) { 11940 SCEVUnknown *Tmp = U; 11941 U = U->Next; 11942 Tmp->~SCEVUnknown(); 11943 } 11944 FirstUnknown = nullptr; 11945 11946 ExprValueMap.clear(); 11947 ValueExprMap.clear(); 11948 HasRecMap.clear(); 11949 11950 // Free any extra memory created for ExitNotTakenInfo in the unlikely event 11951 // that a loop had multiple computable exits. 11952 for (auto &BTCI : BackedgeTakenCounts) 11953 BTCI.second.clear(); 11954 for (auto &BTCI : PredicatedBackedgeTakenCounts) 11955 BTCI.second.clear(); 11956 11957 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage"); 11958 assert(PendingPhiRanges.empty() && "getRangeRef garbage"); 11959 assert(PendingMerges.empty() && "isImpliedViaMerge garbage"); 11960 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!"); 11961 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!"); 11962 } 11963 11964 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) { 11965 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L)); 11966 } 11967 11968 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE, 11969 const Loop *L) { 11970 // Print all inner loops first 11971 for (Loop *I : *L) 11972 PrintLoopInfo(OS, SE, I); 11973 11974 OS << "Loop "; 11975 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11976 OS << ": "; 11977 11978 SmallVector<BasicBlock *, 8> ExitingBlocks; 11979 L->getExitingBlocks(ExitingBlocks); 11980 if (ExitingBlocks.size() != 1) 11981 OS << "<multiple exits> "; 11982 11983 if (SE->hasLoopInvariantBackedgeTakenCount(L)) 11984 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n"; 11985 else 11986 OS << "Unpredictable backedge-taken count.\n"; 11987 11988 if (ExitingBlocks.size() > 1) 11989 for (BasicBlock *ExitingBlock : ExitingBlocks) { 11990 OS << " exit count for " << ExitingBlock->getName() << ": " 11991 << *SE->getExitCount(L, ExitingBlock) << "\n"; 11992 } 11993 11994 OS << "Loop "; 11995 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 11996 OS << ": "; 11997 11998 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) { 11999 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L); 12000 if (SE->isBackedgeTakenCountMaxOrZero(L)) 12001 OS << ", actual taken count either this or zero."; 12002 } else { 12003 OS << "Unpredictable max backedge-taken count. "; 12004 } 12005 12006 OS << "\n" 12007 "Loop "; 12008 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12009 OS << ": "; 12010 12011 SCEVUnionPredicate Pred; 12012 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred); 12013 if (!isa<SCEVCouldNotCompute>(PBT)) { 12014 OS << "Predicated backedge-taken count is " << *PBT << "\n"; 12015 OS << " Predicates:\n"; 12016 Pred.print(OS, 4); 12017 } else { 12018 OS << "Unpredictable predicated backedge-taken count. "; 12019 } 12020 OS << "\n"; 12021 12022 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 12023 OS << "Loop "; 12024 L->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12025 OS << ": "; 12026 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n"; 12027 } 12028 } 12029 12030 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) { 12031 switch (LD) { 12032 case ScalarEvolution::LoopVariant: 12033 return "Variant"; 12034 case ScalarEvolution::LoopInvariant: 12035 return "Invariant"; 12036 case ScalarEvolution::LoopComputable: 12037 return "Computable"; 12038 } 12039 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!"); 12040 } 12041 12042 void ScalarEvolution::print(raw_ostream &OS) const { 12043 // ScalarEvolution's implementation of the print method is to print 12044 // out SCEV values of all instructions that are interesting. Doing 12045 // this potentially causes it to create new SCEV objects though, 12046 // which technically conflicts with the const qualifier. This isn't 12047 // observable from outside the class though, so casting away the 12048 // const isn't dangerous. 12049 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12050 12051 if (ClassifyExpressions) { 12052 OS << "Classifying expressions for: "; 12053 F.printAsOperand(OS, /*PrintType=*/false); 12054 OS << "\n"; 12055 for (Instruction &I : instructions(F)) 12056 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) { 12057 OS << I << '\n'; 12058 OS << " --> "; 12059 const SCEV *SV = SE.getSCEV(&I); 12060 SV->print(OS); 12061 if (!isa<SCEVCouldNotCompute>(SV)) { 12062 OS << " U: "; 12063 SE.getUnsignedRange(SV).print(OS); 12064 OS << " S: "; 12065 SE.getSignedRange(SV).print(OS); 12066 } 12067 12068 const Loop *L = LI.getLoopFor(I.getParent()); 12069 12070 const SCEV *AtUse = SE.getSCEVAtScope(SV, L); 12071 if (AtUse != SV) { 12072 OS << " --> "; 12073 AtUse->print(OS); 12074 if (!isa<SCEVCouldNotCompute>(AtUse)) { 12075 OS << " U: "; 12076 SE.getUnsignedRange(AtUse).print(OS); 12077 OS << " S: "; 12078 SE.getSignedRange(AtUse).print(OS); 12079 } 12080 } 12081 12082 if (L) { 12083 OS << "\t\t" "Exits: "; 12084 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop()); 12085 if (!SE.isLoopInvariant(ExitValue, L)) { 12086 OS << "<<Unknown>>"; 12087 } else { 12088 OS << *ExitValue; 12089 } 12090 12091 bool First = true; 12092 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) { 12093 if (First) { 12094 OS << "\t\t" "LoopDispositions: { "; 12095 First = false; 12096 } else { 12097 OS << ", "; 12098 } 12099 12100 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12101 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter)); 12102 } 12103 12104 for (auto *InnerL : depth_first(L)) { 12105 if (InnerL == L) 12106 continue; 12107 if (First) { 12108 OS << "\t\t" "LoopDispositions: { "; 12109 First = false; 12110 } else { 12111 OS << ", "; 12112 } 12113 12114 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false); 12115 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL)); 12116 } 12117 12118 OS << " }"; 12119 } 12120 12121 OS << "\n"; 12122 } 12123 } 12124 12125 OS << "Determining loop execution counts for: "; 12126 F.printAsOperand(OS, /*PrintType=*/false); 12127 OS << "\n"; 12128 for (Loop *I : LI) 12129 PrintLoopInfo(OS, &SE, I); 12130 } 12131 12132 ScalarEvolution::LoopDisposition 12133 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) { 12134 auto &Values = LoopDispositions[S]; 12135 for (auto &V : Values) { 12136 if (V.getPointer() == L) 12137 return V.getInt(); 12138 } 12139 Values.emplace_back(L, LoopVariant); 12140 LoopDisposition D = computeLoopDisposition(S, L); 12141 auto &Values2 = LoopDispositions[S]; 12142 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12143 if (V.getPointer() == L) { 12144 V.setInt(D); 12145 break; 12146 } 12147 } 12148 return D; 12149 } 12150 12151 ScalarEvolution::LoopDisposition 12152 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) { 12153 switch (S->getSCEVType()) { 12154 case scConstant: 12155 return LoopInvariant; 12156 case scPtrToInt: 12157 case scTruncate: 12158 case scZeroExtend: 12159 case scSignExtend: 12160 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L); 12161 case scAddRecExpr: { 12162 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12163 12164 // If L is the addrec's loop, it's computable. 12165 if (AR->getLoop() == L) 12166 return LoopComputable; 12167 12168 // Add recurrences are never invariant in the function-body (null loop). 12169 if (!L) 12170 return LoopVariant; 12171 12172 // Everything that is not defined at loop entry is variant. 12173 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader())) 12174 return LoopVariant; 12175 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not" 12176 " dominate the contained loop's header?"); 12177 12178 // This recurrence is invariant w.r.t. L if AR's loop contains L. 12179 if (AR->getLoop()->contains(L)) 12180 return LoopInvariant; 12181 12182 // This recurrence is variant w.r.t. L if any of its operands 12183 // are variant. 12184 for (auto *Op : AR->operands()) 12185 if (!isLoopInvariant(Op, L)) 12186 return LoopVariant; 12187 12188 // Otherwise it's loop-invariant. 12189 return LoopInvariant; 12190 } 12191 case scAddExpr: 12192 case scMulExpr: 12193 case scUMaxExpr: 12194 case scSMaxExpr: 12195 case scUMinExpr: 12196 case scSMinExpr: { 12197 bool HasVarying = false; 12198 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) { 12199 LoopDisposition D = getLoopDisposition(Op, L); 12200 if (D == LoopVariant) 12201 return LoopVariant; 12202 if (D == LoopComputable) 12203 HasVarying = true; 12204 } 12205 return HasVarying ? LoopComputable : LoopInvariant; 12206 } 12207 case scUDivExpr: { 12208 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12209 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L); 12210 if (LD == LoopVariant) 12211 return LoopVariant; 12212 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L); 12213 if (RD == LoopVariant) 12214 return LoopVariant; 12215 return (LD == LoopInvariant && RD == LoopInvariant) ? 12216 LoopInvariant : LoopComputable; 12217 } 12218 case scUnknown: 12219 // All non-instruction values are loop invariant. All instructions are loop 12220 // invariant if they are not contained in the specified loop. 12221 // Instructions are never considered invariant in the function body 12222 // (null loop) because they are defined within the "loop". 12223 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) 12224 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant; 12225 return LoopInvariant; 12226 case scCouldNotCompute: 12227 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12228 } 12229 llvm_unreachable("Unknown SCEV kind!"); 12230 } 12231 12232 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) { 12233 return getLoopDisposition(S, L) == LoopInvariant; 12234 } 12235 12236 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) { 12237 return getLoopDisposition(S, L) == LoopComputable; 12238 } 12239 12240 ScalarEvolution::BlockDisposition 12241 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12242 auto &Values = BlockDispositions[S]; 12243 for (auto &V : Values) { 12244 if (V.getPointer() == BB) 12245 return V.getInt(); 12246 } 12247 Values.emplace_back(BB, DoesNotDominateBlock); 12248 BlockDisposition D = computeBlockDisposition(S, BB); 12249 auto &Values2 = BlockDispositions[S]; 12250 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) { 12251 if (V.getPointer() == BB) { 12252 V.setInt(D); 12253 break; 12254 } 12255 } 12256 return D; 12257 } 12258 12259 ScalarEvolution::BlockDisposition 12260 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) { 12261 switch (S->getSCEVType()) { 12262 case scConstant: 12263 return ProperlyDominatesBlock; 12264 case scPtrToInt: 12265 case scTruncate: 12266 case scZeroExtend: 12267 case scSignExtend: 12268 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB); 12269 case scAddRecExpr: { 12270 // This uses a "dominates" query instead of "properly dominates" query 12271 // to test for proper dominance too, because the instruction which 12272 // produces the addrec's value is a PHI, and a PHI effectively properly 12273 // dominates its entire containing block. 12274 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S); 12275 if (!DT.dominates(AR->getLoop()->getHeader(), BB)) 12276 return DoesNotDominateBlock; 12277 12278 // Fall through into SCEVNAryExpr handling. 12279 LLVM_FALLTHROUGH; 12280 } 12281 case scAddExpr: 12282 case scMulExpr: 12283 case scUMaxExpr: 12284 case scSMaxExpr: 12285 case scUMinExpr: 12286 case scSMinExpr: { 12287 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S); 12288 bool Proper = true; 12289 for (const SCEV *NAryOp : NAry->operands()) { 12290 BlockDisposition D = getBlockDisposition(NAryOp, BB); 12291 if (D == DoesNotDominateBlock) 12292 return DoesNotDominateBlock; 12293 if (D == DominatesBlock) 12294 Proper = false; 12295 } 12296 return Proper ? ProperlyDominatesBlock : DominatesBlock; 12297 } 12298 case scUDivExpr: { 12299 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S); 12300 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS(); 12301 BlockDisposition LD = getBlockDisposition(LHS, BB); 12302 if (LD == DoesNotDominateBlock) 12303 return DoesNotDominateBlock; 12304 BlockDisposition RD = getBlockDisposition(RHS, BB); 12305 if (RD == DoesNotDominateBlock) 12306 return DoesNotDominateBlock; 12307 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ? 12308 ProperlyDominatesBlock : DominatesBlock; 12309 } 12310 case scUnknown: 12311 if (Instruction *I = 12312 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) { 12313 if (I->getParent() == BB) 12314 return DominatesBlock; 12315 if (DT.properlyDominates(I->getParent(), BB)) 12316 return ProperlyDominatesBlock; 12317 return DoesNotDominateBlock; 12318 } 12319 return ProperlyDominatesBlock; 12320 case scCouldNotCompute: 12321 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!"); 12322 } 12323 llvm_unreachable("Unknown SCEV kind!"); 12324 } 12325 12326 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) { 12327 return getBlockDisposition(S, BB) >= DominatesBlock; 12328 } 12329 12330 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) { 12331 return getBlockDisposition(S, BB) == ProperlyDominatesBlock; 12332 } 12333 12334 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const { 12335 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; }); 12336 } 12337 12338 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const { 12339 auto IsS = [&](const SCEV *X) { return S == X; }; 12340 auto ContainsS = [&](const SCEV *X) { 12341 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS); 12342 }; 12343 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken); 12344 } 12345 12346 void 12347 ScalarEvolution::forgetMemoizedResults(const SCEV *S) { 12348 ValuesAtScopes.erase(S); 12349 LoopDispositions.erase(S); 12350 BlockDispositions.erase(S); 12351 UnsignedRanges.erase(S); 12352 SignedRanges.erase(S); 12353 ExprValueMap.erase(S); 12354 HasRecMap.erase(S); 12355 MinTrailingZerosCache.erase(S); 12356 12357 for (auto I = PredicatedSCEVRewrites.begin(); 12358 I != PredicatedSCEVRewrites.end();) { 12359 std::pair<const SCEV *, const Loop *> Entry = I->first; 12360 if (Entry.first == S) 12361 PredicatedSCEVRewrites.erase(I++); 12362 else 12363 ++I; 12364 } 12365 12366 auto RemoveSCEVFromBackedgeMap = 12367 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) { 12368 for (auto I = Map.begin(), E = Map.end(); I != E;) { 12369 BackedgeTakenInfo &BEInfo = I->second; 12370 if (BEInfo.hasOperand(S, this)) { 12371 BEInfo.clear(); 12372 Map.erase(I++); 12373 } else 12374 ++I; 12375 } 12376 }; 12377 12378 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts); 12379 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts); 12380 } 12381 12382 void 12383 ScalarEvolution::getUsedLoops(const SCEV *S, 12384 SmallPtrSetImpl<const Loop *> &LoopsUsed) { 12385 struct FindUsedLoops { 12386 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed) 12387 : LoopsUsed(LoopsUsed) {} 12388 SmallPtrSetImpl<const Loop *> &LoopsUsed; 12389 bool follow(const SCEV *S) { 12390 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) 12391 LoopsUsed.insert(AR->getLoop()); 12392 return true; 12393 } 12394 12395 bool isDone() const { return false; } 12396 }; 12397 12398 FindUsedLoops F(LoopsUsed); 12399 SCEVTraversal<FindUsedLoops>(F).visitAll(S); 12400 } 12401 12402 void ScalarEvolution::addToLoopUseLists(const SCEV *S) { 12403 SmallPtrSet<const Loop *, 8> LoopsUsed; 12404 getUsedLoops(S, LoopsUsed); 12405 for (auto *L : LoopsUsed) 12406 LoopUsers[L].push_back(S); 12407 } 12408 12409 void ScalarEvolution::verify() const { 12410 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this); 12411 ScalarEvolution SE2(F, TLI, AC, DT, LI); 12412 12413 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end()); 12414 12415 // Map's SCEV expressions from one ScalarEvolution "universe" to another. 12416 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> { 12417 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {} 12418 12419 const SCEV *visitConstant(const SCEVConstant *Constant) { 12420 return SE.getConstant(Constant->getAPInt()); 12421 } 12422 12423 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12424 return SE.getUnknown(Expr->getValue()); 12425 } 12426 12427 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { 12428 return SE.getCouldNotCompute(); 12429 } 12430 }; 12431 12432 SCEVMapper SCM(SE2); 12433 12434 while (!LoopStack.empty()) { 12435 auto *L = LoopStack.pop_back_val(); 12436 LoopStack.insert(LoopStack.end(), L->begin(), L->end()); 12437 12438 auto *CurBECount = SCM.visit( 12439 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L)); 12440 auto *NewBECount = SE2.getBackedgeTakenCount(L); 12441 12442 if (CurBECount == SE2.getCouldNotCompute() || 12443 NewBECount == SE2.getCouldNotCompute()) { 12444 // NB! This situation is legal, but is very suspicious -- whatever pass 12445 // change the loop to make a trip count go from could not compute to 12446 // computable or vice-versa *should have* invalidated SCEV. However, we 12447 // choose not to assert here (for now) since we don't want false 12448 // positives. 12449 continue; 12450 } 12451 12452 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) { 12453 // SCEV treats "undef" as an unknown but consistent value (i.e. it does 12454 // not propagate undef aggressively). This means we can (and do) fail 12455 // verification in cases where a transform makes the trip count of a loop 12456 // go from "undef" to "undef+1" (say). The transform is fine, since in 12457 // both cases the loop iterates "undef" times, but SCEV thinks we 12458 // increased the trip count of the loop by 1 incorrectly. 12459 continue; 12460 } 12461 12462 if (SE.getTypeSizeInBits(CurBECount->getType()) > 12463 SE.getTypeSizeInBits(NewBECount->getType())) 12464 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType()); 12465 else if (SE.getTypeSizeInBits(CurBECount->getType()) < 12466 SE.getTypeSizeInBits(NewBECount->getType())) 12467 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType()); 12468 12469 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount); 12470 12471 // Unless VerifySCEVStrict is set, we only compare constant deltas. 12472 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) { 12473 dbgs() << "Trip Count for " << *L << " Changed!\n"; 12474 dbgs() << "Old: " << *CurBECount << "\n"; 12475 dbgs() << "New: " << *NewBECount << "\n"; 12476 dbgs() << "Delta: " << *Delta << "\n"; 12477 std::abort(); 12478 } 12479 } 12480 12481 // Collect all valid loops currently in LoopInfo. 12482 SmallPtrSet<Loop *, 32> ValidLoops; 12483 SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end()); 12484 while (!Worklist.empty()) { 12485 Loop *L = Worklist.pop_back_val(); 12486 if (ValidLoops.contains(L)) 12487 continue; 12488 ValidLoops.insert(L); 12489 Worklist.append(L->begin(), L->end()); 12490 } 12491 // Check for SCEV expressions referencing invalid/deleted loops. 12492 for (auto &KV : ValueExprMap) { 12493 auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second); 12494 if (!AR) 12495 continue; 12496 assert(ValidLoops.contains(AR->getLoop()) && 12497 "AddRec references invalid loop"); 12498 } 12499 } 12500 12501 bool ScalarEvolution::invalidate( 12502 Function &F, const PreservedAnalyses &PA, 12503 FunctionAnalysisManager::Invalidator &Inv) { 12504 // Invalidate the ScalarEvolution object whenever it isn't preserved or one 12505 // of its dependencies is invalidated. 12506 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>(); 12507 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) || 12508 Inv.invalidate<AssumptionAnalysis>(F, PA) || 12509 Inv.invalidate<DominatorTreeAnalysis>(F, PA) || 12510 Inv.invalidate<LoopAnalysis>(F, PA); 12511 } 12512 12513 AnalysisKey ScalarEvolutionAnalysis::Key; 12514 12515 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F, 12516 FunctionAnalysisManager &AM) { 12517 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F), 12518 AM.getResult<AssumptionAnalysis>(F), 12519 AM.getResult<DominatorTreeAnalysis>(F), 12520 AM.getResult<LoopAnalysis>(F)); 12521 } 12522 12523 PreservedAnalyses 12524 ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) { 12525 AM.getResult<ScalarEvolutionAnalysis>(F).verify(); 12526 return PreservedAnalyses::all(); 12527 } 12528 12529 PreservedAnalyses 12530 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) { 12531 // For compatibility with opt's -analyze feature under legacy pass manager 12532 // which was not ported to NPM. This keeps tests using 12533 // update_analyze_test_checks.py working. 12534 OS << "Printing analysis 'Scalar Evolution Analysis' for function '" 12535 << F.getName() << "':\n"; 12536 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS); 12537 return PreservedAnalyses::all(); 12538 } 12539 12540 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution", 12541 "Scalar Evolution Analysis", false, true) 12542 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12543 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 12544 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 12545 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 12546 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution", 12547 "Scalar Evolution Analysis", false, true) 12548 12549 char ScalarEvolutionWrapperPass::ID = 0; 12550 12551 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) { 12552 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry()); 12553 } 12554 12555 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) { 12556 SE.reset(new ScalarEvolution( 12557 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 12558 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F), 12559 getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 12560 getAnalysis<LoopInfoWrapperPass>().getLoopInfo())); 12561 return false; 12562 } 12563 12564 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); } 12565 12566 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const { 12567 SE->print(OS); 12568 } 12569 12570 void ScalarEvolutionWrapperPass::verifyAnalysis() const { 12571 if (!VerifySCEV) 12572 return; 12573 12574 SE->verify(); 12575 } 12576 12577 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 12578 AU.setPreservesAll(); 12579 AU.addRequiredTransitive<AssumptionCacheTracker>(); 12580 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 12581 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 12582 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 12583 } 12584 12585 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS, 12586 const SCEV *RHS) { 12587 FoldingSetNodeID ID; 12588 assert(LHS->getType() == RHS->getType() && 12589 "Type mismatch between LHS and RHS"); 12590 // Unique this node based on the arguments 12591 ID.AddInteger(SCEVPredicate::P_Equal); 12592 ID.AddPointer(LHS); 12593 ID.AddPointer(RHS); 12594 void *IP = nullptr; 12595 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12596 return S; 12597 SCEVEqualPredicate *Eq = new (SCEVAllocator) 12598 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS); 12599 UniquePreds.InsertNode(Eq, IP); 12600 return Eq; 12601 } 12602 12603 const SCEVPredicate *ScalarEvolution::getWrapPredicate( 12604 const SCEVAddRecExpr *AR, 12605 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12606 FoldingSetNodeID ID; 12607 // Unique this node based on the arguments 12608 ID.AddInteger(SCEVPredicate::P_Wrap); 12609 ID.AddPointer(AR); 12610 ID.AddInteger(AddedFlags); 12611 void *IP = nullptr; 12612 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP)) 12613 return S; 12614 auto *OF = new (SCEVAllocator) 12615 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags); 12616 UniquePreds.InsertNode(OF, IP); 12617 return OF; 12618 } 12619 12620 namespace { 12621 12622 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> { 12623 public: 12624 12625 /// Rewrites \p S in the context of a loop L and the SCEV predication 12626 /// infrastructure. 12627 /// 12628 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the 12629 /// equivalences present in \p Pred. 12630 /// 12631 /// If \p NewPreds is non-null, rewrite is free to add further predicates to 12632 /// \p NewPreds such that the result will be an AddRecExpr. 12633 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE, 12634 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12635 SCEVUnionPredicate *Pred) { 12636 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred); 12637 return Rewriter.visit(S); 12638 } 12639 12640 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 12641 if (Pred) { 12642 auto ExprPreds = Pred->getPredicatesForExpr(Expr); 12643 for (auto *Pred : ExprPreds) 12644 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred)) 12645 if (IPred->getLHS() == Expr) 12646 return IPred->getRHS(); 12647 } 12648 return convertToAddRecWithPreds(Expr); 12649 } 12650 12651 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 12652 const SCEV *Operand = visit(Expr->getOperand()); 12653 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12654 if (AR && AR->getLoop() == L && AR->isAffine()) { 12655 // This couldn't be folded because the operand didn't have the nuw 12656 // flag. Add the nusw flag as an assumption that we could make. 12657 const SCEV *Step = AR->getStepRecurrence(SE); 12658 Type *Ty = Expr->getType(); 12659 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW)) 12660 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty), 12661 SE.getSignExtendExpr(Step, Ty), L, 12662 AR->getNoWrapFlags()); 12663 } 12664 return SE.getZeroExtendExpr(Operand, Expr->getType()); 12665 } 12666 12667 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 12668 const SCEV *Operand = visit(Expr->getOperand()); 12669 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand); 12670 if (AR && AR->getLoop() == L && AR->isAffine()) { 12671 // This couldn't be folded because the operand didn't have the nsw 12672 // flag. Add the nssw flag as an assumption that we could make. 12673 const SCEV *Step = AR->getStepRecurrence(SE); 12674 Type *Ty = Expr->getType(); 12675 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW)) 12676 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty), 12677 SE.getSignExtendExpr(Step, Ty), L, 12678 AR->getNoWrapFlags()); 12679 } 12680 return SE.getSignExtendExpr(Operand, Expr->getType()); 12681 } 12682 12683 private: 12684 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE, 12685 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds, 12686 SCEVUnionPredicate *Pred) 12687 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {} 12688 12689 bool addOverflowAssumption(const SCEVPredicate *P) { 12690 if (!NewPreds) { 12691 // Check if we've already made this assumption. 12692 return Pred && Pred->implies(P); 12693 } 12694 NewPreds->insert(P); 12695 return true; 12696 } 12697 12698 bool addOverflowAssumption(const SCEVAddRecExpr *AR, 12699 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) { 12700 auto *A = SE.getWrapPredicate(AR, AddedFlags); 12701 return addOverflowAssumption(A); 12702 } 12703 12704 // If \p Expr represents a PHINode, we try to see if it can be represented 12705 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible 12706 // to add this predicate as a runtime overflow check, we return the AddRec. 12707 // If \p Expr does not meet these conditions (is not a PHI node, or we 12708 // couldn't create an AddRec for it, or couldn't add the predicate), we just 12709 // return \p Expr. 12710 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) { 12711 if (!isa<PHINode>(Expr->getValue())) 12712 return Expr; 12713 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>> 12714 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr); 12715 if (!PredicatedRewrite) 12716 return Expr; 12717 for (auto *P : PredicatedRewrite->second){ 12718 // Wrap predicates from outer loops are not supported. 12719 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) { 12720 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr()); 12721 if (L != AR->getLoop()) 12722 return Expr; 12723 } 12724 if (!addOverflowAssumption(P)) 12725 return Expr; 12726 } 12727 return PredicatedRewrite->first; 12728 } 12729 12730 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds; 12731 SCEVUnionPredicate *Pred; 12732 const Loop *L; 12733 }; 12734 12735 } // end anonymous namespace 12736 12737 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L, 12738 SCEVUnionPredicate &Preds) { 12739 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds); 12740 } 12741 12742 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates( 12743 const SCEV *S, const Loop *L, 12744 SmallPtrSetImpl<const SCEVPredicate *> &Preds) { 12745 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds; 12746 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr); 12747 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 12748 12749 if (!AddRec) 12750 return nullptr; 12751 12752 // Since the transformation was successful, we can now transfer the SCEV 12753 // predicates. 12754 for (auto *P : TransformPreds) 12755 Preds.insert(P); 12756 12757 return AddRec; 12758 } 12759 12760 /// SCEV predicates 12761 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID, 12762 SCEVPredicateKind Kind) 12763 : FastID(ID), Kind(Kind) {} 12764 12765 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID, 12766 const SCEV *LHS, const SCEV *RHS) 12767 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) { 12768 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match"); 12769 assert(LHS != RHS && "LHS and RHS are the same SCEV"); 12770 } 12771 12772 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const { 12773 const auto *Op = dyn_cast<SCEVEqualPredicate>(N); 12774 12775 if (!Op) 12776 return false; 12777 12778 return Op->LHS == LHS && Op->RHS == RHS; 12779 } 12780 12781 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; } 12782 12783 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; } 12784 12785 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const { 12786 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n"; 12787 } 12788 12789 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID, 12790 const SCEVAddRecExpr *AR, 12791 IncrementWrapFlags Flags) 12792 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {} 12793 12794 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; } 12795 12796 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const { 12797 const auto *Op = dyn_cast<SCEVWrapPredicate>(N); 12798 12799 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags; 12800 } 12801 12802 bool SCEVWrapPredicate::isAlwaysTrue() const { 12803 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags(); 12804 IncrementWrapFlags IFlags = Flags; 12805 12806 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags) 12807 IFlags = clearFlags(IFlags, IncrementNSSW); 12808 12809 return IFlags == IncrementAnyWrap; 12810 } 12811 12812 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const { 12813 OS.indent(Depth) << *getExpr() << " Added Flags: "; 12814 if (SCEVWrapPredicate::IncrementNUSW & getFlags()) 12815 OS << "<nusw>"; 12816 if (SCEVWrapPredicate::IncrementNSSW & getFlags()) 12817 OS << "<nssw>"; 12818 OS << "\n"; 12819 } 12820 12821 SCEVWrapPredicate::IncrementWrapFlags 12822 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR, 12823 ScalarEvolution &SE) { 12824 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap; 12825 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags(); 12826 12827 // We can safely transfer the NSW flag as NSSW. 12828 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags) 12829 ImpliedFlags = IncrementNSSW; 12830 12831 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) { 12832 // If the increment is positive, the SCEV NUW flag will also imply the 12833 // WrapPredicate NUSW flag. 12834 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 12835 if (Step->getValue()->getValue().isNonNegative()) 12836 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW); 12837 } 12838 12839 return ImpliedFlags; 12840 } 12841 12842 /// Union predicates don't get cached so create a dummy set ID for it. 12843 SCEVUnionPredicate::SCEVUnionPredicate() 12844 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {} 12845 12846 bool SCEVUnionPredicate::isAlwaysTrue() const { 12847 return all_of(Preds, 12848 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); }); 12849 } 12850 12851 ArrayRef<const SCEVPredicate *> 12852 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) { 12853 auto I = SCEVToPreds.find(Expr); 12854 if (I == SCEVToPreds.end()) 12855 return ArrayRef<const SCEVPredicate *>(); 12856 return I->second; 12857 } 12858 12859 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const { 12860 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) 12861 return all_of(Set->Preds, 12862 [this](const SCEVPredicate *I) { return this->implies(I); }); 12863 12864 auto ScevPredsIt = SCEVToPreds.find(N->getExpr()); 12865 if (ScevPredsIt == SCEVToPreds.end()) 12866 return false; 12867 auto &SCEVPreds = ScevPredsIt->second; 12868 12869 return any_of(SCEVPreds, 12870 [N](const SCEVPredicate *I) { return I->implies(N); }); 12871 } 12872 12873 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; } 12874 12875 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const { 12876 for (auto Pred : Preds) 12877 Pred->print(OS, Depth); 12878 } 12879 12880 void SCEVUnionPredicate::add(const SCEVPredicate *N) { 12881 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) { 12882 for (auto Pred : Set->Preds) 12883 add(Pred); 12884 return; 12885 } 12886 12887 if (implies(N)) 12888 return; 12889 12890 const SCEV *Key = N->getExpr(); 12891 assert(Key && "Only SCEVUnionPredicate doesn't have an " 12892 " associated expression!"); 12893 12894 SCEVToPreds[Key].push_back(N); 12895 Preds.push_back(N); 12896 } 12897 12898 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE, 12899 Loop &L) 12900 : SE(SE), L(L) {} 12901 12902 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) { 12903 const SCEV *Expr = SE.getSCEV(V); 12904 RewriteEntry &Entry = RewriteMap[Expr]; 12905 12906 // If we already have an entry and the version matches, return it. 12907 if (Entry.second && Generation == Entry.first) 12908 return Entry.second; 12909 12910 // We found an entry but it's stale. Rewrite the stale entry 12911 // according to the current predicate. 12912 if (Entry.second) 12913 Expr = Entry.second; 12914 12915 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds); 12916 Entry = {Generation, NewSCEV}; 12917 12918 return NewSCEV; 12919 } 12920 12921 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() { 12922 if (!BackedgeCount) { 12923 SCEVUnionPredicate BackedgePred; 12924 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred); 12925 addPredicate(BackedgePred); 12926 } 12927 return BackedgeCount; 12928 } 12929 12930 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) { 12931 if (Preds.implies(&Pred)) 12932 return; 12933 Preds.add(&Pred); 12934 updateGeneration(); 12935 } 12936 12937 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const { 12938 return Preds; 12939 } 12940 12941 void PredicatedScalarEvolution::updateGeneration() { 12942 // If the generation number wrapped recompute everything. 12943 if (++Generation == 0) { 12944 for (auto &II : RewriteMap) { 12945 const SCEV *Rewritten = II.second.second; 12946 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)}; 12947 } 12948 } 12949 } 12950 12951 void PredicatedScalarEvolution::setNoOverflow( 12952 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12953 const SCEV *Expr = getSCEV(V); 12954 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12955 12956 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE); 12957 12958 // Clear the statically implied flags. 12959 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags); 12960 addPredicate(*SE.getWrapPredicate(AR, Flags)); 12961 12962 auto II = FlagsMap.insert({V, Flags}); 12963 if (!II.second) 12964 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second); 12965 } 12966 12967 bool PredicatedScalarEvolution::hasNoOverflow( 12968 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) { 12969 const SCEV *Expr = getSCEV(V); 12970 const auto *AR = cast<SCEVAddRecExpr>(Expr); 12971 12972 Flags = SCEVWrapPredicate::clearFlags( 12973 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE)); 12974 12975 auto II = FlagsMap.find(V); 12976 12977 if (II != FlagsMap.end()) 12978 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second); 12979 12980 return Flags == SCEVWrapPredicate::IncrementAnyWrap; 12981 } 12982 12983 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) { 12984 const SCEV *Expr = this->getSCEV(V); 12985 SmallPtrSet<const SCEVPredicate *, 4> NewPreds; 12986 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds); 12987 12988 if (!New) 12989 return nullptr; 12990 12991 for (auto *P : NewPreds) 12992 Preds.add(P); 12993 12994 updateGeneration(); 12995 RewriteMap[SE.getSCEV(V)] = {Generation, New}; 12996 return New; 12997 } 12998 12999 PredicatedScalarEvolution::PredicatedScalarEvolution( 13000 const PredicatedScalarEvolution &Init) 13001 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds), 13002 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) { 13003 for (auto I : Init.FlagsMap) 13004 FlagsMap.insert(I); 13005 } 13006 13007 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const { 13008 // For each block. 13009 for (auto *BB : L.getBlocks()) 13010 for (auto &I : *BB) { 13011 if (!SE.isSCEVable(I.getType())) 13012 continue; 13013 13014 auto *Expr = SE.getSCEV(&I); 13015 auto II = RewriteMap.find(Expr); 13016 13017 if (II == RewriteMap.end()) 13018 continue; 13019 13020 // Don't print things that are not interesting. 13021 if (II->second.second == Expr) 13022 continue; 13023 13024 OS.indent(Depth) << "[PSE]" << I << ":\n"; 13025 OS.indent(Depth + 2) << *Expr << "\n"; 13026 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n"; 13027 } 13028 } 13029 13030 // Match the mathematical pattern A - (A / B) * B, where A and B can be 13031 // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used 13032 // for URem with constant power-of-2 second operands. 13033 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is 13034 // 4, A / B becomes X / 8). 13035 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS, 13036 const SCEV *&RHS) { 13037 // Try to match 'zext (trunc A to iB) to iY', which is used 13038 // for URem with constant power-of-2 second operands. Make sure the size of 13039 // the operand A matches the size of the whole expressions. 13040 if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr)) 13041 if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) { 13042 LHS = Trunc->getOperand(); 13043 if (LHS->getType() != Expr->getType()) 13044 LHS = getZeroExtendExpr(LHS, Expr->getType()); 13045 RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1) 13046 << getTypeSizeInBits(Trunc->getType())); 13047 return true; 13048 } 13049 const auto *Add = dyn_cast<SCEVAddExpr>(Expr); 13050 if (Add == nullptr || Add->getNumOperands() != 2) 13051 return false; 13052 13053 const SCEV *A = Add->getOperand(1); 13054 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0)); 13055 13056 if (Mul == nullptr) 13057 return false; 13058 13059 const auto MatchURemWithDivisor = [&](const SCEV *B) { 13060 // (SomeExpr + (-(SomeExpr / B) * B)). 13061 if (Expr == getURemExpr(A, B)) { 13062 LHS = A; 13063 RHS = B; 13064 return true; 13065 } 13066 return false; 13067 }; 13068 13069 // (SomeExpr + (-1 * (SomeExpr / B) * B)). 13070 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0))) 13071 return MatchURemWithDivisor(Mul->getOperand(1)) || 13072 MatchURemWithDivisor(Mul->getOperand(2)); 13073 13074 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)). 13075 if (Mul->getNumOperands() == 2) 13076 return MatchURemWithDivisor(Mul->getOperand(1)) || 13077 MatchURemWithDivisor(Mul->getOperand(0)) || 13078 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) || 13079 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0))); 13080 return false; 13081 } 13082 13083 const SCEV * 13084 ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) { 13085 SmallVector<BasicBlock*, 16> ExitingBlocks; 13086 L->getExitingBlocks(ExitingBlocks); 13087 13088 // Form an expression for the maximum exit count possible for this loop. We 13089 // merge the max and exact information to approximate a version of 13090 // getConstantMaxBackedgeTakenCount which isn't restricted to just constants. 13091 SmallVector<const SCEV*, 4> ExitCounts; 13092 for (BasicBlock *ExitingBB : ExitingBlocks) { 13093 const SCEV *ExitCount = getExitCount(L, ExitingBB); 13094 if (isa<SCEVCouldNotCompute>(ExitCount)) 13095 ExitCount = getExitCount(L, ExitingBB, 13096 ScalarEvolution::ConstantMaximum); 13097 if (!isa<SCEVCouldNotCompute>(ExitCount)) { 13098 assert(DT.dominates(ExitingBB, L->getLoopLatch()) && 13099 "We should only have known counts for exiting blocks that " 13100 "dominate latch!"); 13101 ExitCounts.push_back(ExitCount); 13102 } 13103 } 13104 if (ExitCounts.empty()) 13105 return getCouldNotCompute(); 13106 return getUMinFromMismatchedTypes(ExitCounts); 13107 } 13108 13109 /// This rewriter is similar to SCEVParameterRewriter (it replaces SCEVUnknown 13110 /// components following the Map (Value -> SCEV)), but skips AddRecExpr because 13111 /// we cannot guarantee that the replacement is loop invariant in the loop of 13112 /// the AddRec. 13113 class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> { 13114 ValueToSCEVMapTy ⤅ 13115 13116 public: 13117 SCEVLoopGuardRewriter(ScalarEvolution &SE, ValueToSCEVMapTy &M) 13118 : SCEVRewriteVisitor(SE), Map(M) {} 13119 13120 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; } 13121 13122 const SCEV *visitUnknown(const SCEVUnknown *Expr) { 13123 auto I = Map.find(Expr->getValue()); 13124 if (I == Map.end()) 13125 return Expr; 13126 return I->second; 13127 } 13128 }; 13129 13130 const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) { 13131 auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, 13132 const SCEV *RHS, ValueToSCEVMapTy &RewriteMap) { 13133 if (!isa<SCEVUnknown>(LHS)) { 13134 std::swap(LHS, RHS); 13135 Predicate = CmpInst::getSwappedPredicate(Predicate); 13136 } 13137 13138 // For now, limit to conditions that provide information about unknown 13139 // expressions. 13140 auto *LHSUnknown = dyn_cast<SCEVUnknown>(LHS); 13141 if (!LHSUnknown) 13142 return; 13143 13144 // TODO: use information from more predicates. 13145 switch (Predicate) { 13146 case CmpInst::ICMP_ULT: { 13147 if (!containsAddRecurrence(RHS)) { 13148 const SCEV *Base = LHS; 13149 auto I = RewriteMap.find(LHSUnknown->getValue()); 13150 if (I != RewriteMap.end()) 13151 Base = I->second; 13152 13153 RewriteMap[LHSUnknown->getValue()] = 13154 getUMinExpr(Base, getMinusSCEV(RHS, getOne(RHS->getType()))); 13155 } 13156 break; 13157 } 13158 case CmpInst::ICMP_ULE: { 13159 if (!containsAddRecurrence(RHS)) { 13160 const SCEV *Base = LHS; 13161 auto I = RewriteMap.find(LHSUnknown->getValue()); 13162 if (I != RewriteMap.end()) 13163 Base = I->second; 13164 RewriteMap[LHSUnknown->getValue()] = getUMinExpr(Base, RHS); 13165 } 13166 break; 13167 } 13168 case CmpInst::ICMP_EQ: 13169 if (isa<SCEVConstant>(RHS)) 13170 RewriteMap[LHSUnknown->getValue()] = RHS; 13171 break; 13172 case CmpInst::ICMP_NE: 13173 if (isa<SCEVConstant>(RHS) && 13174 cast<SCEVConstant>(RHS)->getValue()->isNullValue()) 13175 RewriteMap[LHSUnknown->getValue()] = 13176 getUMaxExpr(LHS, getOne(RHS->getType())); 13177 break; 13178 default: 13179 break; 13180 } 13181 }; 13182 // Starting at the loop predecessor, climb up the predecessor chain, as long 13183 // as there are predecessors that can be found that have unique successors 13184 // leading to the original header. 13185 // TODO: share this logic with isLoopEntryGuardedByCond. 13186 ValueToSCEVMapTy RewriteMap; 13187 for (std::pair<const BasicBlock *, const BasicBlock *> Pair( 13188 L->getLoopPredecessor(), L->getHeader()); 13189 Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) { 13190 13191 const BranchInst *LoopEntryPredicate = 13192 dyn_cast<BranchInst>(Pair.first->getTerminator()); 13193 if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional()) 13194 continue; 13195 13196 // TODO: use information from more complex conditions, e.g. AND expressions. 13197 auto *Cmp = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition()); 13198 if (!Cmp) 13199 continue; 13200 13201 auto Predicate = Cmp->getPredicate(); 13202 if (LoopEntryPredicate->getSuccessor(1) == Pair.second) 13203 Predicate = CmpInst::getInversePredicate(Predicate); 13204 CollectCondition(Predicate, getSCEV(Cmp->getOperand(0)), 13205 getSCEV(Cmp->getOperand(1)), RewriteMap); 13206 } 13207 13208 // Also collect information from assumptions dominating the loop. 13209 for (auto &AssumeVH : AC.assumptions()) { 13210 if (!AssumeVH) 13211 continue; 13212 auto *AssumeI = cast<CallInst>(AssumeVH); 13213 auto *Cmp = dyn_cast<ICmpInst>(AssumeI->getOperand(0)); 13214 if (!Cmp || !DT.dominates(AssumeI, L->getHeader())) 13215 continue; 13216 CollectCondition(Cmp->getPredicate(), getSCEV(Cmp->getOperand(0)), 13217 getSCEV(Cmp->getOperand(1)), RewriteMap); 13218 } 13219 13220 if (RewriteMap.empty()) 13221 return Expr; 13222 SCEVLoopGuardRewriter Rewriter(*this, RewriteMap); 13223 return Rewriter.visit(Expr); 13224 } 13225