]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/ValueTracking.h
Import Amazon Elastic Network Adapter (ENA) HAL to sys/contrib/
[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   /// If \p IncludeNeg0 is false, -0.0 is considered less than 0.0.
173   bool CannotBeOrderedLessThanZero(const Value *V, const TargetLibraryInfo *TLI);
174
175   /// \returns true if we can prove that the specified FP value has a 0 sign
176   /// bit.
177   bool SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI);
178
179   /// If the specified value can be set by repeating the same byte in memory,
180   /// return the i8 value that it is represented with. This is true for all i8
181   /// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
182   /// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
183   /// i16 0x1234), return null.
184   Value *isBytewiseValue(Value *V);
185
186   /// Given an aggregrate and an sequence of indices, see if the scalar value
187   /// indexed is already around as a register, for example if it were inserted
188   /// directly into the aggregrate.
189   ///
190   /// If InsertBefore is not null, this function will duplicate (modified)
191   /// insertvalues when a part of a nested struct is extracted.
192   Value *FindInsertedValue(Value *V,
193                            ArrayRef<unsigned> idx_range,
194                            Instruction *InsertBefore = nullptr);
195
196   /// Analyze the specified pointer to see if it can be expressed as a base
197   /// pointer plus a constant offset. Return the base and offset to the caller.
198   Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
199                                           const DataLayout &DL);
200   static inline const Value *
201   GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
202                                    const DataLayout &DL) {
203     return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
204                                             DL);
205   }
206
207   /// Returns true if the GEP is based on a pointer to a string (array of i8), 
208   /// and is indexing into this string.
209   bool isGEPBasedOnPointerToString(const GEPOperator *GEP);
210
211   /// This function computes the length of a null-terminated C string pointed to
212   /// by V. If successful, it returns true and returns the string in Str. If
213   /// unsuccessful, it returns false. This does not include the trailing null
214   /// character by default. If TrimAtNul is set to false, then this returns any
215   /// trailing null characters as well as any other characters that come after
216   /// it.
217   bool getConstantStringInfo(const Value *V, StringRef &Str,
218                              uint64_t Offset = 0, bool TrimAtNul = true);
219
220   /// If we can compute the length of the string pointed to by the specified
221   /// pointer, return 'len+1'.  If we can't, return 0.
222   uint64_t GetStringLength(const Value *V);
223
224   /// This method strips off any GEP address adjustments and pointer casts from
225   /// the specified value, returning the original object being addressed. Note
226   /// that the returned value has pointer type if the specified value does. If
227   /// the MaxLookup value is non-zero, it limits the number of instructions to
228   /// be stripped off.
229   Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
230                              unsigned MaxLookup = 6);
231   static inline const Value *GetUnderlyingObject(const Value *V,
232                                                  const DataLayout &DL,
233                                                  unsigned MaxLookup = 6) {
234     return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
235   }
236
237   /// \brief This method is similar to GetUnderlyingObject except that it can
238   /// look through phi and select instructions and return multiple objects.
239   ///
240   /// If LoopInfo is passed, loop phis are further analyzed.  If a pointer
241   /// accesses different objects in each iteration, we don't look through the
242   /// phi node. E.g. consider this loop nest:
243   ///
244   ///   int **A;
245   ///   for (i)
246   ///     for (j) {
247   ///        A[i][j] = A[i-1][j] * B[j]
248   ///     }
249   ///
250   /// This is transformed by Load-PRE to stash away A[i] for the next iteration
251   /// of the outer loop:
252   ///
253   ///   Curr = A[0];          // Prev_0
254   ///   for (i: 1..N) {
255   ///     Prev = Curr;        // Prev = PHI (Prev_0, Curr)
256   ///     Curr = A[i];
257   ///     for (j: 0..N) {
258   ///        Curr[j] = Prev[j] * B[j]
259   ///     }
260   ///   }
261   ///
262   /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
263   /// should not assume that Curr and Prev share the same underlying object thus
264   /// it shouldn't look through the phi above.
265   void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
266                             const DataLayout &DL, LoopInfo *LI = nullptr,
267                             unsigned MaxLookup = 6);
268
269   /// Return true if the only users of this pointer are lifetime markers.
270   bool onlyUsedByLifetimeMarkers(const Value *V);
271
272   /// Return true if the instruction does not have any effects besides
273   /// calculating the result and does not have undefined behavior.
274   ///
275   /// This method never returns true for an instruction that returns true for
276   /// mayHaveSideEffects; however, this method also does some other checks in
277   /// addition. It checks for undefined behavior, like dividing by zero or
278   /// loading from an invalid pointer (but not for undefined results, like a
279   /// shift with a shift amount larger than the width of the result). It checks
280   /// for malloc and alloca because speculatively executing them might cause a
281   /// memory leak. It also returns false for instructions related to control
282   /// flow, specifically terminators and PHI nodes.
283   ///
284   /// If the CtxI is specified this method performs context-sensitive analysis
285   /// and returns true if it is safe to execute the instruction immediately
286   /// before the CtxI.
287   ///
288   /// If the CtxI is NOT specified this method only looks at the instruction
289   /// itself and its operands, so if this method returns true, it is safe to
290   /// move the instruction as long as the correct dominance relationships for
291   /// the operands and users hold.
292   ///
293   /// This method can return true for instructions that read memory;
294   /// for such instructions, moving them may change the resulting value.
295   bool isSafeToSpeculativelyExecute(const Value *V,
296                                     const Instruction *CtxI = nullptr,
297                                     const DominatorTree *DT = nullptr);
298
299   /// Returns true if the result or effects of the given instructions \p I
300   /// depend on or influence global memory.
301   /// Memory dependence arises for example if the instruction reads from
302   /// memory or may produce effects or undefined behaviour. Memory dependent
303   /// instructions generally cannot be reorderd with respect to other memory
304   /// dependent instructions or moved into non-dominated basic blocks.
305   /// Instructions which just compute a value based on the values of their
306   /// operands are not memory dependent.
307   bool mayBeMemoryDependent(const Instruction &I);
308
309   /// Return true if this pointer couldn't possibly be null by its definition.
310   /// This returns true for allocas, non-extern-weak globals, and byval
311   /// arguments.
312   bool isKnownNonNull(const Value *V);
313
314   /// Return true if this pointer couldn't possibly be null. If the context
315   /// instruction and dominator tree are specified, perform context-sensitive
316   /// analysis and return true if the pointer couldn't possibly be null at the
317   /// specified instruction.
318   bool isKnownNonNullAt(const Value *V,
319                         const Instruction *CtxI = nullptr,
320                         const DominatorTree *DT = nullptr);
321
322   /// Return true if it is valid to use the assumptions provided by an
323   /// assume intrinsic, I, at the point in the control-flow identified by the
324   /// context instruction, CxtI.
325   bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
326                                const DominatorTree *DT = nullptr);
327
328   enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
329   OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
330                                                const Value *RHS,
331                                                const DataLayout &DL,
332                                                AssumptionCache *AC,
333                                                const Instruction *CxtI,
334                                                const DominatorTree *DT);
335   OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
336                                                const Value *RHS,
337                                                const DataLayout &DL,
338                                                AssumptionCache *AC,
339                                                const Instruction *CxtI,
340                                                const DominatorTree *DT);
341   OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS,
342                                              const DataLayout &DL,
343                                              AssumptionCache *AC = nullptr,
344                                              const Instruction *CxtI = nullptr,
345                                              const DominatorTree *DT = nullptr);
346   /// This version also leverages the sign bit of Add if known.
347   OverflowResult computeOverflowForSignedAdd(const AddOperator *Add,
348                                              const DataLayout &DL,
349                                              AssumptionCache *AC = nullptr,
350                                              const Instruction *CxtI = nullptr,
351                                              const DominatorTree *DT = nullptr);
352
353   /// Returns true if the arithmetic part of the \p II 's result is
354   /// used only along the paths control dependent on the computation
355   /// not overflowing, \p II being an <op>.with.overflow intrinsic.
356   bool isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
357                                  const DominatorTree &DT);
358
359   /// Return true if this function can prove that the instruction I will
360   /// always transfer execution to one of its successors (including the next
361   /// instruction that follows within a basic block). E.g. this is not
362   /// guaranteed for function calls that could loop infinitely.
363   ///
364   /// In other words, this function returns false for instructions that may
365   /// transfer execution or fail to transfer execution in a way that is not
366   /// captured in the CFG nor in the sequence of instructions within a basic
367   /// block.
368   ///
369   /// Undefined behavior is assumed not to happen, so e.g. division is
370   /// guaranteed to transfer execution to the following instruction even
371   /// though division by zero might cause undefined behavior.
372   bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
373
374   /// Return true if this function can prove that the instruction I
375   /// is executed for every iteration of the loop L.
376   ///
377   /// Note that this currently only considers the loop header.
378   bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
379                                               const Loop *L);
380
381   /// Return true if this function can prove that I is guaranteed to yield
382   /// full-poison (all bits poison) if at least one of its operands are
383   /// full-poison (all bits poison).
384   ///
385   /// The exact rules for how poison propagates through instructions have
386   /// not been settled as of 2015-07-10, so this function is conservative
387   /// and only considers poison to be propagated in uncontroversial
388   /// cases. There is no attempt to track values that may be only partially
389   /// poison.
390   bool propagatesFullPoison(const Instruction *I);
391
392   /// Return either nullptr or an operand of I such that I will trigger
393   /// undefined behavior if I is executed and that operand has a full-poison
394   /// value (all bits poison).
395   const Value *getGuaranteedNonFullPoisonOp(const Instruction *I);
396
397   /// Return true if this function can prove that if PoisonI is executed
398   /// and yields a full-poison value (all bits poison), then that will
399   /// trigger undefined behavior.
400   ///
401   /// Note that this currently only considers the basic block that is
402   /// the parent of I.
403   bool isKnownNotFullPoison(const Instruction *PoisonI);
404
405   /// \brief Specific patterns of select instructions we can match.
406   enum SelectPatternFlavor {
407     SPF_UNKNOWN = 0,
408     SPF_SMIN,                   /// Signed minimum
409     SPF_UMIN,                   /// Unsigned minimum
410     SPF_SMAX,                   /// Signed maximum
411     SPF_UMAX,                   /// Unsigned maximum
412     SPF_FMINNUM,                /// Floating point minnum
413     SPF_FMAXNUM,                /// Floating point maxnum
414     SPF_ABS,                    /// Absolute value
415     SPF_NABS                    /// Negated absolute value
416   };
417   /// \brief Behavior when a floating point min/max is given one NaN and one
418   /// non-NaN as input.
419   enum SelectPatternNaNBehavior {
420     SPNB_NA = 0,                /// NaN behavior not applicable.
421     SPNB_RETURNS_NAN,           /// Given one NaN input, returns the NaN.
422     SPNB_RETURNS_OTHER,         /// Given one NaN input, returns the non-NaN.
423     SPNB_RETURNS_ANY            /// Given one NaN input, can return either (or
424                                 /// it has been determined that no operands can
425                                 /// be NaN).
426   };
427   struct SelectPatternResult {
428     SelectPatternFlavor Flavor;
429     SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
430                                           /// SPF_FMINNUM or SPF_FMAXNUM.
431     bool Ordered;               /// When implementing this min/max pattern as
432                                 /// fcmp; select, does the fcmp have to be
433                                 /// ordered?
434
435     /// \brief Return true if \p SPF is a min or a max pattern.
436     static bool isMinOrMax(SelectPatternFlavor SPF) {
437       return !(SPF == SPF_UNKNOWN || SPF == SPF_ABS || SPF == SPF_NABS);
438     }
439   };
440   /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
441   /// and providing the out parameter results if we successfully match.
442   ///
443   /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
444   /// not match that of the original select. If this is the case, the cast
445   /// operation (one of Trunc,SExt,Zext) that must be done to transform the
446   /// type of LHS and RHS into the type of V is returned in CastOp.
447   ///
448   /// For example:
449   ///   %1 = icmp slt i32 %a, i32 4
450   ///   %2 = sext i32 %a to i64
451   ///   %3 = select i1 %1, i64 %2, i64 4
452   ///
453   /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
454   ///
455   SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
456                                          Instruction::CastOps *CastOp = nullptr);
457   static inline SelectPatternResult
458   matchSelectPattern(const Value *V, const Value *&LHS, const Value *&RHS,
459                      Instruction::CastOps *CastOp = nullptr) {
460     Value *L = const_cast<Value*>(LHS);
461     Value *R = const_cast<Value*>(RHS);
462     auto Result = matchSelectPattern(const_cast<Value*>(V), L, R);
463     LHS = L;
464     RHS = R;
465     return Result;
466   }
467
468   /// Return true if RHS is known to be implied true by LHS.  Return false if
469   /// RHS is known to be implied false by LHS.  Otherwise, return None if no
470   /// implication can be made.
471   /// A & B must be i1 (boolean) values or a vector of such values. Note that
472   /// the truth table for implication is the same as <=u on i1 values (but not
473   /// <=s!).  The truth table for both is:
474   ///    | T | F (B)
475   ///  T | T | F
476   ///  F | T | T
477   /// (A)
478   Optional<bool> isImpliedCondition(const Value *LHS, const Value *RHS,
479                                     const DataLayout &DL,
480                                     bool InvertAPred = false,
481                                     unsigned Depth = 0,
482                                     AssumptionCache *AC = nullptr,
483                                     const Instruction *CxtI = nullptr,
484                                     const DominatorTree *DT = nullptr);
485 } // end namespace llvm
486
487 #endif