1 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The ScalarEvolution class is an LLVM pass which can be used to analyze and
11 // catagorize 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.
16 // This analysis is primarily useful for induction variable substitution and
17 // strength reduction.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
22 #define LLVM_ANALYSIS_SCALAREVOLUTION_H
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Support/DataTypes.h"
27 #include "llvm/Support/ValueHandle.h"
28 #include "llvm/Support/Allocator.h"
29 #include "llvm/Support/ConstantRange.h"
30 #include "llvm/ADT/FoldingSet.h"
31 #include "llvm/ADT/DenseMap.h"
38 class ScalarEvolution;
42 /// SCEV - This class represents an analyzed expression in the program. These
43 /// are opaque objects that the client is not allowed to do much with
46 class SCEV : public FoldingSetNode {
47 const unsigned SCEVType; // The SCEV baseclass this node corresponds to
49 SCEV(const SCEV &); // DO NOT IMPLEMENT
50 void operator=(const SCEV &); // DO NOT IMPLEMENT
54 explicit SCEV(unsigned SCEVTy) :
57 virtual void Profile(FoldingSetNodeID &ID) const = 0;
59 unsigned getSCEVType() const { return SCEVType; }
61 /// isLoopInvariant - Return true if the value of this SCEV is unchanging in
62 /// the specified loop.
63 virtual bool isLoopInvariant(const Loop *L) const = 0;
65 /// hasComputableLoopEvolution - Return true if this SCEV changes value in a
66 /// known way in the specified loop. This property being true implies that
67 /// the value is variant in the loop AND that we can emit an expression to
68 /// compute the value of the expression at any particular loop iteration.
69 virtual bool hasComputableLoopEvolution(const Loop *L) const = 0;
71 /// getType - Return the LLVM type of this SCEV expression.
73 virtual const Type *getType() const = 0;
75 /// isZero - Return true if the expression is a constant zero.
79 /// isOne - Return true if the expression is a constant one.
83 /// isAllOnesValue - Return true if the expression is a constant
86 bool isAllOnesValue() const;
88 /// replaceSymbolicValuesWithConcrete - If this SCEV internally references
89 /// the symbolic value "Sym", construct and return a new SCEV that produces
90 /// the same value, but which uses the concrete value Conc instead of the
91 /// symbolic value. If this SCEV does not use the symbolic value, it
94 replaceSymbolicValuesWithConcrete(const SCEV *Sym,
96 ScalarEvolution &SE) const = 0;
98 /// dominates - Return true if elements that makes up this SCEV dominates
99 /// the specified basic block.
100 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const = 0;
102 /// print - Print out the internal representation of this scalar to the
103 /// specified stream. This should really only be used for debugging
105 virtual void print(raw_ostream &OS) const = 0;
106 void print(std::ostream &OS) const;
107 void print(std::ostream *OS) const { if (OS) print(*OS); }
109 /// dump - This method is used for debugging.
114 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
119 inline std::ostream &operator<<(std::ostream &OS, const SCEV &S) {
124 /// SCEVCouldNotCompute - An object of this class is returned by queries that
125 /// could not be answered. For example, if you ask for the number of
126 /// iterations of a linked-list traversal loop, you will get one of these.
127 /// None of the standard SCEV operations are valid on this class, it is just a
129 struct SCEVCouldNotCompute : public SCEV {
130 SCEVCouldNotCompute();
132 // None of these methods are valid for this object.
133 virtual void Profile(FoldingSetNodeID &ID) const;
134 virtual bool isLoopInvariant(const Loop *L) const;
135 virtual const Type *getType() const;
136 virtual bool hasComputableLoopEvolution(const Loop *L) const;
137 virtual void print(raw_ostream &OS) const;
139 replaceSymbolicValuesWithConcrete(const SCEV *Sym,
141 ScalarEvolution &SE) const;
143 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const {
147 /// Methods for support type inquiry through isa, cast, and dyn_cast:
148 static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
149 static bool classof(const SCEV *S);
152 /// ScalarEvolution - This class is the main scalar evolution driver. Because
153 /// client code (intentionally) can't do much with the SCEV objects directly,
154 /// they must ask this class for services.
156 class ScalarEvolution : public FunctionPass {
157 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
158 /// notified whenever a Value is deleted.
159 class SCEVCallbackVH : public CallbackVH {
161 virtual void deleted();
162 virtual void allUsesReplacedWith(Value *New);
164 SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
167 friend class SCEVCallbackVH;
168 friend class SCEVExpander;
170 /// F - The function we are analyzing.
174 /// LI - The loop information for the function we are currently analyzing.
178 /// TD - The target data information for the target we are targetting.
182 /// CouldNotCompute - This SCEV is used to represent unknown trip
183 /// counts and things.
184 SCEVCouldNotCompute CouldNotCompute;
186 /// Scalars - This is a cache of the scalars we have analyzed so far.
188 std::map<SCEVCallbackVH, const SCEV *> Scalars;
190 /// BackedgeTakenInfo - Information about the backedge-taken count
191 /// of a loop. This currently inclues an exact count and a maximum count.
193 struct BackedgeTakenInfo {
194 /// Exact - An expression indicating the exact backedge-taken count of
195 /// the loop if it is known, or a SCEVCouldNotCompute otherwise.
198 /// Max - An expression indicating the least maximum backedge-taken
199 /// count of the loop that is known, or a SCEVCouldNotCompute.
202 /*implicit*/ BackedgeTakenInfo(const SCEV *exact) :
203 Exact(exact), Max(exact) {}
205 BackedgeTakenInfo(const SCEV *exact, const SCEV *max) :
206 Exact(exact), Max(max) {}
208 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
209 /// computed information, or whether it's all SCEVCouldNotCompute
211 bool hasAnyInfo() const {
212 return !isa<SCEVCouldNotCompute>(Exact) ||
213 !isa<SCEVCouldNotCompute>(Max);
217 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
218 /// this function as they are computed.
219 std::map<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
221 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
222 /// the PHI instructions that we attempt to compute constant evolutions for.
223 /// This allows us to avoid potentially expensive recomputation of these
224 /// properties. An instruction maps to null if we are unable to compute its
226 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
228 /// ValuesAtScopes - This map contains entries for all the instructions
229 /// that we attempt to compute getSCEVAtScope information for without
230 /// using SCEV techniques, which can be expensive.
231 std::map<Instruction *, std::map<const Loop *, Constant *> > ValuesAtScopes;
233 /// createSCEV - We know that there is no SCEV for the specified value.
234 /// Analyze the expression.
235 const SCEV *createSCEV(Value *V);
237 /// createNodeForPHI - Provide the special handling we need to analyze PHI
239 const SCEV *createNodeForPHI(PHINode *PN);
241 /// createNodeForGEP - Provide the special handling we need to analyze GEP
243 const SCEV *createNodeForGEP(User *GEP);
245 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
246 /// for the specified instruction and replaces any references to the
247 /// symbolic value SymName with the specified value. This is used during
249 void ReplaceSymbolicValueWithConcrete(Instruction *I,
253 /// getBECount - Subtract the end and start values and divide by the step,
254 /// rounding up, to get the number of times the backedge is executed. Return
255 /// CouldNotCompute if an intermediate computation overflows.
256 const SCEV *getBECount(const SCEV *Start,
260 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
261 /// loop, lazily computing new values if the loop hasn't been analyzed
263 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
265 /// ComputeBackedgeTakenCount - Compute the number of times the specified
266 /// loop will iterate.
267 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
269 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the
270 /// backedge of the specified loop will execute if it exits via the
272 BackedgeTakenInfo ComputeBackedgeTakenCountFromExit(const Loop *L,
273 BasicBlock *ExitingBlock);
275 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
276 /// backedge of the specified loop will execute if its exit condition
277 /// were a conditional branch of ExitCond, TBB, and FBB.
279 ComputeBackedgeTakenCountFromExitCond(const Loop *L,
284 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of
285 /// times the backedge of the specified loop will execute if its exit
286 /// condition were a conditional branch of the ICmpInst ExitCond, TBB,
289 ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
294 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
295 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
297 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
300 ICmpInst::Predicate p);
302 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
303 /// a constant number of times (the condition evolves only from constants),
304 /// try to evaluate a few iterations of the loop until we get the exit
305 /// condition gets a value of ExitWhen (true or false). If we cannot
306 /// evaluate the trip count of the loop, return CouldNotCompute.
307 const SCEV *ComputeBackedgeTakenCountExhaustively(const Loop *L,
311 /// HowFarToZero - Return the number of times a backedge comparing the
312 /// specified value to zero will execute. If not computable, return
314 const SCEV *HowFarToZero(const SCEV *V, const Loop *L);
316 /// HowFarToNonZero - Return the number of times a backedge checking the
317 /// specified value for nonzero will execute. If not computable, return
319 const SCEV *HowFarToNonZero(const SCEV *V, const Loop *L);
321 /// HowManyLessThans - Return the number of times a backedge containing the
322 /// specified less-than comparison will execute. If not computable, return
323 /// CouldNotCompute. isSigned specifies whether the less-than is signed.
324 BackedgeTakenInfo HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
325 const Loop *L, bool isSigned);
327 /// getLoopPredecessor - If the given loop's header has exactly one unique
328 /// predecessor outside the loop, return it. Otherwise return null.
329 BasicBlock *getLoopPredecessor(const Loop *L);
331 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
332 /// (which may not be an immediate predecessor) which has exactly one
333 /// successor from which BB is reachable, or null if no such block is
335 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
337 /// isNecessaryCond - Test whether the condition described by Pred, LHS,
338 /// and RHS is a necessary condition for the given Cond value to evaluate
340 bool isNecessaryCond(Value *Cond, ICmpInst::Predicate Pred,
341 const SCEV *LHS, const SCEV *RHS,
344 /// isNecessaryCondOperands - Test whether the condition described by Pred,
345 /// LHS, and RHS is a necessary condition for the condition described by
346 /// Pred, FoundLHS, and FoundRHS to evaluate to true.
347 bool isNecessaryCondOperands(ICmpInst::Predicate Pred,
348 const SCEV *LHS, const SCEV *RHS,
349 const SCEV *FoundLHS, const SCEV *FoundRHS);
351 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
352 /// in the header of its containing loop, we know the loop executes a
353 /// constant number of times, and the PHI node is just a recurrence
354 /// involving constants, fold it.
355 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
359 static char ID; // Pass identification, replacement for typeid
362 LLVMContext *getContext() const { return Context; }
364 /// isSCEVable - Test if values of the given type are analyzable within
365 /// the SCEV framework. This primarily includes integer types, and it
366 /// can optionally include pointer types if the ScalarEvolution class
367 /// has access to target-specific information.
368 bool isSCEVable(const Type *Ty) const;
370 /// getTypeSizeInBits - Return the size in bits of the specified type,
371 /// for which isSCEVable must return true.
372 uint64_t getTypeSizeInBits(const Type *Ty) const;
374 /// getEffectiveSCEVType - Return a type with the same bitwidth as
375 /// the given type and which represents how SCEV will treat the given
376 /// type, for which isSCEVable must return true. For pointer types,
377 /// this is the pointer-sized integer type.
378 const Type *getEffectiveSCEVType(const Type *Ty) const;
380 /// getSCEV - Return a SCEV expression handle for the full generality of the
381 /// specified expression.
382 const SCEV *getSCEV(Value *V);
384 const SCEV *getConstant(ConstantInt *V);
385 const SCEV *getConstant(const APInt& Val);
386 const SCEV *getConstant(const Type *Ty, uint64_t V, bool isSigned = false);
387 const SCEV *getTruncateExpr(const SCEV *Op, const Type *Ty);
388 const SCEV *getZeroExtendExpr(const SCEV *Op, const Type *Ty);
389 const SCEV *getSignExtendExpr(const SCEV *Op, const Type *Ty);
390 const SCEV *getAnyExtendExpr(const SCEV *Op, const Type *Ty);
391 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops);
392 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS) {
393 SmallVector<const SCEV *, 2> Ops;
396 return getAddExpr(Ops);
398 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1,
400 SmallVector<const SCEV *, 3> Ops;
404 return getAddExpr(Ops);
406 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops);
407 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS) {
408 SmallVector<const SCEV *, 2> Ops;
411 return getMulExpr(Ops);
413 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
414 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
416 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
418 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
420 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
421 return getAddRecExpr(NewOp, L);
423 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
424 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
425 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
426 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
427 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
428 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
429 const SCEV *getUnknown(Value *V);
430 const SCEV *getCouldNotCompute();
432 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
434 const SCEV *getNegativeSCEV(const SCEV *V);
436 /// getNotSCEV - Return the SCEV object corresponding to ~V.
438 const SCEV *getNotSCEV(const SCEV *V);
440 /// getMinusSCEV - Return LHS-RHS.
442 const SCEV *getMinusSCEV(const SCEV *LHS,
445 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
446 /// of the input value to the specified type. If the type must be
447 /// extended, it is zero extended.
448 const SCEV *getTruncateOrZeroExtend(const SCEV *V, const Type *Ty);
450 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
451 /// of the input value to the specified type. If the type must be
452 /// extended, it is sign extended.
453 const SCEV *getTruncateOrSignExtend(const SCEV *V, const Type *Ty);
455 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
456 /// the input value to the specified type. If the type must be extended,
457 /// it is zero extended. The conversion must not be narrowing.
458 const SCEV *getNoopOrZeroExtend(const SCEV *V, const Type *Ty);
460 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
461 /// the input value to the specified type. If the type must be extended,
462 /// it is sign extended. The conversion must not be narrowing.
463 const SCEV *getNoopOrSignExtend(const SCEV *V, const Type *Ty);
465 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
466 /// the input value to the specified type. If the type must be extended,
467 /// it is extended with unspecified bits. The conversion must not be
469 const SCEV *getNoopOrAnyExtend(const SCEV *V, const Type *Ty);
471 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
472 /// input value to the specified type. The conversion must not be
474 const SCEV *getTruncateOrNoop(const SCEV *V, const Type *Ty);
476 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
477 /// specified signed integer value and return a SCEV for the constant.
478 const SCEV *getIntegerSCEV(int Val, const Type *Ty);
480 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
481 /// the types using zero-extension, and then perform a umax operation
483 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
486 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
487 /// the types using zero-extension, and then perform a umin operation
489 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
492 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
493 /// at the specified scope in the program. The L value specifies a loop
494 /// nest to evaluate the expression at, where null is the top-level or a
495 /// specified loop is immediately inside of the loop.
497 /// This method can be used to compute the exit value for a variable defined
498 /// in a loop by querying what the value will hold in the parent loop.
500 /// In the case that a relevant loop exit value cannot be computed, the
501 /// original value V is returned.
502 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
504 /// getSCEVAtScope - This is a convenience function which does
505 /// getSCEVAtScope(getSCEV(V), L).
506 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
508 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
509 /// a conditional between LHS and RHS. This is used to help avoid max
510 /// expressions in loop trip counts, and to eliminate casts.
511 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
512 const SCEV *LHS, const SCEV *RHS);
514 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
515 /// protected by a conditional between LHS and RHS. This is used to
516 /// to eliminate casts.
517 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
518 const SCEV *LHS, const SCEV *RHS);
520 /// getBackedgeTakenCount - If the specified loop has a predictable
521 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
522 /// object. The backedge-taken count is the number of times the loop header
523 /// will be branched to from within the loop. This is one less than the
524 /// trip count of the loop, since it doesn't count the first iteration,
525 /// when the header is branched to from outside the loop.
527 /// Note that it is not valid to call this method on a loop without a
528 /// loop-invariant backedge-taken count (see
529 /// hasLoopInvariantBackedgeTakenCount).
531 const SCEV *getBackedgeTakenCount(const Loop *L);
533 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
534 /// return the least SCEV value that is known never to be less than the
535 /// actual backedge taken count.
536 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
538 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
539 /// has an analyzable loop-invariant backedge-taken count.
540 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
542 /// forgetLoopBackedgeTakenCount - This method should be called by the
543 /// client when it has changed a loop in a way that may effect
544 /// ScalarEvolution's ability to compute a trip count, or if the loop
546 void forgetLoopBackedgeTakenCount(const Loop *L);
548 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
549 /// is guaranteed to end in (at every loop iteration). It is, at the same
550 /// time, the minimum number of times S is divisible by 2. For example,
551 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
553 uint32_t GetMinTrailingZeros(const SCEV *S);
555 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
557 ConstantRange getUnsignedRange(const SCEV *S);
559 /// getSignedRange - Determine the signed range for a particular SCEV.
561 ConstantRange getSignedRange(const SCEV *S);
563 /// isKnownNegative - Test if the given expression is known to be negative.
565 bool isKnownNegative(const SCEV *S);
567 /// isKnownPositive - Test if the given expression is known to be positive.
569 bool isKnownPositive(const SCEV *S);
571 /// isKnownNonNegative - Test if the given expression is known to be
574 bool isKnownNonNegative(const SCEV *S);
576 /// isKnownNonPositive - Test if the given expression is known to be
579 bool isKnownNonPositive(const SCEV *S);
581 /// isKnownNonZero - Test if the given expression is known to be
584 bool isKnownNonZero(const SCEV *S);
586 /// isKnownNonZero - Test if the given expression is known to satisfy
587 /// the condition described by Pred, LHS, and RHS.
589 bool isKnownPredicate(ICmpInst::Predicate Pred,
590 const SCEV *LHS, const SCEV *RHS);
592 virtual bool runOnFunction(Function &F);
593 virtual void releaseMemory();
594 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
595 void print(raw_ostream &OS, const Module* = 0) const;
596 virtual void print(std::ostream &OS, const Module* = 0) const;
597 void print(std::ostream *OS, const Module* M = 0) const {
598 if (OS) print(*OS, M);
602 FoldingSet<SCEV> UniqueSCEVs;
603 BumpPtrAllocator SCEVAllocator;