1 //===- llvm/Analysis/ValueTracking.h - Walk computations --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains routines that help analyze properties that chains of
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_VALUETRACKING_H
16 #define LLVM_ANALYSIS_VALUETRACKING_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/Instruction.h"
23 #include "llvm/IR/Intrinsics.h"
31 class AssumptionCache;
40 class OptimizationRemarkEmitter;
42 class TargetLibraryInfo;
45 /// Determine which bits of V are known to be either zero or one and return
46 /// them in the KnownZero/KnownOne bit sets.
48 /// This function is defined on values with integer type, values with pointer
49 /// type, and vectors of integers. In the case
50 /// where V is a vector, the known zero and known one values are the
51 /// same width as the vector element, and the bit is set only if it is true
52 /// for all of the elements in the vector.
53 void computeKnownBits(const Value *V, KnownBits &Known,
54 const DataLayout &DL, unsigned Depth = 0,
55 AssumptionCache *AC = nullptr,
56 const Instruction *CxtI = nullptr,
57 const DominatorTree *DT = nullptr,
58 OptimizationRemarkEmitter *ORE = nullptr);
60 /// Returns the known bits rather than passing by reference.
61 KnownBits computeKnownBits(const Value *V, const DataLayout &DL,
62 unsigned Depth = 0, AssumptionCache *AC = nullptr,
63 const Instruction *CxtI = nullptr,
64 const DominatorTree *DT = nullptr,
65 OptimizationRemarkEmitter *ORE = nullptr);
67 /// Compute known bits from the range metadata.
68 /// \p KnownZero the set of bits that are known to be zero
69 /// \p KnownOne the set of bits that are known to be one
70 void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
73 /// Return true if LHS and RHS have no common bits set.
74 bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
76 AssumptionCache *AC = nullptr,
77 const Instruction *CxtI = nullptr,
78 const DominatorTree *DT = nullptr);
80 /// Return true if the given value is known to have exactly one bit set when
81 /// defined. For vectors return true if every element is known to be a power
82 /// of two when defined. Supports values with integer or pointer type and
83 /// vectors of integers. If 'OrZero' is set, then return true if the given
84 /// value is either a power of two or zero.
85 bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
86 bool OrZero = false, unsigned Depth = 0,
87 AssumptionCache *AC = nullptr,
88 const Instruction *CxtI = nullptr,
89 const DominatorTree *DT = nullptr);
91 bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI);
93 /// Return true if the given value is known to be non-zero when defined. For
94 /// vectors, return true if every element is known to be non-zero when
95 /// defined. For pointers, if the context instruction and dominator tree are
96 /// specified, perform context-sensitive analysis and return true if the
97 /// pointer couldn't possibly be null at the specified instruction.
98 /// Supports values with integer or pointer type and vectors of integers.
99 bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth = 0,
100 AssumptionCache *AC = nullptr,
101 const Instruction *CxtI = nullptr,
102 const DominatorTree *DT = nullptr);
104 /// Returns true if the give value is known to be non-negative.
105 bool isKnownNonNegative(const Value *V, const DataLayout &DL,
107 AssumptionCache *AC = nullptr,
108 const Instruction *CxtI = nullptr,
109 const DominatorTree *DT = nullptr);
111 /// Returns true if the given value is known be positive (i.e. non-negative
113 bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth = 0,
114 AssumptionCache *AC = nullptr,
115 const Instruction *CxtI = nullptr,
116 const DominatorTree *DT = nullptr);
118 /// Returns true if the given value is known be negative (i.e. non-positive
120 bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth = 0,
121 AssumptionCache *AC = nullptr,
122 const Instruction *CxtI = nullptr,
123 const DominatorTree *DT = nullptr);
125 /// Return true if the given values are known to be non-equal when defined.
126 /// Supports scalar integer types only.
127 bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL,
128 AssumptionCache *AC = nullptr,
129 const Instruction *CxtI = nullptr,
130 const DominatorTree *DT = nullptr);
132 /// Return true if 'V & Mask' is known to be zero. We use this predicate to
133 /// simplify operations downstream. Mask is known to be zero for bits that V
136 /// This function is defined on values with integer type, values with pointer
137 /// type, and vectors of integers. In the case
138 /// where V is a vector, the mask, known zero, and known one values are the
139 /// same width as the vector element, and the bit is set only if it is true
140 /// for all of the elements in the vector.
141 bool MaskedValueIsZero(const Value *V, const APInt &Mask,
142 const DataLayout &DL,
143 unsigned Depth = 0, AssumptionCache *AC = nullptr,
144 const Instruction *CxtI = nullptr,
145 const DominatorTree *DT = nullptr);
147 /// Return the number of times the sign bit of the register is replicated into
148 /// the other bits. We know that at least 1 bit is always equal to the sign
149 /// bit (itself), but other cases can give us information. For example,
150 /// immediately after an "ashr X, 2", we know that the top 3 bits are all
151 /// equal to each other, so we return 3. For vectors, return the number of
152 /// sign bits for the vector element with the mininum number of known sign
154 unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL,
155 unsigned Depth = 0, AssumptionCache *AC = nullptr,
156 const Instruction *CxtI = nullptr,
157 const DominatorTree *DT = nullptr);
159 /// This function computes the integer multiple of Base that equals V. If
160 /// successful, it returns true and returns the multiple in Multiple. If
161 /// unsuccessful, it returns false. Also, if V can be simplified to an
162 /// integer, then the simplified V is returned in Val. Look through sext only
163 /// if LookThroughSExt=true.
164 bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
165 bool LookThroughSExt = false,
168 /// Map a call instruction to an intrinsic ID. Libcalls which have equivalent
169 /// intrinsics are treated as-if they were intrinsics.
170 Intrinsic::ID getIntrinsicForCallSite(ImmutableCallSite ICS,
171 const TargetLibraryInfo *TLI);
173 /// Return true if we can prove that the specified FP value is never equal to
175 bool CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
178 /// Return true if we can prove that the specified FP value is either NaN or
179 /// never less than -0.0.
186 bool CannotBeOrderedLessThanZero(const Value *V, const TargetLibraryInfo *TLI);
188 /// Return true if the floating-point scalar value is not a NaN or if the
189 /// floating-point vector value has no NaN elements. Return false if a value
190 /// could ever be NaN.
191 bool isKnownNeverNaN(const Value *V);
193 /// Return true if we can prove that the specified FP value's sign bit is 0.
195 /// NaN --> true/false (depending on the NaN's sign bit)
200 bool SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI);
202 /// If the specified value can be set by repeating the same byte in memory,
203 /// return the i8 value that it is represented with. This is true for all i8
204 /// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
205 /// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
206 /// i16 0x1234), return null.
207 Value *isBytewiseValue(Value *V);
209 /// Given an aggregrate and an sequence of indices, see if the scalar value
210 /// indexed is already around as a register, for example if it were inserted
211 /// directly into the aggregrate.
213 /// If InsertBefore is not null, this function will duplicate (modified)
214 /// insertvalues when a part of a nested struct is extracted.
215 Value *FindInsertedValue(Value *V,
216 ArrayRef<unsigned> idx_range,
217 Instruction *InsertBefore = nullptr);
219 /// Analyze the specified pointer to see if it can be expressed as a base
220 /// pointer plus a constant offset. Return the base and offset to the caller.
221 Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
222 const DataLayout &DL);
223 inline const Value *GetPointerBaseWithConstantOffset(const Value *Ptr,
225 const DataLayout &DL) {
226 return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
230 /// Returns true if the GEP is based on a pointer to a string (array of
231 // \p CharSize integers) and is indexing into this string.
232 bool isGEPBasedOnPointerToString(const GEPOperator *GEP,
233 unsigned CharSize = 8);
235 /// Represents offset+length into a ConstantDataArray.
236 struct ConstantDataArraySlice {
237 /// ConstantDataArray pointer. nullptr indicates a zeroinitializer (a valid
238 /// initializer, it just doesn't fit the ConstantDataArray interface).
239 const ConstantDataArray *Array;
241 /// Slice starts at this Offset.
244 /// Length of the slice.
247 /// Moves the Offset and adjusts Length accordingly.
248 void move(uint64_t Delta) {
249 assert(Delta < Length);
254 /// Convenience accessor for elements in the slice.
255 uint64_t operator[](unsigned I) const {
256 return Array==nullptr ? 0 : Array->getElementAsInteger(I + Offset);
260 /// Returns true if the value \p V is a pointer into a ConstantDataArray.
261 /// If successful \p Slice will point to a ConstantDataArray info object
262 /// with an appropriate offset.
263 bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice,
264 unsigned ElementSize, uint64_t Offset = 0);
266 /// This function computes the length of a null-terminated C string pointed to
267 /// by V. If successful, it returns true and returns the string in Str. If
268 /// unsuccessful, it returns false. This does not include the trailing null
269 /// character by default. If TrimAtNul is set to false, then this returns any
270 /// trailing null characters as well as any other characters that come after
272 bool getConstantStringInfo(const Value *V, StringRef &Str,
273 uint64_t Offset = 0, bool TrimAtNul = true);
275 /// If we can compute the length of the string pointed to by the specified
276 /// pointer, return 'len+1'. If we can't, return 0.
277 uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
279 /// This method strips off any GEP address adjustments and pointer casts from
280 /// the specified value, returning the original object being addressed. Note
281 /// that the returned value has pointer type if the specified value does. If
282 /// the MaxLookup value is non-zero, it limits the number of instructions to
284 Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
285 unsigned MaxLookup = 6);
286 inline const Value *GetUnderlyingObject(const Value *V, const DataLayout &DL,
287 unsigned MaxLookup = 6) {
288 return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
291 /// \brief This method is similar to GetUnderlyingObject except that it can
292 /// look through phi and select instructions and return multiple objects.
294 /// If LoopInfo is passed, loop phis are further analyzed. If a pointer
295 /// accesses different objects in each iteration, we don't look through the
296 /// phi node. E.g. consider this loop nest:
301 /// A[i][j] = A[i-1][j] * B[j]
304 /// This is transformed by Load-PRE to stash away A[i] for the next iteration
305 /// of the outer loop:
307 /// Curr = A[0]; // Prev_0
309 /// Prev = Curr; // Prev = PHI (Prev_0, Curr)
312 /// Curr[j] = Prev[j] * B[j]
316 /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
317 /// should not assume that Curr and Prev share the same underlying object thus
318 /// it shouldn't look through the phi above.
319 void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
320 const DataLayout &DL, LoopInfo *LI = nullptr,
321 unsigned MaxLookup = 6);
323 /// This is a wrapper around GetUnderlyingObjects and adds support for basic
324 /// ptrtoint+arithmetic+inttoptr sequences.
325 bool getUnderlyingObjectsForCodeGen(const Value *V,
326 SmallVectorImpl<Value *> &Objects,
327 const DataLayout &DL);
329 /// Return true if the only users of this pointer are lifetime markers.
330 bool onlyUsedByLifetimeMarkers(const Value *V);
332 /// Return true if the instruction does not have any effects besides
333 /// calculating the result and does not have undefined behavior.
335 /// This method never returns true for an instruction that returns true for
336 /// mayHaveSideEffects; however, this method also does some other checks in
337 /// addition. It checks for undefined behavior, like dividing by zero or
338 /// loading from an invalid pointer (but not for undefined results, like a
339 /// shift with a shift amount larger than the width of the result). It checks
340 /// for malloc and alloca because speculatively executing them might cause a
341 /// memory leak. It also returns false for instructions related to control
342 /// flow, specifically terminators and PHI nodes.
344 /// If the CtxI is specified this method performs context-sensitive analysis
345 /// and returns true if it is safe to execute the instruction immediately
348 /// If the CtxI is NOT specified this method only looks at the instruction
349 /// itself and its operands, so if this method returns true, it is safe to
350 /// move the instruction as long as the correct dominance relationships for
351 /// the operands and users hold.
353 /// This method can return true for instructions that read memory;
354 /// for such instructions, moving them may change the resulting value.
355 bool isSafeToSpeculativelyExecute(const Value *V,
356 const Instruction *CtxI = nullptr,
357 const DominatorTree *DT = nullptr);
359 /// Returns true if the result or effects of the given instructions \p I
360 /// depend on or influence global memory.
361 /// Memory dependence arises for example if the instruction reads from
362 /// memory or may produce effects or undefined behaviour. Memory dependent
363 /// instructions generally cannot be reorderd with respect to other memory
364 /// dependent instructions or moved into non-dominated basic blocks.
365 /// Instructions which just compute a value based on the values of their
366 /// operands are not memory dependent.
367 bool mayBeMemoryDependent(const Instruction &I);
369 /// Return true if it is an intrinsic that cannot be speculated but also
371 bool isAssumeLikeIntrinsic(const Instruction *I);
373 /// Return true if it is valid to use the assumptions provided by an
374 /// assume intrinsic, I, at the point in the control-flow identified by the
375 /// context instruction, CxtI.
376 bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
377 const DominatorTree *DT = nullptr);
379 enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
381 OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
383 const DataLayout &DL,
385 const Instruction *CxtI,
386 const DominatorTree *DT);
387 OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
389 const DataLayout &DL,
391 const Instruction *CxtI,
392 const DominatorTree *DT);
393 OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS,
394 const DataLayout &DL,
395 AssumptionCache *AC = nullptr,
396 const Instruction *CxtI = nullptr,
397 const DominatorTree *DT = nullptr);
398 /// This version also leverages the sign bit of Add if known.
399 OverflowResult computeOverflowForSignedAdd(const AddOperator *Add,
400 const DataLayout &DL,
401 AssumptionCache *AC = nullptr,
402 const Instruction *CxtI = nullptr,
403 const DominatorTree *DT = nullptr);
405 /// Returns true if the arithmetic part of the \p II 's result is
406 /// used only along the paths control dependent on the computation
407 /// not overflowing, \p II being an <op>.with.overflow intrinsic.
408 bool isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
409 const DominatorTree &DT);
411 /// Return true if this function can prove that the instruction I will
412 /// always transfer execution to one of its successors (including the next
413 /// instruction that follows within a basic block). E.g. this is not
414 /// guaranteed for function calls that could loop infinitely.
416 /// In other words, this function returns false for instructions that may
417 /// transfer execution or fail to transfer execution in a way that is not
418 /// captured in the CFG nor in the sequence of instructions within a basic
421 /// Undefined behavior is assumed not to happen, so e.g. division is
422 /// guaranteed to transfer execution to the following instruction even
423 /// though division by zero might cause undefined behavior.
424 bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
426 /// Return true if this function can prove that the instruction I
427 /// is executed for every iteration of the loop L.
429 /// Note that this currently only considers the loop header.
430 bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
433 /// Return true if this function can prove that I is guaranteed to yield
434 /// full-poison (all bits poison) if at least one of its operands are
435 /// full-poison (all bits poison).
437 /// The exact rules for how poison propagates through instructions have
438 /// not been settled as of 2015-07-10, so this function is conservative
439 /// and only considers poison to be propagated in uncontroversial
440 /// cases. There is no attempt to track values that may be only partially
442 bool propagatesFullPoison(const Instruction *I);
444 /// Return either nullptr or an operand of I such that I will trigger
445 /// undefined behavior if I is executed and that operand has a full-poison
446 /// value (all bits poison).
447 const Value *getGuaranteedNonFullPoisonOp(const Instruction *I);
449 /// Return true if this function can prove that if PoisonI is executed
450 /// and yields a full-poison value (all bits poison), then that will
451 /// trigger undefined behavior.
453 /// Note that this currently only considers the basic block that is
455 bool programUndefinedIfFullPoison(const Instruction *PoisonI);
457 /// \brief Specific patterns of select instructions we can match.
458 enum SelectPatternFlavor {
460 SPF_SMIN, /// Signed minimum
461 SPF_UMIN, /// Unsigned minimum
462 SPF_SMAX, /// Signed maximum
463 SPF_UMAX, /// Unsigned maximum
464 SPF_FMINNUM, /// Floating point minnum
465 SPF_FMAXNUM, /// Floating point maxnum
466 SPF_ABS, /// Absolute value
467 SPF_NABS /// Negated absolute value
470 /// \brief Behavior when a floating point min/max is given one NaN and one
471 /// non-NaN as input.
472 enum SelectPatternNaNBehavior {
473 SPNB_NA = 0, /// NaN behavior not applicable.
474 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
475 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
476 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
477 /// it has been determined that no operands can
481 struct SelectPatternResult {
482 SelectPatternFlavor Flavor;
483 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
484 /// SPF_FMINNUM or SPF_FMAXNUM.
485 bool Ordered; /// When implementing this min/max pattern as
486 /// fcmp; select, does the fcmp have to be
489 /// \brief Return true if \p SPF is a min or a max pattern.
490 static bool isMinOrMax(SelectPatternFlavor SPF) {
491 return !(SPF == SPF_UNKNOWN || SPF == SPF_ABS || SPF == SPF_NABS);
495 /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
496 /// and providing the out parameter results if we successfully match.
498 /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
499 /// not match that of the original select. If this is the case, the cast
500 /// operation (one of Trunc,SExt,Zext) that must be done to transform the
501 /// type of LHS and RHS into the type of V is returned in CastOp.
504 /// %1 = icmp slt i32 %a, i32 4
505 /// %2 = sext i32 %a to i64
506 /// %3 = select i1 %1, i64 %2, i64 4
508 /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
510 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
511 Instruction::CastOps *CastOp = nullptr);
512 inline SelectPatternResult
513 matchSelectPattern(const Value *V, const Value *&LHS, const Value *&RHS,
514 Instruction::CastOps *CastOp = nullptr) {
515 Value *L = const_cast<Value*>(LHS);
516 Value *R = const_cast<Value*>(RHS);
517 auto Result = matchSelectPattern(const_cast<Value*>(V), L, R);
523 /// Return true if RHS is known to be implied true by LHS. Return false if
524 /// RHS is known to be implied false by LHS. Otherwise, return None if no
525 /// implication can be made.
526 /// A & B must be i1 (boolean) values or a vector of such values. Note that
527 /// the truth table for implication is the same as <=u on i1 values (but not
528 /// <=s!). The truth table for both is:
533 Optional<bool> isImpliedCondition(const Value *LHS, const Value *RHS,
534 const DataLayout &DL, bool LHSIsTrue = true,
536 } // end namespace llvm
538 #endif // LLVM_ANALYSIS_VALUETRACKING_H