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 /// Returns the known bits rather than passing by reference.
60 KnownBits computeKnownBits(const Value *V, const DataLayout &DL,
61 unsigned Depth = 0, AssumptionCache *AC = nullptr,
62 const Instruction *CxtI = nullptr,
63 const DominatorTree *DT = nullptr,
64 OptimizationRemarkEmitter *ORE = nullptr);
65 /// Compute known bits from the range metadata.
66 /// \p KnownZero the set of bits that are known to be zero
67 /// \p KnownOne the set of bits that are known to be one
68 void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
70 /// Return true if LHS and RHS have no common bits set.
71 bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
73 AssumptionCache *AC = nullptr,
74 const Instruction *CxtI = nullptr,
75 const DominatorTree *DT = nullptr);
77 /// Return true if the given value is known to have exactly one bit set when
78 /// defined. For vectors return true if every element is known to be a power
79 /// of two when defined. Supports values with integer or pointer type and
80 /// vectors of integers. If 'OrZero' is set, then return true if the given
81 /// value is either a power of two or zero.
82 bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
83 bool OrZero = false, unsigned Depth = 0,
84 AssumptionCache *AC = nullptr,
85 const Instruction *CxtI = nullptr,
86 const DominatorTree *DT = nullptr);
88 bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI);
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
225 // \p CharSize integers) and is indexing into this string.
226 bool isGEPBasedOnPointerToString(const GEPOperator *GEP,
227 unsigned CharSize = 8);
229 /// Represents offset+length into a ConstantDataArray.
230 struct ConstantDataArraySlice {
231 /// ConstantDataArray pointer. nullptr indicates a zeroinitializer (a valid
232 /// initializer, it just doesn't fit the ConstantDataArray interface).
233 const ConstantDataArray *Array;
234 /// Slice starts at this Offset.
236 /// Length of the slice.
239 /// Moves the Offset and adjusts Length accordingly.
240 void move(uint64_t Delta) {
241 assert(Delta < Length);
245 /// Convenience accessor for elements in the slice.
246 uint64_t operator[](unsigned I) const {
247 return Array==nullptr ? 0 : Array->getElementAsInteger(I + Offset);
251 /// Returns true if the value \p V is a pointer into a ContantDataArray.
252 /// If successful \p Index will point to a ConstantDataArray info object
253 /// with an appropriate offset.
254 bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice,
255 unsigned ElementSize, uint64_t Offset = 0);
257 /// This function computes the length of a null-terminated C string pointed to
258 /// by V. If successful, it returns true and returns the string in Str. If
259 /// unsuccessful, it returns false. This does not include the trailing null
260 /// character by default. If TrimAtNul is set to false, then this returns any
261 /// trailing null characters as well as any other characters that come after
263 bool getConstantStringInfo(const Value *V, StringRef &Str,
264 uint64_t Offset = 0, bool TrimAtNul = true);
266 /// If we can compute the length of the string pointed to by the specified
267 /// pointer, return 'len+1'. If we can't, return 0.
268 uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
270 /// This method strips off any GEP address adjustments and pointer casts from
271 /// the specified value, returning the original object being addressed. Note
272 /// that the returned value has pointer type if the specified value does. If
273 /// the MaxLookup value is non-zero, it limits the number of instructions to
275 Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
276 unsigned MaxLookup = 6);
277 static inline const Value *GetUnderlyingObject(const Value *V,
278 const DataLayout &DL,
279 unsigned MaxLookup = 6) {
280 return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
283 /// \brief This method is similar to GetUnderlyingObject except that it can
284 /// look through phi and select instructions and return multiple objects.
286 /// If LoopInfo is passed, loop phis are further analyzed. If a pointer
287 /// accesses different objects in each iteration, we don't look through the
288 /// phi node. E.g. consider this loop nest:
293 /// A[i][j] = A[i-1][j] * B[j]
296 /// This is transformed by Load-PRE to stash away A[i] for the next iteration
297 /// of the outer loop:
299 /// Curr = A[0]; // Prev_0
301 /// Prev = Curr; // Prev = PHI (Prev_0, Curr)
304 /// Curr[j] = Prev[j] * B[j]
308 /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
309 /// should not assume that Curr and Prev share the same underlying object thus
310 /// it shouldn't look through the phi above.
311 void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
312 const DataLayout &DL, LoopInfo *LI = nullptr,
313 unsigned MaxLookup = 6);
315 /// This is a wrapper around GetUnderlyingObjects and adds support for basic
316 /// ptrtoint+arithmetic+inttoptr sequences.
317 void getUnderlyingObjectsForCodeGen(const Value *V,
318 SmallVectorImpl<Value *> &Objects,
319 const DataLayout &DL);
321 /// Return true if the only users of this pointer are lifetime markers.
322 bool onlyUsedByLifetimeMarkers(const Value *V);
324 /// Return true if the instruction does not have any effects besides
325 /// calculating the result and does not have undefined behavior.
327 /// This method never returns true for an instruction that returns true for
328 /// mayHaveSideEffects; however, this method also does some other checks in
329 /// addition. It checks for undefined behavior, like dividing by zero or
330 /// loading from an invalid pointer (but not for undefined results, like a
331 /// shift with a shift amount larger than the width of the result). It checks
332 /// for malloc and alloca because speculatively executing them might cause a
333 /// memory leak. It also returns false for instructions related to control
334 /// flow, specifically terminators and PHI nodes.
336 /// If the CtxI is specified this method performs context-sensitive analysis
337 /// and returns true if it is safe to execute the instruction immediately
340 /// If the CtxI is NOT specified this method only looks at the instruction
341 /// itself and its operands, so if this method returns true, it is safe to
342 /// move the instruction as long as the correct dominance relationships for
343 /// the operands and users hold.
345 /// This method can return true for instructions that read memory;
346 /// for such instructions, moving them may change the resulting value.
347 bool isSafeToSpeculativelyExecute(const Value *V,
348 const Instruction *CtxI = nullptr,
349 const DominatorTree *DT = nullptr);
351 /// Returns true if the result or effects of the given instructions \p I
352 /// depend on or influence global memory.
353 /// Memory dependence arises for example if the instruction reads from
354 /// memory or may produce effects or undefined behaviour. Memory dependent
355 /// instructions generally cannot be reorderd with respect to other memory
356 /// dependent instructions or moved into non-dominated basic blocks.
357 /// Instructions which just compute a value based on the values of their
358 /// operands are not memory dependent.
359 bool mayBeMemoryDependent(const Instruction &I);
361 /// Return true if this pointer couldn't possibly be null by its definition.
362 /// This returns true for allocas, non-extern-weak globals, and byval
364 bool isKnownNonNull(const Value *V);
366 /// Return true if this pointer couldn't possibly be null. If the context
367 /// instruction and dominator tree are specified, perform context-sensitive
368 /// analysis and return true if the pointer couldn't possibly be null at the
369 /// specified instruction.
370 bool isKnownNonNullAt(const Value *V,
371 const Instruction *CtxI = nullptr,
372 const DominatorTree *DT = nullptr);
374 /// Return true if it is valid to use the assumptions provided by an
375 /// assume intrinsic, I, at the point in the control-flow identified by the
376 /// context instruction, CxtI.
377 bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
378 const DominatorTree *DT = nullptr);
380 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
469 /// \brief Behavior when a floating point min/max is given one NaN and one
470 /// non-NaN as input.
471 enum SelectPatternNaNBehavior {
472 SPNB_NA = 0, /// NaN behavior not applicable.
473 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
474 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
475 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
476 /// it has been determined that no operands can
479 struct SelectPatternResult {
480 SelectPatternFlavor Flavor;
481 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
482 /// SPF_FMINNUM or SPF_FMAXNUM.
483 bool Ordered; /// When implementing this min/max pattern as
484 /// fcmp; select, does the fcmp have to be
487 /// \brief Return true if \p SPF is a min or a max pattern.
488 static bool isMinOrMax(SelectPatternFlavor SPF) {
489 return !(SPF == SPF_UNKNOWN || SPF == SPF_ABS || SPF == SPF_NABS);
492 /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
493 /// and providing the out parameter results if we successfully match.
495 /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
496 /// not match that of the original select. If this is the case, the cast
497 /// operation (one of Trunc,SExt,Zext) that must be done to transform the
498 /// type of LHS and RHS into the type of V is returned in CastOp.
501 /// %1 = icmp slt i32 %a, i32 4
502 /// %2 = sext i32 %a to i64
503 /// %3 = select i1 %1, i64 %2, i64 4
505 /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
507 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
508 Instruction::CastOps *CastOp = nullptr);
509 static inline SelectPatternResult
510 matchSelectPattern(const Value *V, const Value *&LHS, const Value *&RHS,
511 Instruction::CastOps *CastOp = nullptr) {
512 Value *L = const_cast<Value*>(LHS);
513 Value *R = const_cast<Value*>(RHS);
514 auto Result = matchSelectPattern(const_cast<Value*>(V), L, R);
520 /// Return true if RHS is known to be implied true by LHS. Return false if
521 /// RHS is known to be implied false by LHS. Otherwise, return None if no
522 /// implication can be made.
523 /// A & B must be i1 (boolean) values or a vector of such values. Note that
524 /// the truth table for implication is the same as <=u on i1 values (but not
525 /// <=s!). The truth table for both is:
530 Optional<bool> isImpliedCondition(const Value *LHS, const Value *RHS,
531 const DataLayout &DL,
532 bool LHSIsFalse = false, unsigned Depth = 0,
533 AssumptionCache *AC = nullptr,
534 const Instruction *CxtI = nullptr,
535 const DominatorTree *DT = nullptr);
536 } // end namespace llvm