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