LLVM  10.0.0
ValueTracking.h
Go to the documentation of this file.
1 //===- llvm/Analysis/ValueTracking.h - Walk computations --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains routines that help analyze properties that chains of
10 // computations have.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_ANALYSIS_VALUETRACKING_H
15 #define LLVM_ANALYSIS_VALUETRACKING_H
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include <cassert>
26 #include <cstdint>
27 
28 namespace llvm {
29 
30 class AddOperator;
31 class APInt;
32 class AssumptionCache;
33 class DominatorTree;
34 class GEPOperator;
35 class IntrinsicInst;
36 class WithOverflowInst;
37 struct KnownBits;
38 class Loop;
39 class LoopInfo;
40 class MDNode;
41 class OptimizationRemarkEmitter;
42 class StringRef;
43 class TargetLibraryInfo;
44 class Value;
45 
46  /// Determine which bits of V are known to be either zero or one and return
47  /// them in the KnownZero/KnownOne bit sets.
48  ///
49  /// This function is defined on values with integer type, values with pointer
50  /// type, and vectors of integers. In the case
51  /// where V is a vector, the known zero and known one values are the
52  /// same width as the vector element, and the bit is set only if it is true
53  /// for all of the elements in the vector.
54  void computeKnownBits(const Value *V, KnownBits &Known,
55  const DataLayout &DL, unsigned Depth = 0,
56  AssumptionCache *AC = nullptr,
57  const Instruction *CxtI = nullptr,
58  const DominatorTree *DT = nullptr,
59  OptimizationRemarkEmitter *ORE = nullptr,
60  bool UseInstrInfo = true);
61 
62  /// Returns the known bits rather than passing by reference.
63  KnownBits computeKnownBits(const Value *V, const DataLayout &DL,
64  unsigned Depth = 0, AssumptionCache *AC = nullptr,
65  const Instruction *CxtI = nullptr,
66  const DominatorTree *DT = nullptr,
67  OptimizationRemarkEmitter *ORE = nullptr,
68  bool UseInstrInfo = true);
69 
70  /// Compute known bits from the range metadata.
71  /// \p KnownZero the set of bits that are known to be zero
72  /// \p KnownOne the set of bits that are known to be one
73  void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
74  KnownBits &Known);
75 
76  /// Return true if LHS and RHS have no common bits set.
77  bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
78  const DataLayout &DL,
79  AssumptionCache *AC = nullptr,
80  const Instruction *CxtI = nullptr,
81  const DominatorTree *DT = nullptr,
82  bool UseInstrInfo = true);
83 
84  /// Return true if the given value is known to have exactly one bit set when
85  /// defined. For vectors return true if every element is known to be a power
86  /// of two when defined. Supports values with integer or pointer type and
87  /// vectors of integers. If 'OrZero' is set, then return true if the given
88  /// value is either a power of two or zero.
89  bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
90  bool OrZero = false, unsigned Depth = 0,
91  AssumptionCache *AC = nullptr,
92  const Instruction *CxtI = nullptr,
93  const DominatorTree *DT = nullptr,
94  bool UseInstrInfo = true);
95 
96  bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI);
97 
98  /// Return true if the given value is known to be non-zero when defined. For
99  /// vectors, return true if every element is known to be non-zero when
100  /// defined. For pointers, if the context instruction and dominator tree are
101  /// specified, perform context-sensitive analysis and return true if the
102  /// pointer couldn't possibly be null at the specified instruction.
103  /// Supports values with integer or pointer type and vectors of integers.
104  bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth = 0,
105  AssumptionCache *AC = nullptr,
106  const Instruction *CxtI = nullptr,
107  const DominatorTree *DT = nullptr,
108  bool UseInstrInfo = true);
109 
110  /// Return true if the two given values are negation.
111  /// Currently can recoginze Value pair:
112  /// 1: <X, Y> if X = sub (0, Y) or Y = sub (0, X)
113  /// 2: <X, Y> if X = sub (A, B) and Y = sub (B, A)
114  bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW = false);
115 
116  /// Returns true if the give value is known to be non-negative.
117  bool isKnownNonNegative(const Value *V, const DataLayout &DL,
118  unsigned Depth = 0,
119  AssumptionCache *AC = nullptr,
120  const Instruction *CxtI = nullptr,
121  const DominatorTree *DT = nullptr,
122  bool UseInstrInfo = true);
123 
124  /// Returns true if the given value is known be positive (i.e. non-negative
125  /// and non-zero).
126  bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth = 0,
127  AssumptionCache *AC = nullptr,
128  const Instruction *CxtI = nullptr,
129  const DominatorTree *DT = nullptr,
130  bool UseInstrInfo = true);
131 
132  /// Returns true if the given value is known be negative (i.e. non-positive
133  /// and non-zero).
134  bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth = 0,
135  AssumptionCache *AC = nullptr,
136  const Instruction *CxtI = nullptr,
137  const DominatorTree *DT = nullptr,
138  bool UseInstrInfo = true);
139 
140  /// Return true if the given values are known to be non-equal when defined.
141  /// Supports scalar integer types only.
142  bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL,
143  AssumptionCache *AC = nullptr,
144  const Instruction *CxtI = nullptr,
145  const DominatorTree *DT = nullptr,
146  bool UseInstrInfo = true);
147 
148  /// Return true if 'V & Mask' is known to be zero. We use this predicate to
149  /// simplify operations downstream. Mask is known to be zero for bits that V
150  /// cannot have.
151  ///
152  /// This function is defined on values with integer type, values with pointer
153  /// type, and vectors of integers. In the case
154  /// where V is a vector, the mask, known zero, and known one values are the
155  /// same width as the vector element, and the bit is set only if it is true
156  /// for all of the elements in the vector.
157  bool MaskedValueIsZero(const Value *V, const APInt &Mask,
158  const DataLayout &DL,
159  unsigned Depth = 0, AssumptionCache *AC = nullptr,
160  const Instruction *CxtI = nullptr,
161  const DominatorTree *DT = nullptr,
162  bool UseInstrInfo = true);
163 
164  /// Return the number of times the sign bit of the register is replicated into
165  /// the other bits. We know that at least 1 bit is always equal to the sign
166  /// bit (itself), but other cases can give us information. For example,
167  /// immediately after an "ashr X, 2", we know that the top 3 bits are all
168  /// equal to each other, so we return 3. For vectors, return the number of
169  /// sign bits for the vector element with the mininum number of known sign
170  /// bits.
171  unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL,
172  unsigned Depth = 0, AssumptionCache *AC = nullptr,
173  const Instruction *CxtI = nullptr,
174  const DominatorTree *DT = nullptr,
175  bool UseInstrInfo = true);
176 
177  /// This function computes the integer multiple of Base that equals V. If
178  /// successful, it returns true and returns the multiple in Multiple. If
179  /// unsuccessful, it returns false. Also, if V can be simplified to an
180  /// integer, then the simplified V is returned in Val. Look through sext only
181  /// if LookThroughSExt=true.
182  bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
183  bool LookThroughSExt = false,
184  unsigned Depth = 0);
185 
186  /// Map a call instruction to an intrinsic ID. Libcalls which have equivalent
187  /// intrinsics are treated as-if they were intrinsics.
188  Intrinsic::ID getIntrinsicForCallSite(ImmutableCallSite ICS,
189  const TargetLibraryInfo *TLI);
190 
191  /// Return true if we can prove that the specified FP value is never equal to
192  /// -0.0.
193  bool CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
194  unsigned Depth = 0);
195 
196  /// Return true if we can prove that the specified FP value is either NaN or
197  /// never less than -0.0.
198  ///
199  /// NaN --> true
200  /// +0 --> true
201  /// -0 --> true
202  /// x > +0 --> true
203  /// x < -0 --> false
204  bool CannotBeOrderedLessThanZero(const Value *V, const TargetLibraryInfo *TLI);
205 
206  /// Return true if the floating-point scalar value is not an infinity or if
207  /// the floating-point vector value has no infinities. Return false if a value
208  /// could ever be infinity.
209  bool isKnownNeverInfinity(const Value *V, const TargetLibraryInfo *TLI,
210  unsigned Depth = 0);
211 
212  /// Return true if the floating-point scalar value is not a NaN or if the
213  /// floating-point vector value has no NaN elements. Return false if a value
214  /// could ever be NaN.
215  bool isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
216  unsigned Depth = 0);
217 
218  /// Return true if we can prove that the specified FP value's sign bit is 0.
219  ///
220  /// NaN --> true/false (depending on the NaN's sign bit)
221  /// +0 --> true
222  /// -0 --> false
223  /// x > +0 --> true
224  /// x < -0 --> false
225  bool SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI);
226 
227  /// If the specified value can be set by repeating the same byte in memory,
228  /// return the i8 value that it is represented with. This is true for all i8
229  /// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
230  /// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
231  /// i16 0x1234), return null. If the value is entirely undef and padding,
232  /// return undef.
233  Value *isBytewiseValue(Value *V, const DataLayout &DL);
234 
235  /// Given an aggregate and an sequence of indices, see if the scalar value
236  /// indexed is already around as a register, for example if it were inserted
237  /// directly into the aggregate.
238  ///
239  /// If InsertBefore is not null, this function will duplicate (modified)
240  /// insertvalues when a part of a nested struct is extracted.
242  ArrayRef<unsigned> idx_range,
243  Instruction *InsertBefore = nullptr);
244 
245  /// Analyze the specified pointer to see if it can be expressed as a base
246  /// pointer plus a constant offset. Return the base and offset to the caller.
247  ///
248  /// This is a wrapper around Value::stripAndAccumulateConstantOffsets that
249  /// creates and later unpacks the required APInt.
251  const DataLayout &DL,
252  bool AllowNonInbounds = true) {
253  APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
254  Value *Base =
255  Ptr->stripAndAccumulateConstantOffsets(DL, OffsetAPInt, AllowNonInbounds);
256 
257  Offset = OffsetAPInt.getSExtValue();
258  return Base;
259  }
260  inline const Value *
262  const DataLayout &DL,
263  bool AllowNonInbounds = true) {
264  return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset, DL,
265  AllowNonInbounds);
266  }
267 
268  /// Returns true if the GEP is based on a pointer to a string (array of
269  // \p CharSize integers) and is indexing into this string.
271  unsigned CharSize = 8);
272 
273  /// Represents offset+length into a ConstantDataArray.
275  /// ConstantDataArray pointer. nullptr indicates a zeroinitializer (a valid
276  /// initializer, it just doesn't fit the ConstantDataArray interface).
278 
279  /// Slice starts at this Offset.
280  uint64_t Offset;
281 
282  /// Length of the slice.
283  uint64_t Length;
284 
285  /// Moves the Offset and adjusts Length accordingly.
286  void move(uint64_t Delta) {
287  assert(Delta < Length);
288  Offset += Delta;
289  Length -= Delta;
290  }
291 
292  /// Convenience accessor for elements in the slice.
293  uint64_t operator[](unsigned I) const {
294  return Array==nullptr ? 0 : Array->getElementAsInteger(I + Offset);
295  }
296  };
297 
298  /// Returns true if the value \p V is a pointer into a ConstantDataArray.
299  /// If successful \p Slice will point to a ConstantDataArray info object
300  /// with an appropriate offset.
302  unsigned ElementSize, uint64_t Offset = 0);
303 
304  /// This function computes the length of a null-terminated C string pointed to
305  /// by V. If successful, it returns true and returns the string in Str. If
306  /// unsuccessful, it returns false. This does not include the trailing null
307  /// character by default. If TrimAtNul is set to false, then this returns any
308  /// trailing null characters as well as any other characters that come after
309  /// it.
310  bool getConstantStringInfo(const Value *V, StringRef &Str,
311  uint64_t Offset = 0, bool TrimAtNul = true);
312 
313  /// If we can compute the length of the string pointed to by the specified
314  /// pointer, return 'len+1'. If we can't, return 0.
315  uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
316 
317  /// This function returns call pointer argument that is considered the same by
318  /// aliasing rules. You CAN'T use it to replace one value with another. If
319  /// \p MustPreserveNullness is true, the call must preserve the nullness of
320  /// the pointer.
322  bool MustPreserveNullness);
323  inline Value *
325  bool MustPreserveNullness) {
326  return const_cast<Value *>(getArgumentAliasingToReturnedPointer(
327  const_cast<const CallBase *>(Call), MustPreserveNullness));
328  }
329 
330  /// {launder,strip}.invariant.group returns pointer that aliases its argument,
331  /// and it only captures pointer by returning it.
332  /// These intrinsics are not marked as nocapture, because returning is
333  /// considered as capture. The arguments are not marked as returned neither,
334  /// because it would make it useless. If \p MustPreserveNullness is true,
335  /// the intrinsic must preserve the nullness of the pointer.
337  const CallBase *Call, bool MustPreserveNullness);
338 
339  /// This method strips off any GEP address adjustments and pointer casts from
340  /// the specified value, returning the original object being addressed. Note
341  /// that the returned value has pointer type if the specified value does. If
342  /// the MaxLookup value is non-zero, it limits the number of instructions to
343  /// be stripped off.
344  Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
345  unsigned MaxLookup = 6);
346  inline const Value *GetUnderlyingObject(const Value *V, const DataLayout &DL,
347  unsigned MaxLookup = 6) {
348  return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
349  }
350 
351  /// This method is similar to GetUnderlyingObject except that it can
352  /// look through phi and select instructions and return multiple objects.
353  ///
354  /// If LoopInfo is passed, loop phis are further analyzed. If a pointer
355  /// accesses different objects in each iteration, we don't look through the
356  /// phi node. E.g. consider this loop nest:
357  ///
358  /// int **A;
359  /// for (i)
360  /// for (j) {
361  /// A[i][j] = A[i-1][j] * B[j]
362  /// }
363  ///
364  /// This is transformed by Load-PRE to stash away A[i] for the next iteration
365  /// of the outer loop:
366  ///
367  /// Curr = A[0]; // Prev_0
368  /// for (i: 1..N) {
369  /// Prev = Curr; // Prev = PHI (Prev_0, Curr)
370  /// Curr = A[i];
371  /// for (j: 0..N) {
372  /// Curr[j] = Prev[j] * B[j]
373  /// }
374  /// }
375  ///
376  /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
377  /// should not assume that Curr and Prev share the same underlying object thus
378  /// it shouldn't look through the phi above.
379  void GetUnderlyingObjects(const Value *V,
381  const DataLayout &DL, LoopInfo *LI = nullptr,
382  unsigned MaxLookup = 6);
383 
384  /// This is a wrapper around GetUnderlyingObjects and adds support for basic
385  /// ptrtoint+arithmetic+inttoptr sequences.
387  SmallVectorImpl<Value *> &Objects,
388  const DataLayout &DL);
389 
390  /// Return true if the only users of this pointer are lifetime markers.
391  bool onlyUsedByLifetimeMarkers(const Value *V);
392 
393  /// Return true if speculation of the given load must be suppressed to avoid
394  /// ordering or interfering with an active sanitizer. If not suppressed,
395  /// dereferenceability and alignment must be proven separately. Note: This
396  /// is only needed for raw reasoning; if you use the interface below
397  /// (isSafeToSpeculativelyExecute), this is handled internally.
398  bool mustSuppressSpeculation(const LoadInst &LI);
399 
400  /// Return true if the instruction does not have any effects besides
401  /// calculating the result and does not have undefined behavior.
402  ///
403  /// This method never returns true for an instruction that returns true for
404  /// mayHaveSideEffects; however, this method also does some other checks in
405  /// addition. It checks for undefined behavior, like dividing by zero or
406  /// loading from an invalid pointer (but not for undefined results, like a
407  /// shift with a shift amount larger than the width of the result). It checks
408  /// for malloc and alloca because speculatively executing them might cause a
409  /// memory leak. It also returns false for instructions related to control
410  /// flow, specifically terminators and PHI nodes.
411  ///
412  /// If the CtxI is specified this method performs context-sensitive analysis
413  /// and returns true if it is safe to execute the instruction immediately
414  /// before the CtxI.
415  ///
416  /// If the CtxI is NOT specified this method only looks at the instruction
417  /// itself and its operands, so if this method returns true, it is safe to
418  /// move the instruction as long as the correct dominance relationships for
419  /// the operands and users hold.
420  ///
421  /// This method can return true for instructions that read memory;
422  /// for such instructions, moving them may change the resulting value.
423  bool isSafeToSpeculativelyExecute(const Value *V,
424  const Instruction *CtxI = nullptr,
425  const DominatorTree *DT = nullptr);
426 
427  /// Returns true if the result or effects of the given instructions \p I
428  /// depend on or influence global memory.
429  /// Memory dependence arises for example if the instruction reads from
430  /// memory or may produce effects or undefined behaviour. Memory dependent
431  /// instructions generally cannot be reorderd with respect to other memory
432  /// dependent instructions or moved into non-dominated basic blocks.
433  /// Instructions which just compute a value based on the values of their
434  /// operands are not memory dependent.
435  bool mayBeMemoryDependent(const Instruction &I);
436 
437  /// Return true if it is an intrinsic that cannot be speculated but also
438  /// cannot trap.
439  bool isAssumeLikeIntrinsic(const Instruction *I);
440 
441  /// Return true if it is valid to use the assumptions provided by an
442  /// assume intrinsic, I, at the point in the control-flow identified by the
443  /// context instruction, CxtI.
444  bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
445  const DominatorTree *DT = nullptr);
446 
447  enum class OverflowResult {
448  /// Always overflows in the direction of signed/unsigned min value.
450  /// Always overflows in the direction of signed/unsigned max value.
452  /// May or may not overflow.
453  MayOverflow,
454  /// Never overflows.
456  };
457 
459  const Value *RHS,
460  const DataLayout &DL,
461  AssumptionCache *AC,
462  const Instruction *CxtI,
463  const DominatorTree *DT,
464  bool UseInstrInfo = true);
465  OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
466  const DataLayout &DL,
467  AssumptionCache *AC,
468  const Instruction *CxtI,
469  const DominatorTree *DT,
470  bool UseInstrInfo = true);
472  const Value *RHS,
473  const DataLayout &DL,
474  AssumptionCache *AC,
475  const Instruction *CxtI,
476  const DominatorTree *DT,
477  bool UseInstrInfo = true);
478  OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS,
479  const DataLayout &DL,
480  AssumptionCache *AC = nullptr,
481  const Instruction *CxtI = nullptr,
482  const DominatorTree *DT = nullptr);
483  /// This version also leverages the sign bit of Add if known.
485  const DataLayout &DL,
486  AssumptionCache *AC = nullptr,
487  const Instruction *CxtI = nullptr,
488  const DominatorTree *DT = nullptr);
490  const DataLayout &DL,
491  AssumptionCache *AC,
492  const Instruction *CxtI,
493  const DominatorTree *DT);
494  OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
495  const DataLayout &DL,
496  AssumptionCache *AC,
497  const Instruction *CxtI,
498  const DominatorTree *DT);
499 
500  /// Returns true if the arithmetic part of the \p WO 's result is
501  /// used only along the paths control dependent on the computation
502  /// not overflowing, \p WO being an <op>.with.overflow intrinsic.
504  const DominatorTree &DT);
505 
506 
507  /// Determine the possible constant range of an integer or vector of integer
508  /// value. This is intended as a cheap, non-recursive check.
509  ConstantRange computeConstantRange(const Value *V, bool UseInstrInfo = true);
510 
511  /// Return true if this function can prove that the instruction I will
512  /// always transfer execution to one of its successors (including the next
513  /// instruction that follows within a basic block). E.g. this is not
514  /// guaranteed for function calls that could loop infinitely.
515  ///
516  /// In other words, this function returns false for instructions that may
517  /// transfer execution or fail to transfer execution in a way that is not
518  /// captured in the CFG nor in the sequence of instructions within a basic
519  /// block.
520  ///
521  /// Undefined behavior is assumed not to happen, so e.g. division is
522  /// guaranteed to transfer execution to the following instruction even
523  /// though division by zero might cause undefined behavior.
525 
526  /// Returns true if this block does not contain a potential implicit exit.
527  /// This is equivelent to saying that all instructions within the basic block
528  /// are guaranteed to transfer execution to their successor within the basic
529  /// block. This has the same assumptions w.r.t. undefined behavior as the
530  /// instruction variant of this function.
532 
533  /// Return true if this function can prove that the instruction I
534  /// is executed for every iteration of the loop L.
535  ///
536  /// Note that this currently only considers the loop header.
538  const Loop *L);
539 
540  /// Return true if this function can prove that I is guaranteed to yield
541  /// full-poison (all bits poison) if at least one of its operands are
542  /// full-poison (all bits poison).
543  ///
544  /// The exact rules for how poison propagates through instructions have
545  /// not been settled as of 2015-07-10, so this function is conservative
546  /// and only considers poison to be propagated in uncontroversial
547  /// cases. There is no attempt to track values that may be only partially
548  /// poison.
549  bool propagatesFullPoison(const Instruction *I);
550 
551  /// Return either nullptr or an operand of I such that I will trigger
552  /// undefined behavior if I is executed and that operand has a full-poison
553  /// value (all bits poison).
555 
556  /// Return true if the given instruction must trigger undefined behavior.
557  /// when I is executed with any operands which appear in KnownPoison holding
558  /// a full-poison value at the point of execution.
559  bool mustTriggerUB(const Instruction *I,
560  const SmallSet<const Value *, 16>& KnownPoison);
561 
562  /// Return true if this function can prove that if PoisonI is executed
563  /// and yields a full-poison value (all bits poison), then that will
564  /// trigger undefined behavior.
565  ///
566  /// Note that this currently only considers the basic block that is
567  /// the parent of I.
568  bool programUndefinedIfFullPoison(const Instruction *PoisonI);
569 
570  /// Return true if this function can prove that V is never undef value
571  /// or poison value.
573 
574  /// Specific patterns of select instructions we can match.
577  SPF_SMIN, /// Signed minimum
578  SPF_UMIN, /// Unsigned minimum
579  SPF_SMAX, /// Signed maximum
580  SPF_UMAX, /// Unsigned maximum
581  SPF_FMINNUM, /// Floating point minnum
582  SPF_FMAXNUM, /// Floating point maxnum
583  SPF_ABS, /// Absolute value
584  SPF_NABS /// Negated absolute value
585  };
586 
587  /// Behavior when a floating point min/max is given one NaN and one
588  /// non-NaN as input.
590  SPNB_NA = 0, /// NaN behavior not applicable.
591  SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
592  SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
593  SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
594  /// it has been determined that no operands can
595  /// be NaN).
596  };
597 
600  SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
601  /// SPF_FMINNUM or SPF_FMAXNUM.
602  bool Ordered; /// When implementing this min/max pattern as
603  /// fcmp; select, does the fcmp have to be
604  /// ordered?
605 
606  /// Return true if \p SPF is a min or a max pattern.
607  static bool isMinOrMax(SelectPatternFlavor SPF) {
608  return SPF != SPF_UNKNOWN && SPF != SPF_ABS && SPF != SPF_NABS;
609  }
610  };
611 
612  /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
613  /// and providing the out parameter results if we successfully match.
614  ///
615  /// For ABS/NABS, LHS will be set to the input to the abs idiom. RHS will be
616  /// the negation instruction from the idiom.
617  ///
618  /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
619  /// not match that of the original select. If this is the case, the cast
620  /// operation (one of Trunc,SExt,Zext) that must be done to transform the
621  /// type of LHS and RHS into the type of V is returned in CastOp.
622  ///
623  /// For example:
624  /// %1 = icmp slt i32 %a, i32 4
625  /// %2 = sext i32 %a to i64
626  /// %3 = select i1 %1, i64 %2, i64 4
627  ///
628  /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
629  ///
631  Instruction::CastOps *CastOp = nullptr,
632  unsigned Depth = 0);
633 
634  inline SelectPatternResult
635  matchSelectPattern(const Value *V, const Value *&LHS, const Value *&RHS) {
636  Value *L = const_cast<Value *>(LHS);
637  Value *R = const_cast<Value *>(RHS);
638  auto Result = matchSelectPattern(const_cast<Value *>(V), L, R);
639  LHS = L;
640  RHS = R;
641  return Result;
642  }
643 
644  /// Determine the pattern that a select with the given compare as its
645  /// predicate and given values as its true/false operands would match.
647  CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
648  Instruction::CastOps *CastOp = nullptr, unsigned Depth = 0);
649 
650  /// Return the canonical comparison predicate for the specified
651  /// minimum/maximum flavor.
653  bool Ordered = false);
654 
655  /// Return the inverse minimum/maximum flavor of the specified flavor.
656  /// For example, signed minimum is the inverse of signed maximum.
658 
659  /// Return the canonical inverse comparison predicate for the specified
660  /// minimum/maximum flavor.
662 
663  /// Return true if RHS is known to be implied true by LHS. Return false if
664  /// RHS is known to be implied false by LHS. Otherwise, return None if no
665  /// implication can be made.
666  /// A & B must be i1 (boolean) values or a vector of such values. Note that
667  /// the truth table for implication is the same as <=u on i1 values (but not
668  /// <=s!). The truth table for both is:
669  /// | T | F (B)
670  /// T | T | F
671  /// F | T | T
672  /// (A)
673  Optional<bool> isImpliedCondition(const Value *LHS, const Value *RHS,
674  const DataLayout &DL, bool LHSIsTrue = true,
675  unsigned Depth = 0);
676 
677  /// Return the boolean condition value in the context of the given instruction
678  /// if it is known based on dominating conditions.
680  const Instruction *ContextI,
681  const DataLayout &DL);
682 
683  /// If Ptr1 is provably equal to Ptr2 plus a constant offset, return that
684  /// offset. For example, Ptr1 might be &A[42], and Ptr2 might be &A[40]. In
685  /// this case offset would be -8.
686  Optional<int64_t> isPointerOffset(const Value *Ptr1, const Value *Ptr2,
687  const DataLayout &DL);
688 } // end namespace llvm
689 
690 #endif // LLVM_ANALYSIS_VALUETRACKING_H
const Value * getGuaranteedNonFullPoisonOp(const Instruction *I)
Return either nullptr or an operand of I such that I will trigger undefined behavior if I is executed...
bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the given value is known be positive (i.e.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:722
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset...
bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
Unsigned minimum.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Represents an op.with.overflow intrinsic.
bool isGuaranteedNotToBeUndefOrPoison(const Value *V)
Return true if this function can prove that V is never undef value or poison value.
Optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
A cache of @llvm.assume calls within a function.
Always overflows in the direction of signed/unsigned min value.
bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr)
Return true if it is valid to use the assumptions provided by an assume intrinsic, I, at the point in the control-flow identified by the context instruction, CxtI.
SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1105
An instruction for reading from memory.
Definition: Instructions.h:169
ConstantRange computeConstantRange(const Value *V, bool UseInstrInfo=true)
Determine the possible constant range of an integer or vector of integer value.
Hexagon Common GEP
bool isGEPBasedOnPointerToString(const GEPOperator *GEP, unsigned CharSize=8)
Returns true if the GEP is based on a pointer to a string (array of.
uint64_t Offset
Slice starts at this Offset.
bool Ordered
Only applicable if Flavor is SPF_FMINNUM or SPF_FMAXNUM.
bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveNullness)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
bool propagatesFullPoison(const Instruction *I)
Return true if this function can prove that I is guaranteed to yield full-poison (all bits poison) if...
Signed maximum.
Intrinsic::ID getIntrinsicForCallSite(ImmutableCallSite ICS, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to have exactly one bit set when defined. ...
Absolute value.
OverflowResult computeOverflowForUnsignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
NaN behavior not applicable.
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if &#39;V & Mask&#39; is known to be zero.
bool programUndefinedIfFullPoison(const Instruction *PoisonI)
Return true if this function can prove that if PoisonI is executed and yields a full-poison value (al...
uint64_t operator[](unsigned I) const
Convenience accessor for elements in the slice.
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1632
bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO &#39;s result is used only along the paths control dependen...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
const ConstantDataArray * Array
ConstantDataArray pointer.
May or may not overflow.
SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the give value is known to be non-negative.
uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return &#39;len+1&#39;...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
bool CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits...
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
void GetUnderlyingObjects(const Value *V, SmallVectorImpl< const Value *> &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
bool isKnownNeverInfinity(const Value *V, const TargetLibraryInfo *TLI, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false)
Return true if the two given values are negation.
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double, and whose elements are just simple data values (i.e.
Definition: Constants.h:690
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value *> &Objects, const DataLayout &DL)
This is a wrapper around GetUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
bool mustTriggerUB(const Instruction *I, const SmallSet< const Value *, 16 > &KnownPoison)
Return true if the given instruction must trigger undefined behavior.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:732
CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input. ...
unsigned getIndexTypeSizeInBits(Type *Ty) const
Layout size of the index used in GEP calculation.
Definition: DataLayout.cpp:687
Represents offset+length into a ConstantDataArray.
CmpInst::Predicate getInverseMinMaxPred(SelectPatternFlavor SPF)
Return the canonical inverse comparison predicate for the specified minimum/maximum flavor...
bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap. ...
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, Instruction *InsertBefore=nullptr)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
Floating point maxnum.
Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
Given one NaN input, returns the non-NaN.
const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveNullness)
This function returns call pointer argument that is considered the same by aliasing rules...
SelectPatternFlavor Flavor
Unsigned maximum.
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
Definition: Constants.cpp:2760
uint64_t Length
Length of the slice.
SelectPatternFlavor
Specific patterns of select instructions we can match.
This class represents a range of values.
Definition: ConstantRange.h:47
Floating point minnum.
SelectPatternNaNBehavior NaNBehavior
void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
Optional< int64_t > isPointerOffset(const Value *Ptr1, const Value *Ptr2, const DataLayout &DL)
If Ptr1 is provably equal to Ptr2 plus a constant offset, return that offset.
Class for arbitrary precision integers.
Definition: APInt.h:69
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to be non-zero when defined.
const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds) const
Accumulate the constant offset this value has compared to a base pointer.
Definition: Value.cpp:551
Always overflows in the direction of signed/unsigned max value.
bool mayBeMemoryDependent(const Instruction &I)
Returns true if the result or effects of the given instructions I depend on or influence global memor...
OverflowResult
bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the given value is known be negative (i.e.
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:509
bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given values are known to be non-equal when defined.
#define I(x, y, z)
Definition: MD5.cpp:58
bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if LHS and RHS have no common bits set.
bool SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI)
Return true if we can prove that the specified FP value&#39;s sign bit is 0.
bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple, bool LookThroughSExt=false, unsigned Depth=0)
This function computes the integer multiple of Base that equals V.
bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
bool isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
Signed minimum.
Optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
bool getConstantStringInfo(const Value *V, StringRef &Str, uint64_t Offset=0, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Given one NaN input, returns the NaN.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM Value Representation.
Definition: Value.h:74
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
void move(uint64_t Delta)
Moves the Offset and adjusts Length accordingly.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
bool CannotBeOrderedLessThanZero(const Value *V, const TargetLibraryInfo *TLI)
Return true if we can prove that the specified FP value is either NaN or never less than -0...
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)