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