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