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