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"
35 class ScalarEvolution;
38 /// SCEV - This class represent an analyzed expression in the program. These
39 /// are reference counted opaque objects that the client is not allowed to
40 /// do much with directly.
43 const unsigned SCEVType; // The SCEV baseclass this node corresponds to
44 mutable unsigned RefCount;
46 friend class SCEVHandle;
47 void addRef() const { ++RefCount; }
48 void dropRef() const {
53 SCEV(const SCEV &); // DO NOT IMPLEMENT
54 void operator=(const SCEV &); // DO NOT IMPLEMENT
58 explicit SCEV(unsigned SCEVTy) : SCEVType(SCEVTy), RefCount(0) {}
60 unsigned getSCEVType() const { return SCEVType; }
62 /// isLoopInvariant - Return true if the value of this SCEV is unchanging in
63 /// the specified loop.
64 virtual bool isLoopInvariant(const Loop *L) const = 0;
66 /// hasComputableLoopEvolution - Return true if this SCEV changes value in a
67 /// known way in the specified loop. This property being true implies that
68 /// the value is variant in the loop AND that we can emit an expression to
69 /// compute the value of the expression at any particular loop iteration.
70 virtual bool hasComputableLoopEvolution(const Loop *L) const = 0;
72 /// getType - Return the LLVM type of this SCEV expression.
74 virtual const Type *getType() const = 0;
76 /// isZero - Return true if the expression is a constant zero.
80 /// isOne - Return true if the expression is a constant one.
84 /// replaceSymbolicValuesWithConcrete - If this SCEV internally references
85 /// the symbolic value "Sym", construct and return a new SCEV that produces
86 /// the same value, but which uses the concrete value Conc instead of the
87 /// symbolic value. If this SCEV does not use the symbolic value, it
90 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
91 const SCEVHandle &Conc,
92 ScalarEvolution &SE) const = 0;
94 /// dominates - Return true if elements that makes up this SCEV dominates
95 /// the specified basic block.
96 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const = 0;
98 /// print - Print out the internal representation of this scalar to the
99 /// specified stream. This should really only be used for debugging
101 virtual void print(raw_ostream &OS) const = 0;
102 void print(std::ostream &OS) const;
103 void print(std::ostream *OS) const { if (OS) print(*OS); }
105 /// dump - This method is used for debugging.
110 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
115 inline std::ostream &operator<<(std::ostream &OS, const SCEV &S) {
120 /// SCEVCouldNotCompute - An object of this class is returned by queries that
121 /// could not be answered. For example, if you ask for the number of
122 /// iterations of a linked-list traversal loop, you will get one of these.
123 /// None of the standard SCEV operations are valid on this class, it is just a
125 struct SCEVCouldNotCompute : public SCEV {
126 SCEVCouldNotCompute();
127 ~SCEVCouldNotCompute();
129 // None of these methods are valid for this object.
130 virtual bool isLoopInvariant(const Loop *L) const;
131 virtual const Type *getType() const;
132 virtual bool hasComputableLoopEvolution(const Loop *L) const;
133 virtual void print(raw_ostream &OS) const;
135 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
136 const SCEVHandle &Conc,
137 ScalarEvolution &SE) const;
139 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const {
143 /// Methods for support type inquiry through isa, cast, and dyn_cast:
144 static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
145 static bool classof(const SCEV *S);
148 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
149 /// notified whenever a Value is deleted.
150 class SCEVCallbackVH : public CallbackVH {
152 virtual void deleted();
153 virtual void allUsesReplacedWith(Value *New);
155 SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
158 /// SCEVHandle - This class is used to maintain the SCEV object's refcounts,
159 /// freeing the objects when the last reference is dropped.
162 SCEVHandle(); // DO NOT IMPLEMENT
164 SCEVHandle(const SCEV *s) : S(s) {
165 assert(S && "Cannot create a handle to a null SCEV!");
168 SCEVHandle(const SCEVHandle &RHS) : S(RHS.S) {
171 ~SCEVHandle() { S->dropRef(); }
173 operator const SCEV*() const { return S; }
175 const SCEV &operator*() const { return *S; }
176 const SCEV *operator->() const { return S; }
178 bool operator==(const SCEV *RHS) const { return S == RHS; }
179 bool operator!=(const SCEV *RHS) const { return S != RHS; }
181 const SCEVHandle &operator=(SCEV *RHS) {
190 const SCEVHandle &operator=(const SCEVHandle &RHS) {
200 template<typename From> struct simplify_type;
201 template<> struct simplify_type<const SCEVHandle> {
202 typedef const SCEV* SimpleType;
203 static SimpleType getSimplifiedValue(const SCEVHandle &Node) {
207 template<> struct simplify_type<SCEVHandle>
208 : public simplify_type<const SCEVHandle> {};
210 /// ScalarEvolution - This class is the main scalar evolution driver. Because
211 /// client code (intentionally) can't do much with the SCEV objects directly,
212 /// they must ask this class for services.
214 class ScalarEvolution : public FunctionPass {
215 friend class SCEVCallbackVH;
217 /// F - The function we are analyzing.
221 /// LI - The loop information for the function we are currently analyzing.
225 /// TD - The target data information for the target we are targetting.
229 /// UnknownValue - This SCEV is used to represent unknown trip counts and
231 SCEVHandle UnknownValue;
233 /// Scalars - This is a cache of the scalars we have analyzed so far.
235 std::map<SCEVCallbackVH, SCEVHandle> Scalars;
237 /// BackedgeTakenInfo - Information about the backedge-taken count
238 /// of a loop. This currently inclues an exact count and a maximum count.
240 struct BackedgeTakenInfo {
241 /// Exact - An expression indicating the exact backedge-taken count of
242 /// the loop if it is known, or a SCEVCouldNotCompute otherwise.
245 /// Exact - An expression indicating the least maximum backedge-taken
246 /// count of the loop that is known, or a SCEVCouldNotCompute.
249 /*implicit*/ BackedgeTakenInfo(SCEVHandle exact) :
250 Exact(exact), Max(exact) {}
252 /*implicit*/ BackedgeTakenInfo(const SCEV *exact) :
253 Exact(exact), Max(exact) {}
255 BackedgeTakenInfo(SCEVHandle exact, SCEVHandle max) :
256 Exact(exact), Max(max) {}
258 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
259 /// computed information, or whether it's all SCEVCouldNotCompute
261 bool hasAnyInfo() const {
262 return !isa<SCEVCouldNotCompute>(Exact) ||
263 !isa<SCEVCouldNotCompute>(Max);
267 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
268 /// this function as they are computed.
269 std::map<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
271 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
272 /// the PHI instructions that we attempt to compute constant evolutions for.
273 /// This allows us to avoid potentially expensive recomputation of these
274 /// properties. An instruction maps to null if we are unable to compute its
276 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
278 /// ValuesAtScopes - This map contains entries for all the instructions
279 /// that we attempt to compute getSCEVAtScope information for without
280 /// using SCEV techniques, which can be expensive.
281 std::map<Instruction *, std::map<const Loop *, Constant *> > ValuesAtScopes;
283 /// createSCEV - We know that there is no SCEV for the specified value.
284 /// Analyze the expression.
285 SCEVHandle createSCEV(Value *V);
287 /// createNodeForPHI - Provide the special handling we need to analyze PHI
289 SCEVHandle createNodeForPHI(PHINode *PN);
291 /// createNodeForGEP - Provide the special handling we need to analyze GEP
293 SCEVHandle createNodeForGEP(User *GEP);
295 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
296 /// for the specified instruction and replaces any references to the
297 /// symbolic value SymName with the specified value. This is used during
299 void ReplaceSymbolicValueWithConcrete(Instruction *I,
300 const SCEVHandle &SymName,
301 const SCEVHandle &NewVal);
303 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
304 /// loop, lazily computing new values if the loop hasn't been analyzed
306 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
308 /// ComputeBackedgeTakenCount - Compute the number of times the specified
309 /// loop will iterate.
310 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
312 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
313 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
315 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
318 ICmpInst::Predicate p);
320 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
321 /// a constant number of times (the condition evolves only from constants),
322 /// try to evaluate a few iterations of the loop until we get the exit
323 /// condition gets a value of ExitWhen (true or false). If we cannot
324 /// evaluate the trip count of the loop, return UnknownValue.
325 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
328 /// HowFarToZero - Return the number of times a backedge comparing the
329 /// specified value to zero will execute. If not computable, return
331 SCEVHandle HowFarToZero(const SCEV *V, const Loop *L);
333 /// HowFarToNonZero - Return the number of times a backedge checking the
334 /// specified value for nonzero will execute. If not computable, return
336 SCEVHandle HowFarToNonZero(const SCEV *V, const Loop *L);
338 /// HowManyLessThans - Return the number of times a backedge containing the
339 /// specified less-than comparison will execute. If not computable, return
340 /// UnknownValue. isSigned specifies whether the less-than is signed.
341 BackedgeTakenInfo HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
342 const Loop *L, bool isSigned);
344 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
345 /// (which may not be an immediate predecessor) which has exactly one
346 /// successor from which BB is reachable, or null if no such block is
348 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
350 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
351 /// in the header of its containing loop, we know the loop executes a
352 /// constant number of times, and the PHI node is just a recurrence
353 /// involving constants, fold it.
354 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
357 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
358 /// PHI nodes in the given loop. This is used when the trip count of
359 /// the loop may have changed.
360 void forgetLoopPHIs(const Loop *L);
363 static char ID; // Pass identification, replacement for typeid
366 /// isSCEVable - Test if values of the given type are analyzable within
367 /// the SCEV framework. This primarily includes integer types, and it
368 /// can optionally include pointer types if the ScalarEvolution class
369 /// has access to target-specific information.
370 bool isSCEVable(const Type *Ty) const;
372 /// getTypeSizeInBits - Return the size in bits of the specified type,
373 /// for which isSCEVable must return true.
374 uint64_t getTypeSizeInBits(const Type *Ty) const;
376 /// getEffectiveSCEVType - Return a type with the same bitwidth as
377 /// the given type and which represents how SCEV will treat the given
378 /// type, for which isSCEVable must return true. For pointer types,
379 /// this is the pointer-sized integer type.
380 const Type *getEffectiveSCEVType(const Type *Ty) const;
382 /// getSCEV - Return a SCEV expression handle for the full generality of the
383 /// specified expression.
384 SCEVHandle getSCEV(Value *V);
386 SCEVHandle getConstant(ConstantInt *V);
387 SCEVHandle getConstant(const APInt& Val);
388 SCEVHandle getTruncateExpr(const SCEVHandle &Op, const Type *Ty);
389 SCEVHandle getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty);
390 SCEVHandle getSignExtendExpr(const SCEVHandle &Op, const Type *Ty);
391 SCEVHandle getAddExpr(std::vector<SCEVHandle> &Ops);
392 SCEVHandle getAddExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
393 std::vector<SCEVHandle> Ops;
396 return getAddExpr(Ops);
398 SCEVHandle getAddExpr(const SCEVHandle &Op0, const SCEVHandle &Op1,
399 const SCEVHandle &Op2) {
400 std::vector<SCEVHandle> Ops;
404 return getAddExpr(Ops);
406 SCEVHandle getMulExpr(std::vector<SCEVHandle> &Ops);
407 SCEVHandle getMulExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
408 std::vector<SCEVHandle> Ops;
411 return getMulExpr(Ops);
413 SCEVHandle getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
414 SCEVHandle getAddRecExpr(const SCEVHandle &Start, const SCEVHandle &Step,
416 SCEVHandle getAddRecExpr(std::vector<SCEVHandle> &Operands,
418 SCEVHandle getAddRecExpr(const std::vector<SCEVHandle> &Operands,
420 std::vector<SCEVHandle> NewOp(Operands);
421 return getAddRecExpr(NewOp, L);
423 SCEVHandle getSMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
424 SCEVHandle getSMaxExpr(std::vector<SCEVHandle> Operands);
425 SCEVHandle getUMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
426 SCEVHandle getUMaxExpr(std::vector<SCEVHandle> Operands);
427 SCEVHandle getUnknown(Value *V);
428 SCEVHandle getCouldNotCompute();
430 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
432 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
434 /// getNotSCEV - Return the SCEV object corresponding to ~V.
436 SCEVHandle getNotSCEV(const SCEVHandle &V);
438 /// getMinusSCEV - Return LHS-RHS.
440 SCEVHandle getMinusSCEV(const SCEVHandle &LHS,
441 const SCEVHandle &RHS);
443 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
444 /// of the input value to the specified type. If the type must be
445 /// extended, it is zero extended.
446 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
448 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
449 /// of the input value to the specified type. If the type must be
450 /// extended, it is sign extended.
451 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
453 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
454 /// the input value to the specified type. If the type must be extended,
455 /// it is zero extended. The conversion must not be narrowing.
456 SCEVHandle getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty);
458 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
459 /// the input value to the specified type. If the type must be extended,
460 /// it is sign extended. The conversion must not be narrowing.
461 SCEVHandle getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty);
463 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
464 /// input value to the specified type. The conversion must not be
466 SCEVHandle getTruncateOrNoop(const SCEVHandle &V, const Type *Ty);
468 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
469 /// specified signed integer value and return a SCEV for the constant.
470 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
472 /// hasSCEV - Return true if the SCEV for this value has already been
474 bool hasSCEV(Value *V) const;
476 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
477 /// the specified value.
478 void setSCEV(Value *V, const SCEVHandle &H);
480 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
481 /// at the specified scope in the program. The L value specifies a loop
482 /// nest to evaluate the expression at, where null is the top-level or a
483 /// specified loop is immediately inside of the loop.
485 /// This method can be used to compute the exit value for a variable defined
486 /// in a loop by querying what the value will hold in the parent loop.
488 /// If this value is not computable at this scope, a SCEVCouldNotCompute
489 /// object is returned.
490 SCEVHandle getSCEVAtScope(const SCEV *S, const Loop *L);
492 /// getSCEVAtScope - This is a convenience function which does
493 /// getSCEVAtScope(getSCEV(V), L).
494 SCEVHandle getSCEVAtScope(Value *V, const Loop *L);
496 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
497 /// a conditional between LHS and RHS. This is used to help avoid max
498 /// expressions in loop trip counts.
499 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
500 const SCEV *LHS, const SCEV *RHS);
502 /// getBackedgeTakenCount - If the specified loop has a predictable
503 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
504 /// object. The backedge-taken count is the number of times the loop header
505 /// will be branched to from within the loop. This is one less than the
506 /// trip count of the loop, since it doesn't count the first iteration,
507 /// when the header is branched to from outside the loop.
509 /// Note that it is not valid to call this method on a loop without a
510 /// loop-invariant backedge-taken count (see
511 /// hasLoopInvariantBackedgeTakenCount).
513 SCEVHandle getBackedgeTakenCount(const Loop *L);
515 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
516 /// return the least SCEV value that is known never to be less than the
517 /// actual backedge taken count.
518 SCEVHandle getMaxBackedgeTakenCount(const Loop *L);
520 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
521 /// has an analyzable loop-invariant backedge-taken count.
522 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
524 /// forgetLoopBackedgeTakenCount - This method should be called by the
525 /// client when it has changed a loop in a way that may effect
526 /// ScalarEvolution's ability to compute a trip count, or if the loop
528 void forgetLoopBackedgeTakenCount(const Loop *L);
530 virtual bool runOnFunction(Function &F);
531 virtual void releaseMemory();
532 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
533 void print(raw_ostream &OS, const Module* = 0) const;
534 virtual void print(std::ostream &OS, const Module* = 0) const;
535 void print(std::ostream *OS, const Module* M = 0) const {
536 if (OS) print(*OS, M);