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 /// replaceSymbolicValuesWithConcrete - If this SCEV internally references
81 /// the symbolic value "Sym", construct and return a new SCEV that produces
82 /// the same value, but which uses the concrete value Conc instead of the
83 /// symbolic value. If this SCEV does not use the symbolic value, it
86 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
87 const SCEVHandle &Conc,
88 ScalarEvolution &SE) const = 0;
90 /// dominates - Return true if elements that makes up this SCEV dominates
91 /// the specified basic block.
92 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const = 0;
94 /// print - Print out the internal representation of this scalar to the
95 /// specified stream. This should really only be used for debugging
97 virtual void print(raw_ostream &OS) const = 0;
98 void print(std::ostream &OS) const;
99 void print(std::ostream *OS) const { if (OS) print(*OS); }
101 /// dump - This method is used for debugging.
106 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
111 inline std::ostream &operator<<(std::ostream &OS, const SCEV &S) {
116 /// SCEVCouldNotCompute - An object of this class is returned by queries that
117 /// could not be answered. For example, if you ask for the number of
118 /// iterations of a linked-list traversal loop, you will get one of these.
119 /// None of the standard SCEV operations are valid on this class, it is just a
121 struct SCEVCouldNotCompute : public SCEV {
122 SCEVCouldNotCompute();
123 ~SCEVCouldNotCompute();
125 // None of these methods are valid for this object.
126 virtual bool isLoopInvariant(const Loop *L) const;
127 virtual const Type *getType() const;
128 virtual bool hasComputableLoopEvolution(const Loop *L) const;
129 virtual void print(raw_ostream &OS) const;
131 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
132 const SCEVHandle &Conc,
133 ScalarEvolution &SE) const;
135 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const {
139 /// Methods for support type inquiry through isa, cast, and dyn_cast:
140 static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
141 static bool classof(const SCEV *S);
144 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
145 /// notified whenever a Value is deleted.
146 class SCEVCallbackVH : public CallbackVH {
148 virtual void deleted();
149 virtual void allUsesReplacedWith(Value *New);
151 SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
154 /// SCEVHandle - This class is used to maintain the SCEV object's refcounts,
155 /// freeing the objects when the last reference is dropped.
158 SCEVHandle(); // DO NOT IMPLEMENT
160 SCEVHandle(const SCEV *s) : S(s) {
161 assert(S && "Cannot create a handle to a null SCEV!");
164 SCEVHandle(const SCEVHandle &RHS) : S(RHS.S) {
167 ~SCEVHandle() { S->dropRef(); }
169 operator const SCEV*() const { return S; }
171 const SCEV &operator*() const { return *S; }
172 const SCEV *operator->() const { return S; }
174 bool operator==(const SCEV *RHS) const { return S == RHS; }
175 bool operator!=(const SCEV *RHS) const { return S != RHS; }
177 const SCEVHandle &operator=(SCEV *RHS) {
186 const SCEVHandle &operator=(const SCEVHandle &RHS) {
196 template<typename From> struct simplify_type;
197 template<> struct simplify_type<const SCEVHandle> {
198 typedef const SCEV* SimpleType;
199 static SimpleType getSimplifiedValue(const SCEVHandle &Node) {
203 template<> struct simplify_type<SCEVHandle>
204 : public simplify_type<const SCEVHandle> {};
206 /// ScalarEvolution - This class is the main scalar evolution driver. Because
207 /// client code (intentionally) can't do much with the SCEV objects directly,
208 /// they must ask this class for services.
210 class ScalarEvolution : public FunctionPass {
211 friend class SCEVCallbackVH;
213 /// F - The function we are analyzing.
217 /// LI - The loop information for the function we are currently analyzing.
221 /// TD - The target data information for the target we are targetting.
225 /// UnknownValue - This SCEV is used to represent unknown trip counts and
227 SCEVHandle UnknownValue;
229 /// Scalars - This is a cache of the scalars we have analyzed so far.
231 std::map<SCEVCallbackVH, SCEVHandle> Scalars;
233 /// BackedgeTakenInfo - Information about the backedge-taken count
234 /// of a loop. This currently inclues an exact count and a maximum count.
236 struct BackedgeTakenInfo {
237 /// Exact - An expression indicating the exact backedge-taken count of
238 /// the loop if it is known, or a SCEVCouldNotCompute otherwise.
241 /// Exact - An expression indicating the least maximum backedge-taken
242 /// count of the loop that is known, or a SCEVCouldNotCompute.
245 /*implicit*/ BackedgeTakenInfo(SCEVHandle exact) :
246 Exact(exact), Max(exact) {}
248 /*implicit*/ BackedgeTakenInfo(const SCEV *exact) :
249 Exact(exact), Max(exact) {}
251 BackedgeTakenInfo(SCEVHandle exact, SCEVHandle max) :
252 Exact(exact), Max(max) {}
254 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
255 /// computed information, or whether it's all SCEVCouldNotCompute
257 bool hasAnyInfo() const {
258 return !isa<SCEVCouldNotCompute>(Exact) ||
259 !isa<SCEVCouldNotCompute>(Max);
263 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
264 /// this function as they are computed.
265 std::map<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
267 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
268 /// the PHI instructions that we attempt to compute constant evolutions for.
269 /// This allows us to avoid potentially expensive recomputation of these
270 /// properties. An instruction maps to null if we are unable to compute its
272 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
274 /// createSCEV - We know that there is no SCEV for the specified value.
275 /// Analyze the expression.
276 SCEVHandle createSCEV(Value *V);
278 /// createNodeForPHI - Provide the special handling we need to analyze PHI
280 SCEVHandle createNodeForPHI(PHINode *PN);
282 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
283 /// for the specified instruction and replaces any references to the
284 /// symbolic value SymName with the specified value. This is used during
286 void ReplaceSymbolicValueWithConcrete(Instruction *I,
287 const SCEVHandle &SymName,
288 const SCEVHandle &NewVal);
290 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
291 /// loop, lazily computing new values if the loop hasn't been analyzed
293 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
295 /// ComputeBackedgeTakenCount - Compute the number of times the specified
296 /// loop will iterate.
297 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
299 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
300 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
302 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
305 ICmpInst::Predicate p);
307 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
308 /// a constant number of times (the condition evolves only from constants),
309 /// try to evaluate a few iterations of the loop until we get the exit
310 /// condition gets a value of ExitWhen (true or false). If we cannot
311 /// evaluate the trip count of the loop, return UnknownValue.
312 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
315 /// HowFarToZero - Return the number of times a backedge comparing the
316 /// specified value to zero will execute. If not computable, return
318 SCEVHandle HowFarToZero(const SCEV *V, const Loop *L);
320 /// HowFarToNonZero - Return the number of times a backedge checking the
321 /// specified value for nonzero will execute. If not computable, return
323 SCEVHandle HowFarToNonZero(const SCEV *V, const Loop *L);
325 /// HowManyLessThans - Return the number of times a backedge containing the
326 /// specified less-than comparison will execute. If not computable, return
327 /// UnknownValue. isSigned specifies whether the less-than is signed.
328 BackedgeTakenInfo HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
329 const Loop *L, bool isSigned);
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 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
338 /// in the header of its containing loop, we know the loop executes a
339 /// constant number of times, and the PHI node is just a recurrence
340 /// involving constants, fold it.
341 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
344 /// getSCEVAtScope - Compute the value of the specified expression within
345 /// the indicated loop (which may be null to indicate in no loop). If the
346 /// expression cannot be evaluated, return UnknownValue itself.
347 SCEVHandle getSCEVAtScope(const SCEV *S, const Loop *L);
349 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
350 /// PHI nodes in the given loop. This is used when the trip count of
351 /// the loop may have changed.
352 void forgetLoopPHIs(const Loop *L);
355 static char ID; // Pass identification, replacement for typeid
358 /// isSCEVable - Test if values of the given type are analyzable within
359 /// the SCEV framework. This primarily includes integer types, and it
360 /// can optionally include pointer types if the ScalarEvolution class
361 /// has access to target-specific information.
362 bool isSCEVable(const Type *Ty) const;
364 /// getTypeSizeInBits - Return the size in bits of the specified type,
365 /// for which isSCEVable must return true.
366 uint64_t getTypeSizeInBits(const Type *Ty) const;
368 /// getEffectiveSCEVType - Return a type with the same bitwidth as
369 /// the given type and which represents how SCEV will treat the given
370 /// type, for which isSCEVable must return true. For pointer types,
371 /// this is the pointer-sized integer type.
372 const Type *getEffectiveSCEVType(const Type *Ty) const;
374 /// getSCEV - Return a SCEV expression handle for the full generality of the
375 /// specified expression.
376 SCEVHandle getSCEV(Value *V);
378 SCEVHandle getConstant(ConstantInt *V);
379 SCEVHandle getConstant(const APInt& Val);
380 SCEVHandle getTruncateExpr(const SCEVHandle &Op, const Type *Ty);
381 SCEVHandle getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty);
382 SCEVHandle getSignExtendExpr(const SCEVHandle &Op, const Type *Ty);
383 SCEVHandle getAddExpr(std::vector<SCEVHandle> &Ops);
384 SCEVHandle getAddExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
385 std::vector<SCEVHandle> Ops;
388 return getAddExpr(Ops);
390 SCEVHandle getAddExpr(const SCEVHandle &Op0, const SCEVHandle &Op1,
391 const SCEVHandle &Op2) {
392 std::vector<SCEVHandle> Ops;
396 return getAddExpr(Ops);
398 SCEVHandle getMulExpr(std::vector<SCEVHandle> &Ops);
399 SCEVHandle getMulExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
400 std::vector<SCEVHandle> Ops;
403 return getMulExpr(Ops);
405 SCEVHandle getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
406 SCEVHandle getAddRecExpr(const SCEVHandle &Start, const SCEVHandle &Step,
408 SCEVHandle getAddRecExpr(std::vector<SCEVHandle> &Operands,
410 SCEVHandle getAddRecExpr(const std::vector<SCEVHandle> &Operands,
412 std::vector<SCEVHandle> NewOp(Operands);
413 return getAddRecExpr(NewOp, L);
415 SCEVHandle getSMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
416 SCEVHandle getSMaxExpr(std::vector<SCEVHandle> Operands);
417 SCEVHandle getUMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
418 SCEVHandle getUMaxExpr(std::vector<SCEVHandle> Operands);
419 SCEVHandle getUnknown(Value *V);
420 SCEVHandle getCouldNotCompute();
422 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
424 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
426 /// getNotSCEV - Return the SCEV object corresponding to ~V.
428 SCEVHandle getNotSCEV(const SCEVHandle &V);
430 /// getMinusSCEV - Return LHS-RHS.
432 SCEVHandle getMinusSCEV(const SCEVHandle &LHS,
433 const SCEVHandle &RHS);
435 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
436 /// of the input value to the specified type. If the type must be
437 /// extended, it is zero extended.
438 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
440 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
441 /// of the input value to the specified type. If the type must be
442 /// extended, it is sign extended.
443 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
445 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
446 /// specified signed integer value and return a SCEV for the constant.
447 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
449 /// hasSCEV - Return true if the SCEV for this value has already been
451 bool hasSCEV(Value *V) const;
453 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
454 /// the specified value.
455 void setSCEV(Value *V, const SCEVHandle &H);
457 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
458 /// at the specified scope in the program. The L value specifies a loop
459 /// nest to evaluate the expression at, where null is the top-level or a
460 /// specified loop is immediately inside of the loop.
462 /// This method can be used to compute the exit value for a variable defined
463 /// in a loop by querying what the value will hold in the parent loop.
465 /// If this value is not computable at this scope, a SCEVCouldNotCompute
466 /// object is returned.
467 SCEVHandle getSCEVAtScope(Value *V, const Loop *L);
469 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
470 /// a conditional between LHS and RHS. This is used to help avoid max
471 /// expressions in loop trip counts.
472 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
473 const SCEV *LHS, const SCEV *RHS);
475 /// getBackedgeTakenCount - If the specified loop has a predictable
476 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
477 /// object. The backedge-taken count is the number of times the loop header
478 /// will be branched to from within the loop. This is one less than the
479 /// trip count of the loop, since it doesn't count the first iteration,
480 /// when the header is branched to from outside the loop.
482 /// Note that it is not valid to call this method on a loop without a
483 /// loop-invariant backedge-taken count (see
484 /// hasLoopInvariantBackedgeTakenCount).
486 SCEVHandle getBackedgeTakenCount(const Loop *L);
488 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
489 /// return the least SCEV value that is known never to be less than the
490 /// actual backedge taken count.
491 SCEVHandle getMaxBackedgeTakenCount(const Loop *L);
493 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
494 /// has an analyzable loop-invariant backedge-taken count.
495 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
497 /// forgetLoopBackedgeTakenCount - This method should be called by the
498 /// client when it has changed a loop in a way that may effect
499 /// ScalarEvolution's ability to compute a trip count, or if the loop
501 void forgetLoopBackedgeTakenCount(const Loop *L);
503 virtual bool runOnFunction(Function &F);
504 virtual void releaseMemory();
505 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
506 void print(raw_ostream &OS, const Module* = 0) const;
507 virtual void print(std::ostream &OS, const Module* = 0) const;
508 void print(std::ostream *OS, const Module* M = 0) const {
509 if (OS) print(*OS, M);