1 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // The ScalarEvolution class is an LLVM pass which can be used to analyze and 11 // categorize scalar expressions in loops. It specializes in recognizing 12 // general induction variables, representing them with the abstract and opaque 13 // SCEV class. Given this analysis, trip counts of loops and other important 14 // properties can be obtained. 15 // 16 // This analysis is primarily useful for induction variable substitution and 17 // strength reduction. 18 // 19 //===----------------------------------------------------------------------===// 20 21 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H 22 #define LLVM_ANALYSIS_SCALAREVOLUTION_H 23 24 #include "llvm/ADT/DenseSet.h" 25 #include "llvm/ADT/FoldingSet.h" 26 #include "llvm/IR/ConstantRange.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/Operator.h" 30 #include "llvm/IR/ValueHandle.h" 31 #include "llvm/Pass.h" 32 #include "llvm/Support/Allocator.h" 33 #include "llvm/Support/DataTypes.h" 34 #include <map> 35 36 namespace llvm { 37 class APInt; 38 class Constant; 39 class ConstantInt; 40 class DominatorTree; 41 class Type; 42 class ScalarEvolution; 43 class DataLayout; 44 class TargetLibraryInfo; 45 class LLVMContext; 46 class Loop; 47 class LoopInfo; 48 class Operator; 49 class SCEVUnknown; 50 class SCEV; 51 template<> struct FoldingSetTrait<SCEV>; 52 53 /// SCEV - This class represents an analyzed expression in the program. These 54 /// are opaque objects that the client is not allowed to do much with 55 /// directly. 56 /// 57 class SCEV : public FoldingSetNode { 58 friend struct FoldingSetTrait<SCEV>; 59 60 /// FastID - A reference to an Interned FoldingSetNodeID for this node. 61 /// The ScalarEvolution's BumpPtrAllocator holds the data. 62 FoldingSetNodeIDRef FastID; 63 64 // The SCEV baseclass this node corresponds to 65 const unsigned short SCEVType; 66 67 protected: 68 /// SubclassData - This field is initialized to zero and may be used in 69 /// subclasses to store miscellaneous information. 70 unsigned short SubclassData; 71 72 private: 73 SCEV(const SCEV &) LLVM_DELETED_FUNCTION; 74 void operator=(const SCEV &) LLVM_DELETED_FUNCTION; 75 76 public: 77 /// NoWrapFlags are bitfield indices into SubclassData. 78 /// 79 /// Add and Mul expressions may have no-unsigned-wrap <NUW> or 80 /// no-signed-wrap <NSW> properties, which are derived from the IR 81 /// operator. NSW is a misnomer that we use to mean no signed overflow or 82 /// underflow. 83 /// 84 /// AddRec expression may have a no-self-wraparound <NW> property if the 85 /// result can never reach the start value. This property is independent of 86 /// the actual start value and step direction. Self-wraparound is defined 87 /// purely in terms of the recurrence's loop, step size, and 88 /// bitwidth. Formally, a recurrence with no self-wraparound satisfies: 89 /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth). 90 /// 91 /// Note that NUW and NSW are also valid properties of a recurrence, and 92 /// either implies NW. For convenience, NW will be set for a recurrence 93 /// whenever either NUW or NSW are set. 94 enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee. 95 FlagNW = (1 << 0), // No self-wrap. 96 FlagNUW = (1 << 1), // No unsigned wrap. 97 FlagNSW = (1 << 2), // No signed wrap. 98 NoWrapMask = (1 << 3) -1 }; 99 100 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) : 101 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {} 102 103 unsigned getSCEVType() const { return SCEVType; } 104 105 /// getType - Return the LLVM type of this SCEV expression. 106 /// 107 Type *getType() const; 108 109 /// isZero - Return true if the expression is a constant zero. 110 /// 111 bool isZero() const; 112 113 /// isOne - Return true if the expression is a constant one. 114 /// 115 bool isOne() const; 116 117 /// isAllOnesValue - Return true if the expression is a constant 118 /// all-ones value. 119 /// 120 bool isAllOnesValue() const; 121 122 /// isNonConstantNegative - Return true if the specified scev is negated, 123 /// but not a constant. 124 bool isNonConstantNegative() const; 125 126 /// print - Print out the internal representation of this scalar to the 127 /// specified stream. This should really only be used for debugging 128 /// purposes. 129 void print(raw_ostream &OS) const; 130 131 /// dump - This method is used for debugging. 132 /// 133 void dump() const; 134 }; 135 136 // Specialize FoldingSetTrait for SCEV to avoid needing to compute 137 // temporary FoldingSetNodeID values. 138 template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> { 139 static void Profile(const SCEV &X, FoldingSetNodeID& ID) { 140 ID = X.FastID; 141 } 142 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, 143 unsigned IDHash, FoldingSetNodeID &TempID) { 144 return ID == X.FastID; 145 } 146 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) { 147 return X.FastID.ComputeHash(); 148 } 149 }; 150 151 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) { 152 S.print(OS); 153 return OS; 154 } 155 156 /// SCEVCouldNotCompute - An object of this class is returned by queries that 157 /// could not be answered. For example, if you ask for the number of 158 /// iterations of a linked-list traversal loop, you will get one of these. 159 /// None of the standard SCEV operations are valid on this class, it is just a 160 /// marker. 161 struct SCEVCouldNotCompute : public SCEV { 162 SCEVCouldNotCompute(); 163 164 /// Methods for support type inquiry through isa, cast, and dyn_cast: 165 static bool classof(const SCEV *S); 166 }; 167 168 /// ScalarEvolution - This class is the main scalar evolution driver. Because 169 /// client code (intentionally) can't do much with the SCEV objects directly, 170 /// they must ask this class for services. 171 /// 172 class ScalarEvolution : public FunctionPass { 173 public: 174 /// LoopDisposition - An enum describing the relationship between a 175 /// SCEV and a loop. 176 enum LoopDisposition { 177 LoopVariant, ///< The SCEV is loop-variant (unknown). 178 LoopInvariant, ///< The SCEV is loop-invariant. 179 LoopComputable ///< The SCEV varies predictably with the loop. 180 }; 181 182 /// BlockDisposition - An enum describing the relationship between a 183 /// SCEV and a basic block. 184 enum BlockDisposition { 185 DoesNotDominateBlock, ///< The SCEV does not dominate the block. 186 DominatesBlock, ///< The SCEV dominates the block. 187 ProperlyDominatesBlock ///< The SCEV properly dominates the block. 188 }; 189 190 /// Convenient NoWrapFlags manipulation that hides enum casts and is 191 /// visible in the ScalarEvolution name space. 192 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT 193 maskFlags(SCEV::NoWrapFlags Flags, int Mask) { 194 return (SCEV::NoWrapFlags)(Flags & Mask); 195 } 196 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT 197 setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) { 198 return (SCEV::NoWrapFlags)(Flags | OnFlags); 199 } 200 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT 201 clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) { 202 return (SCEV::NoWrapFlags)(Flags & ~OffFlags); 203 } 204 205 private: 206 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be 207 /// notified whenever a Value is deleted. 208 class SCEVCallbackVH : public CallbackVH { 209 ScalarEvolution *SE; 210 void deleted() override; 211 void allUsesReplacedWith(Value *New) override; 212 public: 213 SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr); 214 }; 215 216 friend class SCEVCallbackVH; 217 friend class SCEVExpander; 218 friend class SCEVUnknown; 219 220 /// F - The function we are analyzing. 221 /// 222 Function *F; 223 224 /// LI - The loop information for the function we are currently analyzing. 225 /// 226 LoopInfo *LI; 227 228 /// The DataLayout information for the target we are targeting. 229 /// 230 const DataLayout *DL; 231 232 /// TLI - The target library information for the target we are targeting. 233 /// 234 TargetLibraryInfo *TLI; 235 236 /// DT - The dominator tree. 237 /// 238 DominatorTree *DT; 239 240 /// CouldNotCompute - This SCEV is used to represent unknown trip 241 /// counts and things. 242 SCEVCouldNotCompute CouldNotCompute; 243 244 /// ValueExprMapType - The typedef for ValueExprMap. 245 /// 246 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> > 247 ValueExprMapType; 248 249 /// ValueExprMap - This is a cache of the values we have analyzed so far. 250 /// 251 ValueExprMapType ValueExprMap; 252 253 /// Mark predicate values currently being processed by isImpliedCond. 254 DenseSet<Value*> PendingLoopPredicates; 255 256 /// ExitLimit - Information about the number of loop iterations for which a 257 /// loop exit's branch condition evaluates to the not-taken path. This is a 258 /// temporary pair of exact and max expressions that are eventually 259 /// summarized in ExitNotTakenInfo and BackedgeTakenInfo. 260 /// 261 /// If MustExit is true, then the exit must be taken when the BECount 262 /// reaches Exact (and before surpassing Max). If MustExit is false, then 263 /// BECount may exceed Exact or Max if the loop exits via another branch. In 264 /// either case, the loop may exit early via another branch. 265 /// 266 /// MustExit is true for most cases. However, an exit guarded by an 267 /// (in)equality on a nonunit stride may be skipped. 268 struct ExitLimit { 269 const SCEV *Exact; 270 const SCEV *Max; 271 bool MustExit; 272 273 /*implicit*/ ExitLimit(const SCEV *E) 274 : Exact(E), Max(E), MustExit(true) {} 275 276 ExitLimit(const SCEV *E, const SCEV *M, bool MustExit) 277 : Exact(E), Max(M), MustExit(MustExit) {} 278 279 /// hasAnyInfo - Test whether this ExitLimit contains any computed 280 /// information, or whether it's all SCEVCouldNotCompute values. 281 bool hasAnyInfo() const { 282 return !isa<SCEVCouldNotCompute>(Exact) || 283 !isa<SCEVCouldNotCompute>(Max); 284 } 285 }; 286 287 /// ExitNotTakenInfo - Information about the number of times a particular 288 /// loop exit may be reached before exiting the loop. 289 struct ExitNotTakenInfo { 290 AssertingVH<BasicBlock> ExitingBlock; 291 const SCEV *ExactNotTaken; 292 PointerIntPair<ExitNotTakenInfo*, 1> NextExit; 293 294 ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {} 295 296 /// isCompleteList - Return true if all loop exits are computable. 297 bool isCompleteList() const { 298 return NextExit.getInt() == 0; 299 } 300 301 void setIncomplete() { NextExit.setInt(1); } 302 303 /// getNextExit - Return a pointer to the next exit's not-taken info. 304 ExitNotTakenInfo *getNextExit() const { 305 return NextExit.getPointer(); 306 } 307 308 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); } 309 }; 310 311 /// BackedgeTakenInfo - Information about the backedge-taken count 312 /// of a loop. This currently includes an exact count and a maximum count. 313 /// 314 class BackedgeTakenInfo { 315 /// ExitNotTaken - A list of computable exits and their not-taken counts. 316 /// Loops almost never have more than one computable exit. 317 ExitNotTakenInfo ExitNotTaken; 318 319 /// Max - An expression indicating the least maximum backedge-taken 320 /// count of the loop that is known, or a SCEVCouldNotCompute. 321 const SCEV *Max; 322 323 public: 324 BackedgeTakenInfo() : Max(nullptr) {} 325 326 /// Initialize BackedgeTakenInfo from a list of exact exit counts. 327 BackedgeTakenInfo( 328 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts, 329 bool Complete, const SCEV *MaxCount); 330 331 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any 332 /// computed information, or whether it's all SCEVCouldNotCompute 333 /// values. 334 bool hasAnyInfo() const { 335 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max); 336 } 337 338 /// getExact - Return an expression indicating the exact backedge-taken 339 /// count of the loop if it is known, or SCEVCouldNotCompute 340 /// otherwise. This is the number of times the loop header can be 341 /// guaranteed to execute, minus one. 342 const SCEV *getExact(ScalarEvolution *SE) const; 343 344 /// getExact - Return the number of times this loop exit may fall through 345 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not 346 /// to exit via this block before this number of iterations, but may exit 347 /// via another block. 348 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const; 349 350 /// getMax - Get the max backedge taken count for the loop. 351 const SCEV *getMax(ScalarEvolution *SE) const; 352 353 /// Return true if any backedge taken count expressions refer to the given 354 /// subexpression. 355 bool hasOperand(const SCEV *S, ScalarEvolution *SE) const; 356 357 /// clear - Invalidate this result and free associated memory. 358 void clear(); 359 }; 360 361 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for 362 /// this function as they are computed. 363 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts; 364 365 /// ConstantEvolutionLoopExitValue - This map contains entries for all of 366 /// the PHI instructions that we attempt to compute constant evolutions for. 367 /// This allows us to avoid potentially expensive recomputation of these 368 /// properties. An instruction maps to null if we are unable to compute its 369 /// exit value. 370 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue; 371 372 /// ValuesAtScopes - This map contains entries for all the expressions 373 /// that we attempt to compute getSCEVAtScope information for, which can 374 /// be expensive in extreme cases. 375 DenseMap<const SCEV *, 376 SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes; 377 378 /// LoopDispositions - Memoized computeLoopDisposition results. 379 DenseMap<const SCEV *, 380 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> > LoopDispositions; 381 382 /// computeLoopDisposition - Compute a LoopDisposition value. 383 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L); 384 385 /// BlockDispositions - Memoized computeBlockDisposition results. 386 DenseMap<const SCEV *, 387 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> > BlockDispositions; 388 389 /// computeBlockDisposition - Compute a BlockDisposition value. 390 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB); 391 392 /// UnsignedRanges - Memoized results from getUnsignedRange 393 DenseMap<const SCEV *, ConstantRange> UnsignedRanges; 394 395 /// SignedRanges - Memoized results from getSignedRange 396 DenseMap<const SCEV *, ConstantRange> SignedRanges; 397 398 /// setUnsignedRange - Set the memoized unsigned range for the given SCEV. 399 const ConstantRange &setUnsignedRange(const SCEV *S, 400 const ConstantRange &CR) { 401 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair = 402 UnsignedRanges.insert(std::make_pair(S, CR)); 403 if (!Pair.second) 404 Pair.first->second = CR; 405 return Pair.first->second; 406 } 407 408 /// setUnsignedRange - Set the memoized signed range for the given SCEV. 409 const ConstantRange &setSignedRange(const SCEV *S, 410 const ConstantRange &CR) { 411 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair = 412 SignedRanges.insert(std::make_pair(S, CR)); 413 if (!Pair.second) 414 Pair.first->second = CR; 415 return Pair.first->second; 416 } 417 418 /// createSCEV - We know that there is no SCEV for the specified value. 419 /// Analyze the expression. 420 const SCEV *createSCEV(Value *V); 421 422 /// createNodeForPHI - Provide the special handling we need to analyze PHI 423 /// SCEVs. 424 const SCEV *createNodeForPHI(PHINode *PN); 425 426 /// createNodeForGEP - Provide the special handling we need to analyze GEP 427 /// SCEVs. 428 const SCEV *createNodeForGEP(GEPOperator *GEP); 429 430 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called 431 /// at most once for each SCEV+Loop pair. 432 /// 433 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L); 434 435 /// ForgetSymbolicValue - This looks up computed SCEV values for all 436 /// instructions that depend on the given instruction and removes them from 437 /// the ValueExprMap map if they reference SymName. This is used during PHI 438 /// resolution. 439 void ForgetSymbolicName(Instruction *I, const SCEV *SymName); 440 441 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given 442 /// loop, lazily computing new values if the loop hasn't been analyzed 443 /// yet. 444 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L); 445 446 /// ComputeBackedgeTakenCount - Compute the number of times the specified 447 /// loop will iterate. 448 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L); 449 450 /// ComputeExitLimit - Compute the number of times the backedge of the 451 /// specified loop will execute if it exits via the specified block. 452 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock); 453 454 /// ComputeExitLimitFromCond - Compute the number of times the backedge of 455 /// the specified loop will execute if its exit condition were a conditional 456 /// branch of ExitCond, TBB, and FBB. 457 ExitLimit ComputeExitLimitFromCond(const Loop *L, 458 Value *ExitCond, 459 BasicBlock *TBB, 460 BasicBlock *FBB, 461 bool IsSubExpr); 462 463 /// ComputeExitLimitFromICmp - Compute the number of times the backedge of 464 /// the specified loop will execute if its exit condition were a conditional 465 /// branch of the ICmpInst ExitCond, TBB, and FBB. 466 ExitLimit ComputeExitLimitFromICmp(const Loop *L, 467 ICmpInst *ExitCond, 468 BasicBlock *TBB, 469 BasicBlock *FBB, 470 bool IsSubExpr); 471 472 /// ComputeExitLimitFromSingleExitSwitch - Compute the number of times the 473 /// backedge of the specified loop will execute if its exit condition were a 474 /// switch with a single exiting case to ExitingBB. 475 ExitLimit 476 ComputeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch, 477 BasicBlock *ExitingBB, bool IsSubExpr); 478 479 /// ComputeLoadConstantCompareExitLimit - Given an exit condition 480 /// of 'icmp op load X, cst', try to see if we can compute the 481 /// backedge-taken count. 482 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI, 483 Constant *RHS, 484 const Loop *L, 485 ICmpInst::Predicate p); 486 487 /// ComputeExitCountExhaustively - If the loop is known to execute a 488 /// constant number of times (the condition evolves only from constants), 489 /// try to evaluate a few iterations of the loop until we get the exit 490 /// condition gets a value of ExitWhen (true or false). If we cannot 491 /// evaluate the exit count of the loop, return CouldNotCompute. 492 const SCEV *ComputeExitCountExhaustively(const Loop *L, 493 Value *Cond, 494 bool ExitWhen); 495 496 /// HowFarToZero - Return the number of times an exit condition comparing 497 /// the specified value to zero will execute. If not computable, return 498 /// CouldNotCompute. 499 ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr); 500 501 /// HowFarToNonZero - Return the number of times an exit condition checking 502 /// the specified value for nonzero will execute. If not computable, return 503 /// CouldNotCompute. 504 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L); 505 506 /// HowManyLessThans - Return the number of times an exit condition 507 /// containing the specified less-than comparison will execute. If not 508 /// computable, return CouldNotCompute. isSigned specifies whether the 509 /// less-than is signed. 510 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS, 511 const Loop *L, bool isSigned, bool IsSubExpr); 512 ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 513 const Loop *L, bool isSigned, bool IsSubExpr); 514 515 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB 516 /// (which may not be an immediate predecessor) which has exactly one 517 /// successor from which BB is reachable, or null if no such block is 518 /// found. 519 std::pair<BasicBlock *, BasicBlock *> 520 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB); 521 522 /// isImpliedCond - Test whether the condition described by Pred, LHS, and 523 /// RHS is true whenever the given FoundCondValue value evaluates to true. 524 bool isImpliedCond(ICmpInst::Predicate Pred, 525 const SCEV *LHS, const SCEV *RHS, 526 Value *FoundCondValue, 527 bool Inverse); 528 529 /// isImpliedCondOperands - Test whether the condition described by Pred, 530 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, 531 /// and FoundRHS is true. 532 bool isImpliedCondOperands(ICmpInst::Predicate Pred, 533 const SCEV *LHS, const SCEV *RHS, 534 const SCEV *FoundLHS, const SCEV *FoundRHS); 535 536 /// isImpliedCondOperandsHelper - Test whether the condition described by 537 /// Pred, LHS, and RHS is true whenever the condition described by Pred, 538 /// FoundLHS, and FoundRHS is true. 539 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 540 const SCEV *LHS, const SCEV *RHS, 541 const SCEV *FoundLHS, 542 const SCEV *FoundRHS); 543 544 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 545 /// in the header of its containing loop, we know the loop executes a 546 /// constant number of times, and the PHI node is just a recurrence 547 /// involving constants, fold it. 548 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, 549 const Loop *L); 550 551 /// isKnownPredicateWithRanges - Test if the given expression is known to 552 /// satisfy the condition described by Pred and the known constant ranges 553 /// of LHS and RHS. 554 /// 555 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred, 556 const SCEV *LHS, const SCEV *RHS); 557 558 /// forgetMemoizedResults - Drop memoized information computed for S. 559 void forgetMemoizedResults(const SCEV *S); 560 561 /// Return false iff given SCEV contains a SCEVUnknown with NULL value- 562 /// pointer. 563 bool checkValidity(const SCEV *S) const; 564 565 public: 566 static char ID; // Pass identification, replacement for typeid 567 ScalarEvolution(); 568 569 LLVMContext &getContext() const { return F->getContext(); } 570 571 /// isSCEVable - Test if values of the given type are analyzable within 572 /// the SCEV framework. This primarily includes integer types, and it 573 /// can optionally include pointer types if the ScalarEvolution class 574 /// has access to target-specific information. 575 bool isSCEVable(Type *Ty) const; 576 577 /// getTypeSizeInBits - Return the size in bits of the specified type, 578 /// for which isSCEVable must return true. 579 uint64_t getTypeSizeInBits(Type *Ty) const; 580 581 /// getEffectiveSCEVType - Return a type with the same bitwidth as 582 /// the given type and which represents how SCEV will treat the given 583 /// type, for which isSCEVable must return true. For pointer types, 584 /// this is the pointer-sized integer type. 585 Type *getEffectiveSCEVType(Type *Ty) const; 586 587 /// getSCEV - Return a SCEV expression for the full generality of the 588 /// specified expression. 589 const SCEV *getSCEV(Value *V); 590 591 const SCEV *getConstant(ConstantInt *V); 592 const SCEV *getConstant(const APInt& Val); 593 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false); 594 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty); 595 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty); 596 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty); 597 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty); 598 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 599 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); 600 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS, 601 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { 602 SmallVector<const SCEV *, 2> Ops; 603 Ops.push_back(LHS); 604 Ops.push_back(RHS); 605 return getAddExpr(Ops, Flags); 606 } 607 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, 608 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { 609 SmallVector<const SCEV *, 3> Ops; 610 Ops.push_back(Op0); 611 Ops.push_back(Op1); 612 Ops.push_back(Op2); 613 return getAddExpr(Ops, Flags); 614 } 615 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 616 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); 617 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS, 618 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) 619 { 620 SmallVector<const SCEV *, 2> Ops; 621 Ops.push_back(LHS); 622 Ops.push_back(RHS); 623 return getMulExpr(Ops, Flags); 624 } 625 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, 626 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { 627 SmallVector<const SCEV *, 3> Ops; 628 Ops.push_back(Op0); 629 Ops.push_back(Op1); 630 Ops.push_back(Op2); 631 return getMulExpr(Ops, Flags); 632 } 633 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS); 634 const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS); 635 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step, 636 const Loop *L, SCEV::NoWrapFlags Flags); 637 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 638 const Loop *L, SCEV::NoWrapFlags Flags); 639 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands, 640 const Loop *L, SCEV::NoWrapFlags Flags) { 641 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end()); 642 return getAddRecExpr(NewOp, L, Flags); 643 } 644 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS); 645 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands); 646 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS); 647 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands); 648 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS); 649 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS); 650 const SCEV *getUnknown(Value *V); 651 const SCEV *getCouldNotCompute(); 652 653 /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type 654 /// IntTy 655 /// 656 const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy); 657 658 /// getOffsetOfExpr - Return an expression for offsetof on the given field 659 /// with type IntTy 660 /// 661 const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo); 662 663 /// getNegativeSCEV - Return the SCEV object corresponding to -V. 664 /// 665 const SCEV *getNegativeSCEV(const SCEV *V); 666 667 /// getNotSCEV - Return the SCEV object corresponding to ~V. 668 /// 669 const SCEV *getNotSCEV(const SCEV *V); 670 671 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1. 672 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 673 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); 674 675 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion 676 /// of the input value to the specified type. If the type must be 677 /// extended, it is zero extended. 678 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty); 679 680 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion 681 /// of the input value to the specified type. If the type must be 682 /// extended, it is sign extended. 683 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty); 684 685 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of 686 /// the input value to the specified type. If the type must be extended, 687 /// it is zero extended. The conversion must not be narrowing. 688 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty); 689 690 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of 691 /// the input value to the specified type. If the type must be extended, 692 /// it is sign extended. The conversion must not be narrowing. 693 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty); 694 695 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of 696 /// the input value to the specified type. If the type must be extended, 697 /// it is extended with unspecified bits. The conversion must not be 698 /// narrowing. 699 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty); 700 701 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the 702 /// input value to the specified type. The conversion must not be 703 /// widening. 704 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty); 705 706 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of 707 /// the types using zero-extension, and then perform a umax operation 708 /// with them. 709 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS, 710 const SCEV *RHS); 711 712 /// getUMinFromMismatchedTypes - Promote the operands to the wider of 713 /// the types using zero-extension, and then perform a umin operation 714 /// with them. 715 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS, 716 const SCEV *RHS); 717 718 /// getPointerBase - Transitively follow the chain of pointer-type operands 719 /// until reaching a SCEV that does not have a single pointer operand. This 720 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, 721 /// but corner cases do exist. 722 const SCEV *getPointerBase(const SCEV *V); 723 724 /// getSCEVAtScope - Return a SCEV expression for the specified value 725 /// at the specified scope in the program. The L value specifies a loop 726 /// nest to evaluate the expression at, where null is the top-level or a 727 /// specified loop is immediately inside of the loop. 728 /// 729 /// This method can be used to compute the exit value for a variable defined 730 /// in a loop by querying what the value will hold in the parent loop. 731 /// 732 /// In the case that a relevant loop exit value cannot be computed, the 733 /// original value V is returned. 734 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L); 735 736 /// getSCEVAtScope - This is a convenience function which does 737 /// getSCEVAtScope(getSCEV(V), L). 738 const SCEV *getSCEVAtScope(Value *V, const Loop *L); 739 740 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected 741 /// by a conditional between LHS and RHS. This is used to help avoid max 742 /// expressions in loop trip counts, and to eliminate casts. 743 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, 744 const SCEV *LHS, const SCEV *RHS); 745 746 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 747 /// protected by a conditional between LHS and RHS. This is used to 748 /// to eliminate casts. 749 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, 750 const SCEV *LHS, const SCEV *RHS); 751 752 /// getSmallConstantTripCount - Returns the maximum trip count of this loop 753 /// as a normal unsigned value. Returns 0 if the trip count is unknown or 754 /// not constant. This "trip count" assumes that control exits via 755 /// ExitingBlock. More precisely, it is the number of times that control may 756 /// reach ExitingBlock before taking the branch. For loops with multiple 757 /// exits, it may not be the number times that the loop header executes if 758 /// the loop exits prematurely via another branch. 759 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock); 760 761 /// getSmallConstantTripMultiple - Returns the largest constant divisor of 762 /// the trip count of this loop as a normal unsigned value, if 763 /// possible. This means that the actual trip count is always a multiple of 764 /// the returned value (don't forget the trip count could very well be zero 765 /// as well!). As explained in the comments for getSmallConstantTripCount, 766 /// this assumes that control exits the loop via ExitingBlock. 767 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock); 768 769 // getExitCount - Get the expression for the number of loop iterations for 770 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise 771 // return SCEVCouldNotCompute. 772 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock); 773 774 /// getBackedgeTakenCount - If the specified loop has a predictable 775 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute 776 /// object. The backedge-taken count is the number of times the loop header 777 /// will be branched to from within the loop. This is one less than the 778 /// trip count of the loop, since it doesn't count the first iteration, 779 /// when the header is branched to from outside the loop. 780 /// 781 /// Note that it is not valid to call this method on a loop without a 782 /// loop-invariant backedge-taken count (see 783 /// hasLoopInvariantBackedgeTakenCount). 784 /// 785 const SCEV *getBackedgeTakenCount(const Loop *L); 786 787 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except 788 /// return the least SCEV value that is known never to be less than the 789 /// actual backedge taken count. 790 const SCEV *getMaxBackedgeTakenCount(const Loop *L); 791 792 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop 793 /// has an analyzable loop-invariant backedge-taken count. 794 bool hasLoopInvariantBackedgeTakenCount(const Loop *L); 795 796 /// forgetLoop - This method should be called by the client when it has 797 /// changed a loop in a way that may effect ScalarEvolution's ability to 798 /// compute a trip count, or if the loop is deleted. 799 void forgetLoop(const Loop *L); 800 801 /// forgetValue - This method should be called by the client when it has 802 /// changed a value in a way that may effect its value, or which may 803 /// disconnect it from a def-use chain linking it to a loop. 804 void forgetValue(Value *V); 805 806 /// \brief Called when the client has changed the disposition of values in 807 /// this loop. 808 /// 809 /// We don't have a way to invalidate per-loop dispositions. Clear and 810 /// recompute is simpler. 811 void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); } 812 813 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S 814 /// is guaranteed to end in (at every loop iteration). It is, at the same 815 /// time, the minimum number of times S is divisible by 2. For example, 816 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the 817 /// bitwidth of S. 818 uint32_t GetMinTrailingZeros(const SCEV *S); 819 820 /// getUnsignedRange - Determine the unsigned range for a particular SCEV. 821 /// 822 ConstantRange getUnsignedRange(const SCEV *S); 823 824 /// getSignedRange - Determine the signed range for a particular SCEV. 825 /// 826 ConstantRange getSignedRange(const SCEV *S); 827 828 /// isKnownNegative - Test if the given expression is known to be negative. 829 /// 830 bool isKnownNegative(const SCEV *S); 831 832 /// isKnownPositive - Test if the given expression is known to be positive. 833 /// 834 bool isKnownPositive(const SCEV *S); 835 836 /// isKnownNonNegative - Test if the given expression is known to be 837 /// non-negative. 838 /// 839 bool isKnownNonNegative(const SCEV *S); 840 841 /// isKnownNonPositive - Test if the given expression is known to be 842 /// non-positive. 843 /// 844 bool isKnownNonPositive(const SCEV *S); 845 846 /// isKnownNonZero - Test if the given expression is known to be 847 /// non-zero. 848 /// 849 bool isKnownNonZero(const SCEV *S); 850 851 /// isKnownPredicate - Test if the given expression is known to satisfy 852 /// the condition described by Pred, LHS, and RHS. 853 /// 854 bool isKnownPredicate(ICmpInst::Predicate Pred, 855 const SCEV *LHS, const SCEV *RHS); 856 857 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with 858 /// predicate Pred. Return true iff any changes were made. If the 859 /// operands are provably equal or unequal, LHS and RHS are set to 860 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE. 861 /// 862 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, 863 const SCEV *&LHS, 864 const SCEV *&RHS, 865 unsigned Depth = 0); 866 867 /// getLoopDisposition - Return the "disposition" of the given SCEV with 868 /// respect to the given loop. 869 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L); 870 871 /// isLoopInvariant - Return true if the value of the given SCEV is 872 /// unchanging in the specified loop. 873 bool isLoopInvariant(const SCEV *S, const Loop *L); 874 875 /// hasComputableLoopEvolution - Return true if the given SCEV changes value 876 /// in a known way in the specified loop. This property being true implies 877 /// that the value is variant in the loop AND that we can emit an expression 878 /// to compute the value of the expression at any particular loop iteration. 879 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L); 880 881 /// getLoopDisposition - Return the "disposition" of the given SCEV with 882 /// respect to the given block. 883 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB); 884 885 /// dominates - Return true if elements that makes up the given SCEV 886 /// dominate the specified basic block. 887 bool dominates(const SCEV *S, const BasicBlock *BB); 888 889 /// properlyDominates - Return true if elements that makes up the given SCEV 890 /// properly dominate the specified basic block. 891 bool properlyDominates(const SCEV *S, const BasicBlock *BB); 892 893 /// hasOperand - Test whether the given SCEV has Op as a direct or 894 /// indirect operand. 895 bool hasOperand(const SCEV *S, const SCEV *Op) const; 896 897 /// Return the size of an element read or written by Inst. 898 const SCEV *getElementSize(Instruction *Inst); 899 900 /// Compute the array dimensions Sizes from the set of Terms extracted from 901 /// the memory access function of this SCEVAddRecExpr. 902 void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 903 SmallVectorImpl<const SCEV *> &Sizes, 904 const SCEV *ElementSize) const; 905 906 bool runOnFunction(Function &F) override; 907 void releaseMemory() override; 908 void getAnalysisUsage(AnalysisUsage &AU) const override; 909 void print(raw_ostream &OS, const Module* = nullptr) const override; 910 void verifyAnalysis() const override; 911 912 private: 913 /// Compute the backedge taken count knowing the interval difference, the 914 /// stride and presence of the equality in the comparison. 915 const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride, 916 bool Equality); 917 918 /// Verify if an linear IV with positive stride can overflow when in a 919 /// less-than comparison, knowing the invariant term of the comparison, 920 /// the stride and the knowledge of NSW/NUW flags on the recurrence. 921 bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 922 bool IsSigned, bool NoWrap); 923 924 /// Verify if an linear IV with negative stride can overflow when in a 925 /// greater-than comparison, knowing the invariant term of the comparison, 926 /// the stride and the knowledge of NSW/NUW flags on the recurrence. 927 bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 928 bool IsSigned, bool NoWrap); 929 930 private: 931 FoldingSet<SCEV> UniqueSCEVs; 932 BumpPtrAllocator SCEVAllocator; 933 934 /// FirstUnknown - The head of a linked list of all SCEVUnknown 935 /// values that have been allocated. This is used by releaseMemory 936 /// to locate them all and call their destructors. 937 SCEVUnknown *FirstUnknown; 938 }; 939 } 940 941 #endif 942