258723dc4dbe8c082be53beef0f2005d312e6ca3
[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/IR/Instruction.h"
20 #include "llvm/Support/DataTypes.h"
21
22 namespace llvm {
23   class Value;
24   class Instruction;
25   class APInt;
26   class DataLayout;
27   class StringRef;
28   class MDNode;
29   class AssumptionCache;
30   class DominatorTree;
31   class TargetLibraryInfo;
32   class LoopInfo;
33   class Loop;
34
35   /// Determine which bits of V are known to be either zero or one and return
36   /// them in the KnownZero/KnownOne bit sets.
37   ///
38   /// This function is defined on values with integer type, values with pointer
39   /// type, and vectors of integers.  In the case
40   /// where V is a vector, the known zero and known one values are the
41   /// same width as the vector element, and the bit is set only if it is true
42   /// for all of the elements in the vector.
43   void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
44                         const DataLayout &DL, unsigned Depth = 0,
45                         AssumptionCache *AC = nullptr,
46                         const Instruction *CxtI = nullptr,
47                         const DominatorTree *DT = nullptr);
48   /// Compute known bits from the range metadata.
49   /// \p KnownZero the set of bits that are known to be zero
50   void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
51                                          APInt &KnownZero);
52   /// Return true if LHS and RHS have no common bits set.
53   bool haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
54                            AssumptionCache *AC = nullptr,
55                            const Instruction *CxtI = nullptr,
56                            const DominatorTree *DT = nullptr);
57
58   /// ComputeSignBit - Determine whether the sign bit is known to be zero or
59   /// one.  Convenience wrapper around computeKnownBits.
60   void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
61                       const DataLayout &DL, unsigned Depth = 0,
62                       AssumptionCache *AC = nullptr,
63                       const Instruction *CxtI = nullptr,
64                       const DominatorTree *DT = nullptr);
65
66   /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have
67   /// exactly one bit set when defined. For vectors return true if every
68   /// element is known to be a power of two when defined.  Supports values with
69   /// integer or pointer type and vectors of integers.  If 'OrZero' is set then
70   /// return true if the given value is either a power of two or zero.
71   bool isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL,
72                               bool OrZero = false, unsigned Depth = 0,
73                               AssumptionCache *AC = nullptr,
74                               const Instruction *CxtI = nullptr,
75                               const DominatorTree *DT = nullptr);
76
77   /// isKnownNonZero - Return true if the given value is known to be non-zero
78   /// when defined.  For vectors return true if every element is known to be
79   /// non-zero when defined.  Supports values with integer or pointer type and
80   /// vectors of integers.
81   bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth = 0,
82                       AssumptionCache *AC = nullptr,
83                       const Instruction *CxtI = nullptr,
84                       const DominatorTree *DT = nullptr);
85
86   /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
87   /// this predicate to simplify operations downstream.  Mask is known to be
88   /// zero for bits that V cannot have.
89   ///
90   /// This function is defined on values with integer type, values with pointer
91   /// type, and vectors of integers.  In the case
92   /// where V is a vector, the mask, known zero, and known one values are the
93   /// same width as the vector element, and the bit is set only if it is true
94   /// for all of the elements in the vector.
95   bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
96                          unsigned Depth = 0, AssumptionCache *AC = nullptr,
97                          const Instruction *CxtI = nullptr,
98                          const DominatorTree *DT = nullptr);
99
100   /// ComputeNumSignBits - Return the number of times the sign bit of the
101   /// register is replicated into the other bits.  We know that at least 1 bit
102   /// is always equal to the sign bit (itself), but other cases can give us
103   /// information.  For example, immediately after an "ashr X, 2", we know that
104   /// the top 3 bits are all equal to each other, so we return 3.
105   ///
106   /// 'Op' must have a scalar integer type.
107   ///
108   unsigned ComputeNumSignBits(Value *Op, const DataLayout &DL,
109                               unsigned Depth = 0, AssumptionCache *AC = nullptr,
110                               const Instruction *CxtI = nullptr,
111                               const DominatorTree *DT = nullptr);
112
113   /// ComputeMultiple - This function computes the integer multiple of Base that
114   /// equals V.  If successful, it returns true and returns the multiple in
115   /// Multiple.  If unsuccessful, it returns false.  Also, if V can be
116   /// simplified to an integer, then the simplified V is returned in Val.  Look
117   /// through sext only if LookThroughSExt=true.
118   bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
119                        bool LookThroughSExt = false,
120                        unsigned Depth = 0);
121
122   /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
123   /// value is never equal to -0.0.
124   ///
125   bool CannotBeNegativeZero(const Value *V, unsigned Depth = 0);
126
127   /// CannotBeOrderedLessThanZero - Return true if we can prove that the 
128   /// specified FP value is either a NaN or never less than 0.0.
129   ///
130   bool CannotBeOrderedLessThanZero(const Value *V, unsigned Depth = 0);
131
132   /// isBytewiseValue - If the specified value can be set by repeating the same
133   /// byte in memory, return the i8 value that it is represented with.  This is
134   /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
135   /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
136   /// byte store (e.g. i16 0x1234), return null.
137   Value *isBytewiseValue(Value *V);
138     
139   /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
140   /// the scalar value indexed is already around as a register, for example if
141   /// it were inserted directly into the aggregrate.
142   ///
143   /// If InsertBefore is not null, this function will duplicate (modified)
144   /// insertvalues when a part of a nested struct is extracted.
145   Value *FindInsertedValue(Value *V,
146                            ArrayRef<unsigned> idx_range,
147                            Instruction *InsertBefore = nullptr);
148
149   /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
150   /// it can be expressed as a base pointer plus a constant offset.  Return the
151   /// base and offset to the caller.
152   Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
153                                           const DataLayout &DL);
154   static inline const Value *
155   GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
156                                    const DataLayout &DL) {
157     return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
158                                             DL);
159   }
160   
161   /// getConstantStringInfo - This function computes the length of a
162   /// null-terminated C string pointed to by V.  If successful, it returns true
163   /// and returns the string in Str.  If unsuccessful, it returns false.  This
164   /// does not include the trailing nul character by default.  If TrimAtNul is
165   /// set to false, then this returns any trailing nul characters as well as any
166   /// other characters that come after it.
167   bool getConstantStringInfo(const Value *V, StringRef &Str,
168                              uint64_t Offset = 0, bool TrimAtNul = true);
169
170   /// GetStringLength - If we can compute the length of the string pointed to by
171   /// the specified pointer, return 'len+1'.  If we can't, return 0.
172   uint64_t GetStringLength(Value *V);
173
174   /// GetUnderlyingObject - This method strips off any GEP address adjustments
175   /// and pointer casts from the specified value, returning the original object
176   /// being addressed.  Note that the returned value has pointer type if the
177   /// specified value does.  If the MaxLookup value is non-zero, it limits the
178   /// number of instructions to be stripped off.
179   Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
180                              unsigned MaxLookup = 6);
181   static inline const Value *GetUnderlyingObject(const Value *V,
182                                                  const DataLayout &DL,
183                                                  unsigned MaxLookup = 6) {
184     return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
185   }
186
187   /// \brief This method is similar to GetUnderlyingObject except that it can
188   /// look through phi and select instructions and return multiple objects.
189   ///
190   /// If LoopInfo is passed, loop phis are further analyzed.  If a pointer
191   /// accesses different objects in each iteration, we don't look through the
192   /// phi node. E.g. consider this loop nest:
193   ///
194   ///   int **A;
195   ///   for (i)
196   ///     for (j) {
197   ///        A[i][j] = A[i-1][j] * B[j]
198   ///     }
199   ///
200   /// This is transformed by Load-PRE to stash away A[i] for the next iteration
201   /// of the outer loop:
202   ///
203   ///   Curr = A[0];          // Prev_0
204   ///   for (i: 1..N) {
205   ///     Prev = Curr;        // Prev = PHI (Prev_0, Curr)
206   ///     Curr = A[i];
207   ///     for (j: 0..N) {
208   ///        Curr[j] = Prev[j] * B[j]
209   ///     }
210   ///   }
211   ///
212   /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
213   /// should not assume that Curr and Prev share the same underlying object thus
214   /// it shouldn't look through the phi above.
215   void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
216                             const DataLayout &DL, LoopInfo *LI = nullptr,
217                             unsigned MaxLookup = 6);
218
219   /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
220   /// are lifetime markers.
221   bool onlyUsedByLifetimeMarkers(const Value *V);
222
223   /// isDereferenceablePointer - Return true if this is always a dereferenceable
224   /// pointer. If the context instruction is specified perform context-sensitive
225   /// analysis and return true if the pointer is dereferenceable at the
226   /// specified instruction.
227   bool isDereferenceablePointer(const Value *V, const DataLayout &DL,
228                                 const Instruction *CtxI = nullptr,
229                                 const DominatorTree *DT = nullptr,
230                                 const TargetLibraryInfo *TLI = nullptr);
231   
232   /// isSafeToSpeculativelyExecute - Return true if the instruction does not
233   /// have any effects besides calculating the result and does not have
234   /// undefined behavior.
235   ///
236   /// This method never returns true for an instruction that returns true for
237   /// mayHaveSideEffects; however, this method also does some other checks in
238   /// addition. It checks for undefined behavior, like dividing by zero or
239   /// loading from an invalid pointer (but not for undefined results, like a
240   /// shift with a shift amount larger than the width of the result). It checks
241   /// for malloc and alloca because speculatively executing them might cause a
242   /// memory leak. It also returns false for instructions related to control
243   /// flow, specifically terminators and PHI nodes.
244   ///
245   /// If the CtxI is specified this method performs context-sensitive analysis
246   /// and returns true if it is safe to execute the instruction immediately
247   /// before the CtxI.
248   ///
249   /// If the CtxI is NOT specified this method only looks at the instruction
250   /// itself and its operands, so if this method returns true, it is safe to
251   /// move the instruction as long as the correct dominance relationships for
252   /// the operands and users hold.
253   ///
254   /// This method can return true for instructions that read memory;
255   /// for such instructions, moving them may change the resulting value.
256   bool isSafeToSpeculativelyExecute(const Value *V,
257                                     const Instruction *CtxI = nullptr,
258                                     const DominatorTree *DT = nullptr,
259                                     const TargetLibraryInfo *TLI = nullptr);
260
261   /// isKnownNonNull - Return true if this pointer couldn't possibly be null by
262   /// its definition.  This returns true for allocas, non-extern-weak globals
263   /// and byval arguments.
264   bool isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI = nullptr);
265
266   /// isKnownNonNullAt - Return true if this pointer couldn't possibly be null.
267   /// If the context instruction is specified perform context-sensitive analysis
268   /// and return true if the pointer couldn't possibly be null at the specified
269   /// instruction.
270   bool isKnownNonNullAt(const Value *V,
271                         const Instruction *CtxI = nullptr,
272                         const DominatorTree *DT  = nullptr,
273                         const TargetLibraryInfo *TLI = nullptr);
274
275   /// Return true if it is valid to use the assumptions provided by an
276   /// assume intrinsic, I, at the point in the control-flow identified by the
277   /// context instruction, CxtI.
278   bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
279                                const DominatorTree *DT = nullptr);
280
281   enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
282   OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
283                                                const DataLayout &DL,
284                                                AssumptionCache *AC,
285                                                const Instruction *CxtI,
286                                                const DominatorTree *DT);
287   OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
288                                                const DataLayout &DL,
289                                                AssumptionCache *AC,
290                                                const Instruction *CxtI,
291                                                const DominatorTree *DT);
292
293   /// Return true if this function can prove that the instruction I will
294   /// always transfer execution to one of its successors (including the next
295   /// instruction that follows within a basic block). E.g. this is not
296   /// guaranteed for function calls that could loop infinitely.
297   ///
298   /// In other words, this function returns false for instructions that may
299   /// transfer execution or fail to transfer execution in a way that is not
300   /// captured in the CFG nor in the sequence of instructions within a basic
301   /// block.
302   ///
303   /// Undefined behavior is assumed not to happen, so e.g. division is
304   /// guaranteed to transfer execution to the following instruction even
305   /// though division by zero might cause undefined behavior.
306   bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
307
308   /// Return true if this function can prove that the instruction I
309   /// is executed for every iteration of the loop L.
310   ///
311   /// Note that this currently only considers the loop header.
312   bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
313                                               const Loop *L);
314
315   /// Return true if this function can prove that I is guaranteed to yield
316   /// full-poison (all bits poison) if at least one of its operands are
317   /// full-poison (all bits poison).
318   ///
319   /// The exact rules for how poison propagates through instructions have
320   /// not been settled as of 2015-07-10, so this function is conservative
321   /// and only considers poison to be propagated in uncontroversial
322   /// cases. There is no attempt to track values that may be only partially
323   /// poison.
324   bool propagatesFullPoison(const Instruction *I);
325
326   /// Return either nullptr or an operand of I such that I will trigger
327   /// undefined behavior if I is executed and that operand has a full-poison
328   /// value (all bits poison).
329   const Value *getGuaranteedNonFullPoisonOp(const Instruction *I);
330
331   /// Return true if this function can prove that if PoisonI is executed
332   /// and yields a full-poison value (all bits poison), then that will
333   /// trigger undefined behavior.
334   ///
335   /// Note that this currently only considers the basic block that is
336   /// the parent of I.
337   bool isKnownNotFullPoison(const Instruction *PoisonI);
338
339   /// \brief Specific patterns of select instructions we can match.
340   enum SelectPatternFlavor {
341     SPF_UNKNOWN = 0,
342     SPF_SMIN,                   // Signed minimum
343     SPF_UMIN,                   // Unsigned minimum
344     SPF_SMAX,                   // Signed maximum
345     SPF_UMAX,                   // Unsigned maximum
346     SPF_ABS,                    // Absolute value
347     SPF_NABS                    // Negated absolute value
348   };
349   /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
350   /// and providing the out parameter results if we successfully match.
351   ///
352   /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
353   /// not match that of the original select. If this is the case, the cast
354   /// operation (one of Trunc,SExt,Zext) that must be done to transform the
355   /// type of LHS and RHS into the type of V is returned in CastOp.
356   ///
357   /// For example:
358   ///   %1 = icmp slt i32 %a, i32 4
359   ///   %2 = sext i32 %a to i64
360   ///   %3 = select i1 %1, i64 %2, i64 4
361   ///
362   /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
363   ///
364   SelectPatternFlavor matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
365                                          Instruction::CastOps *CastOp = nullptr);
366
367 } // end namespace llvm
368
369 #endif