c0b84fb33459e8abef4cadacbb19fd513b2f9b59
[oota-llvm.git] / include / llvm / Analysis / ValueTracking.h
1 //===- llvm/Analysis/ValueTracking.h - Walk computations --------*- 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 // This file contains routines that help analyze properties that chains of
11 // computations have.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_ANALYSIS_VALUETRACKING_H
16 #define LLVM_ANALYSIS_VALUETRACKING_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/Support/DataTypes.h"
20
21 namespace llvm {
22   class Value;
23   class Instruction;
24   class APInt;
25   class DataLayout;
26   class StringRef;
27   class MDNode;
28   class AssumptionCache;
29   class DominatorTree;
30   class TargetLibraryInfo;
31   class LoopInfo;
32
33   /// Determine which bits of V are known to be either zero or one and return
34   /// them in the KnownZero/KnownOne bit sets.
35   ///
36   /// This function is defined on values with integer type, values with pointer
37   /// type, and vectors of integers.  In the case
38   /// where V is a vector, the known zero and known one values are the
39   /// same width as the vector element, and the bit is set only if it is true
40   /// for all of the elements in the vector.
41   void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
42                         const DataLayout &DL, unsigned Depth = 0,
43                         AssumptionCache *AC = nullptr,
44                         const Instruction *CxtI = nullptr,
45                         const DominatorTree *DT = nullptr);
46   /// Compute known bits from the range metadata.
47   /// \p KnownZero the set of bits that are known to be zero
48   void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
49                                          APInt &KnownZero);
50
51   /// ComputeSignBit - Determine whether the sign bit is known to be zero or
52   /// one.  Convenience wrapper around computeKnownBits.
53   void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
54                       const DataLayout &DL, unsigned Depth = 0,
55                       AssumptionCache *AC = nullptr,
56                       const Instruction *CxtI = nullptr,
57                       const DominatorTree *DT = nullptr);
58
59   /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have
60   /// exactly one bit set when defined. For vectors return true if every
61   /// element is known to be a power of two when defined.  Supports values with
62   /// integer or pointer type and vectors of integers.  If 'OrZero' is set then
63   /// returns true if the given value is either a power of two or zero.
64   bool isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL,
65                               bool OrZero = false, unsigned Depth = 0,
66                               AssumptionCache *AC = nullptr,
67                               const Instruction *CxtI = nullptr,
68                               const DominatorTree *DT = nullptr);
69
70   /// isKnownNonZero - Return true if the given value is known to be non-zero
71   /// when defined.  For vectors return true if every element is known to be
72   /// non-zero when defined.  Supports values with integer or pointer type and
73   /// vectors of integers.
74   bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth = 0,
75                       AssumptionCache *AC = nullptr,
76                       const Instruction *CxtI = nullptr,
77                       const DominatorTree *DT = nullptr);
78
79   /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
80   /// this predicate to simplify operations downstream.  Mask is known to be
81   /// zero for bits that V cannot have.
82   ///
83   /// This function is defined on values with integer type, values with pointer
84   /// type, and vectors of integers.  In the case
85   /// where V is a vector, the mask, known zero, and known one values are the
86   /// same width as the vector element, and the bit is set only if it is true
87   /// for all of the elements in the vector.
88   bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
89                          unsigned Depth = 0, AssumptionCache *AC = nullptr,
90                          const Instruction *CxtI = nullptr,
91                          const DominatorTree *DT = nullptr);
92
93   /// ComputeNumSignBits - Return the number of times the sign bit of the
94   /// register is replicated into the other bits.  We know that at least 1 bit
95   /// is always equal to the sign bit (itself), but other cases can give us
96   /// information.  For example, immediately after an "ashr X, 2", we know that
97   /// the top 3 bits are all equal to each other, so we return 3.
98   ///
99   /// 'Op' must have a scalar integer type.
100   ///
101   unsigned ComputeNumSignBits(Value *Op, const DataLayout &DL,
102                               unsigned Depth = 0, AssumptionCache *AC = nullptr,
103                               const Instruction *CxtI = nullptr,
104                               const DominatorTree *DT = nullptr);
105
106   /// ComputeMultiple - This function computes the integer multiple of Base that
107   /// equals V.  If successful, it returns true and returns the multiple in
108   /// Multiple.  If unsuccessful, it returns false.  Also, if V can be
109   /// simplified to an integer, then the simplified V is returned in Val.  Look
110   /// through sext only if LookThroughSExt=true.
111   bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
112                        bool LookThroughSExt = false,
113                        unsigned Depth = 0);
114
115   /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
116   /// value is never equal to -0.0.
117   ///
118   bool CannotBeNegativeZero(const Value *V, unsigned Depth = 0);
119
120   /// CannotBeOrderedLessThanZero - Return true if we can prove that the 
121   /// specified FP value is either a NaN or never less than 0.0.
122   ///
123   bool CannotBeOrderedLessThanZero(const Value *V, unsigned Depth = 0);
124
125   /// isBytewiseValue - If the specified value can be set by repeating the same
126   /// byte in memory, return the i8 value that it is represented with.  This is
127   /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
128   /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
129   /// byte store (e.g. i16 0x1234), return null.
130   Value *isBytewiseValue(Value *V);
131     
132   /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
133   /// the scalar value indexed is already around as a register, for example if
134   /// it were inserted directly into the aggregrate.
135   ///
136   /// If InsertBefore is not null, this function will duplicate (modified)
137   /// insertvalues when a part of a nested struct is extracted.
138   Value *FindInsertedValue(Value *V,
139                            ArrayRef<unsigned> idx_range,
140                            Instruction *InsertBefore = nullptr);
141
142   /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
143   /// it can be expressed as a base pointer plus a constant offset.  Return the
144   /// base and offset to the caller.
145   Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
146                                           const DataLayout &DL);
147   static inline const Value *
148   GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
149                                    const DataLayout &DL) {
150     return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
151                                             DL);
152   }
153   
154   /// getConstantStringInfo - This function computes the length of a
155   /// null-terminated C string pointed to by V.  If successful, it returns true
156   /// and returns the string in Str.  If unsuccessful, it returns false.  This
157   /// does not include the trailing nul character by default.  If TrimAtNul is
158   /// set to false, then this returns any trailing nul characters as well as any
159   /// other characters that come after it.
160   bool getConstantStringInfo(const Value *V, StringRef &Str,
161                              uint64_t Offset = 0, bool TrimAtNul = true);
162
163   /// GetStringLength - If we can compute the length of the string pointed to by
164   /// the specified pointer, return 'len+1'.  If we can't, return 0.
165   uint64_t GetStringLength(Value *V);
166
167   /// GetUnderlyingObject - This method strips off any GEP address adjustments
168   /// and pointer casts from the specified value, returning the original object
169   /// being addressed.  Note that the returned value has pointer type if the
170   /// specified value does.  If the MaxLookup value is non-zero, it limits the
171   /// number of instructions to be stripped off.
172   Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
173                              unsigned MaxLookup = 6);
174   static inline const Value *GetUnderlyingObject(const Value *V,
175                                                  const DataLayout &DL,
176                                                  unsigned MaxLookup = 6) {
177     return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
178   }
179
180   /// \brief This method is similar to GetUnderlyingObject except that it can
181   /// look through phi and select instructions and return multiple objects.
182   ///
183   /// If LoopInfo is passed, loop phis are further analyzed.  If a pointer
184   /// accesses different objects in each iteration, we don't look through the
185   /// phi node. E.g. consider this loop nest:
186   ///
187   ///   int **A;
188   ///   for (i)
189   ///     for (j) {
190   ///        A[i][j] = A[i-1][j] * B[j]
191   ///     }
192   ///
193   /// This is transformed by Load-PRE to stash away A[i] for the next iteration
194   /// of the outer loop:
195   ///
196   ///   Curr = A[0];          // Prev_0
197   ///   for (i: 1..N) {
198   ///     Prev = Curr;        // Prev = PHI (Prev_0, Curr)
199   ///     Curr = A[i];
200   ///     for (j: 0..N) {
201   ///        Curr[j] = Prev[j] * B[j]
202   ///     }
203   ///   }
204   ///
205   /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
206   /// should not assume that Curr and Prev share the same underlying object thus
207   /// it shouldn't look through the phi above.
208   void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
209                             const DataLayout &DL, LoopInfo *LI = nullptr,
210                             unsigned MaxLookup = 6);
211
212   /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
213   /// are lifetime markers.
214   bool onlyUsedByLifetimeMarkers(const Value *V);
215
216   /// isDereferenceablePointer - Return true if this is always a dereferenceable 
217   /// pointer.
218   ///
219   /// Test if this value is always a pointer to allocated and suitably aligned
220   /// memory for a simple load or store.
221   bool isDereferenceablePointer(const Value *V, const DataLayout &DL);
222   
223   /// isSafeToSpeculativelyExecute - Return true if the instruction does not
224   /// have any effects besides calculating the result and does not have
225   /// undefined behavior.
226   ///
227   /// This method never returns true for an instruction that returns true for
228   /// mayHaveSideEffects; however, this method also does some other checks in
229   /// addition. It checks for undefined behavior, like dividing by zero or
230   /// loading from an invalid pointer (but not for undefined results, like a
231   /// shift with a shift amount larger than the width of the result). It checks
232   /// for malloc and alloca because speculatively executing them might cause a
233   /// memory leak. It also returns false for instructions related to control
234   /// flow, specifically terminators and PHI nodes.
235   ///
236   /// This method only looks at the instruction itself and its operands, so if
237   /// this method returns true, it is safe to move the instruction as long as
238   /// the correct dominance relationships for the operands and users hold.
239   /// However, this method can return true for instructions that read memory;
240   /// for such instructions, moving them may change the resulting value.
241   bool isSafeToSpeculativelyExecute(const Value *V);
242
243   /// isKnownNonNull - Return true if this pointer couldn't possibly be null by
244   /// its definition.  This returns true for allocas, non-extern-weak globals
245   /// and byval arguments.
246   bool isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI = nullptr);
247
248   /// Return true if it is valid to use the assumptions provided by an
249   /// assume intrinsic, I, at the point in the control-flow identified by the
250   /// context instruction, CxtI.
251   bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
252                                const DominatorTree *DT = nullptr);
253
254   enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
255   OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
256                                                const DataLayout &DL,
257                                                AssumptionCache *AC,
258                                                const Instruction *CxtI,
259                                                const DominatorTree *DT);
260   OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
261                                                const DataLayout &DL,
262                                                AssumptionCache *AC,
263                                                const Instruction *CxtI,
264                                                const DominatorTree *DT);
265   
266   /// \brief Specific patterns of select instructions we can match.
267   enum SelectPatternFlavor {
268     SPF_UNKNOWN = 0,
269     SPF_SMIN,                   // Signed minimum
270     SPF_UMIN,                   // Unsigned minimum
271     SPF_SMAX,                   // Signed maximum
272     SPF_UMAX,                   // Unsigned maximum
273     SPF_ABS,                    // Absolute value
274     SPF_NABS                    // Negated absolute value
275   };
276   /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
277   /// and providing the out parameter results if we successfully match.
278   SelectPatternFlavor matchSelectPattern(Value *V, Value *&LHS, Value *&RHS);
279
280 } // end namespace llvm
281
282 #endif