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/IR/ConstantRange.h"
20 #include "llvm/IR/Instruction.h"
21 #include "llvm/Support/DataTypes.h"
26 class AssumptionCache;
34 class TargetLibraryInfo;
37 /// Determine which bits of V are known to be either zero or one and return
38 /// them in the KnownZero/KnownOne bit sets.
40 /// This function is defined on values with integer type, values with pointer
41 /// type, and vectors of integers. In the case
42 /// where V is a vector, the known zero and known one values are the
43 /// same width as the vector element, and the bit is set only if it is true
44 /// for all of the elements in the vector.
45 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
46 const DataLayout &DL, unsigned Depth = 0,
47 AssumptionCache *AC = nullptr,
48 const Instruction *CxtI = nullptr,
49 const DominatorTree *DT = nullptr);
50 /// Compute known bits from the range metadata.
51 /// \p KnownZero the set of bits that are known to be zero
52 /// \p KnownOne the set of bits that are known to be one
53 void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
54 APInt &KnownZero, APInt &KnownOne);
55 /// Return true if LHS and RHS have no common bits set.
56 bool haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
57 AssumptionCache *AC = nullptr,
58 const Instruction *CxtI = nullptr,
59 const DominatorTree *DT = nullptr);
61 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
62 /// one. Convenience wrapper around computeKnownBits.
63 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
64 const DataLayout &DL, unsigned Depth = 0,
65 AssumptionCache *AC = nullptr,
66 const Instruction *CxtI = nullptr,
67 const DominatorTree *DT = nullptr);
69 /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have
70 /// exactly one bit set when defined. For vectors return true if every
71 /// element is known to be a power of two when defined. Supports values with
72 /// integer or pointer type and vectors of integers. If 'OrZero' is set then
73 /// return true if the given value is either a power of two or zero.
74 bool isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL,
75 bool OrZero = false, unsigned Depth = 0,
76 AssumptionCache *AC = nullptr,
77 const Instruction *CxtI = nullptr,
78 const DominatorTree *DT = nullptr);
80 /// isKnownNonZero - Return true if the given value is known to be non-zero
81 /// when defined. For vectors return true if every element is known to be
82 /// non-zero when defined. Supports values with integer or pointer type and
83 /// vectors of integers.
84 bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth = 0,
85 AssumptionCache *AC = nullptr,
86 const Instruction *CxtI = nullptr,
87 const DominatorTree *DT = nullptr);
89 /// Returns true if the give value is known to be non-negative.
90 bool isKnownNonNegative(Value *V, const DataLayout &DL, unsigned Depth = 0,
91 AssumptionCache *AC = nullptr,
92 const Instruction *CxtI = nullptr,
93 const DominatorTree *DT = nullptr);
95 /// isKnownNonEqual - Return true if the given values are known to be
96 /// non-equal when defined. Supports scalar integer types only.
97 bool isKnownNonEqual(Value *V1, Value *V2, const DataLayout &DL,
98 AssumptionCache *AC = nullptr,
99 const Instruction *CxtI = nullptr,
100 const DominatorTree *DT = nullptr);
102 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
103 /// this predicate to simplify operations downstream. Mask is known to be
104 /// zero for bits that V cannot have.
106 /// This function is defined on values with integer type, values with pointer
107 /// type, and vectors of integers. In the case
108 /// where V is a vector, the mask, known zero, and known one values are the
109 /// same width as the vector element, and the bit is set only if it is true
110 /// for all of the elements in the vector.
111 bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
112 unsigned Depth = 0, AssumptionCache *AC = nullptr,
113 const Instruction *CxtI = nullptr,
114 const DominatorTree *DT = nullptr);
116 /// ComputeNumSignBits - Return the number of times the sign bit of the
117 /// register is replicated into the other bits. We know that at least 1 bit
118 /// is always equal to the sign bit (itself), but other cases can give us
119 /// information. For example, immediately after an "ashr X, 2", we know that
120 /// the top 3 bits are all equal to each other, so we return 3.
122 /// 'Op' must have a scalar integer type.
124 unsigned ComputeNumSignBits(Value *Op, const DataLayout &DL,
125 unsigned Depth = 0, AssumptionCache *AC = nullptr,
126 const Instruction *CxtI = nullptr,
127 const DominatorTree *DT = nullptr);
129 /// ComputeMultiple - This function computes the integer multiple of Base that
130 /// equals V. If successful, it returns true and returns the multiple in
131 /// Multiple. If unsuccessful, it returns false. Also, if V can be
132 /// simplified to an integer, then the simplified V is returned in Val. Look
133 /// through sext only if LookThroughSExt=true.
134 bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
135 bool LookThroughSExt = false,
138 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
139 /// value is never equal to -0.0.
141 bool CannotBeNegativeZero(const Value *V, unsigned Depth = 0);
143 /// CannotBeOrderedLessThanZero - Return true if we can prove that the
144 /// specified FP value is either a NaN or never less than 0.0.
146 bool CannotBeOrderedLessThanZero(const Value *V, unsigned Depth = 0);
148 /// isBytewiseValue - If the specified value can be set by repeating the same
149 /// byte in memory, return the i8 value that it is represented with. This is
150 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
151 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
152 /// byte store (e.g. i16 0x1234), return null.
153 Value *isBytewiseValue(Value *V);
155 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
156 /// the scalar value indexed is already around as a register, for example if
157 /// it were inserted directly into the aggregrate.
159 /// If InsertBefore is not null, this function will duplicate (modified)
160 /// insertvalues when a part of a nested struct is extracted.
161 Value *FindInsertedValue(Value *V,
162 ArrayRef<unsigned> idx_range,
163 Instruction *InsertBefore = nullptr);
165 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
166 /// it can be expressed as a base pointer plus a constant offset. Return the
167 /// base and offset to the caller.
168 Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
169 const DataLayout &DL);
170 static inline const Value *
171 GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
172 const DataLayout &DL) {
173 return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
177 /// getConstantStringInfo - This function computes the length of a
178 /// null-terminated C string pointed to by V. If successful, it returns true
179 /// and returns the string in Str. If unsuccessful, it returns false. This
180 /// does not include the trailing nul character by default. If TrimAtNul is
181 /// set to false, then this returns any trailing nul characters as well as any
182 /// other characters that come after it.
183 bool getConstantStringInfo(const Value *V, StringRef &Str,
184 uint64_t Offset = 0, bool TrimAtNul = true);
186 /// GetStringLength - If we can compute the length of the string pointed to by
187 /// the specified pointer, return 'len+1'. If we can't, return 0.
188 uint64_t GetStringLength(Value *V);
190 /// GetUnderlyingObject - This method strips off any GEP address adjustments
191 /// and pointer casts from the specified value, returning the original object
192 /// being addressed. Note that the returned value has pointer type if the
193 /// specified value does. If the MaxLookup value is non-zero, it limits the
194 /// number of instructions to be stripped off.
195 Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
196 unsigned MaxLookup = 6);
197 static inline const Value *GetUnderlyingObject(const Value *V,
198 const DataLayout &DL,
199 unsigned MaxLookup = 6) {
200 return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
203 /// \brief This method is similar to GetUnderlyingObject except that it can
204 /// look through phi and select instructions and return multiple objects.
206 /// If LoopInfo is passed, loop phis are further analyzed. If a pointer
207 /// accesses different objects in each iteration, we don't look through the
208 /// phi node. E.g. consider this loop nest:
213 /// A[i][j] = A[i-1][j] * B[j]
216 /// This is transformed by Load-PRE to stash away A[i] for the next iteration
217 /// of the outer loop:
219 /// Curr = A[0]; // Prev_0
221 /// Prev = Curr; // Prev = PHI (Prev_0, Curr)
224 /// Curr[j] = Prev[j] * B[j]
228 /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
229 /// should not assume that Curr and Prev share the same underlying object thus
230 /// it shouldn't look through the phi above.
231 void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
232 const DataLayout &DL, LoopInfo *LI = nullptr,
233 unsigned MaxLookup = 6);
235 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
236 /// are lifetime markers.
237 bool onlyUsedByLifetimeMarkers(const Value *V);
239 /// isDereferenceablePointer - Return true if this is always a dereferenceable
240 /// pointer. If the context instruction is specified perform context-sensitive
241 /// analysis and return true if the pointer is dereferenceable at the
242 /// specified instruction.
243 bool isDereferenceablePointer(const Value *V, const DataLayout &DL,
244 const Instruction *CtxI = nullptr,
245 const DominatorTree *DT = nullptr,
246 const TargetLibraryInfo *TLI = nullptr);
248 /// Returns true if V is always a dereferenceable pointer with alignment
249 /// greater or equal than requested. If the context instruction is specified
250 /// performs context-sensitive analysis and returns true if the pointer is
251 /// dereferenceable at the specified instruction.
252 bool isDereferenceableAndAlignedPointer(const Value *V, unsigned Align,
253 const DataLayout &DL,
254 const Instruction *CtxI = nullptr,
255 const DominatorTree *DT = nullptr,
256 const TargetLibraryInfo *TLI = nullptr);
258 /// isSafeToSpeculativelyExecute - Return true if the instruction does not
259 /// have any effects besides calculating the result and does not have
260 /// undefined behavior.
262 /// This method never returns true for an instruction that returns true for
263 /// mayHaveSideEffects; however, this method also does some other checks in
264 /// addition. It checks for undefined behavior, like dividing by zero or
265 /// loading from an invalid pointer (but not for undefined results, like a
266 /// shift with a shift amount larger than the width of the result). It checks
267 /// for malloc and alloca because speculatively executing them might cause a
268 /// memory leak. It also returns false for instructions related to control
269 /// flow, specifically terminators and PHI nodes.
271 /// If the CtxI is specified this method performs context-sensitive analysis
272 /// and returns true if it is safe to execute the instruction immediately
275 /// If the CtxI is NOT specified this method only looks at the instruction
276 /// itself and its operands, so if this method returns true, it is safe to
277 /// move the instruction as long as the correct dominance relationships for
278 /// the operands and users hold.
280 /// This method can return true for instructions that read memory;
281 /// for such instructions, moving them may change the resulting value.
282 bool isSafeToSpeculativelyExecute(const Value *V,
283 const Instruction *CtxI = nullptr,
284 const DominatorTree *DT = nullptr,
285 const TargetLibraryInfo *TLI = nullptr);
287 /// Returns true if the result or effects of the given instructions \p I
288 /// depend on or influence global memory.
289 /// Memory dependence arises for example if the the instruction reads from
290 /// memory or may produce effects or undefined behaviour. Memory dependent
291 /// instructions generally cannot be reorderd with respect to other memory
292 /// dependent instructions or moved into non-dominated basic blocks.
293 /// Instructions which just compute a value based on the values of their
294 /// operands are not memory dependent.
295 bool mayBeMemoryDependent(const Instruction &I);
297 /// isKnownNonNull - Return true if this pointer couldn't possibly be null by
298 /// its definition. This returns true for allocas, non-extern-weak globals
299 /// and byval arguments.
300 bool isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI = nullptr);
302 /// isKnownNonNullAt - Return true if this pointer couldn't possibly be null.
303 /// If the context instruction is specified perform context-sensitive analysis
304 /// and return true if the pointer couldn't possibly be null at the specified
306 bool isKnownNonNullAt(const Value *V,
307 const Instruction *CtxI = nullptr,
308 const DominatorTree *DT = nullptr,
309 const TargetLibraryInfo *TLI = nullptr);
311 /// Return true if it is valid to use the assumptions provided by an
312 /// assume intrinsic, I, at the point in the control-flow identified by the
313 /// context instruction, CxtI.
314 bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
315 const DominatorTree *DT = nullptr);
317 enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
318 OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
319 const DataLayout &DL,
321 const Instruction *CxtI,
322 const DominatorTree *DT);
323 OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
324 const DataLayout &DL,
326 const Instruction *CxtI,
327 const DominatorTree *DT);
328 OverflowResult computeOverflowForSignedAdd(Value *LHS, Value *RHS,
329 const DataLayout &DL,
330 AssumptionCache *AC = nullptr,
331 const Instruction *CxtI = nullptr,
332 const DominatorTree *DT = nullptr);
333 /// This version also leverages the sign bit of Add if known.
334 OverflowResult computeOverflowForSignedAdd(AddOperator *Add,
335 const DataLayout &DL,
336 AssumptionCache *AC = nullptr,
337 const Instruction *CxtI = nullptr,
338 const DominatorTree *DT = nullptr);
340 /// Return true if this function can prove that the instruction I will
341 /// always transfer execution to one of its successors (including the next
342 /// instruction that follows within a basic block). E.g. this is not
343 /// guaranteed for function calls that could loop infinitely.
345 /// In other words, this function returns false for instructions that may
346 /// transfer execution or fail to transfer execution in a way that is not
347 /// captured in the CFG nor in the sequence of instructions within a basic
350 /// Undefined behavior is assumed not to happen, so e.g. division is
351 /// guaranteed to transfer execution to the following instruction even
352 /// though division by zero might cause undefined behavior.
353 bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
355 /// Return true if this function can prove that the instruction I
356 /// is executed for every iteration of the loop L.
358 /// Note that this currently only considers the loop header.
359 bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
362 /// Return true if this function can prove that I is guaranteed to yield
363 /// full-poison (all bits poison) if at least one of its operands are
364 /// full-poison (all bits poison).
366 /// The exact rules for how poison propagates through instructions have
367 /// not been settled as of 2015-07-10, so this function is conservative
368 /// and only considers poison to be propagated in uncontroversial
369 /// cases. There is no attempt to track values that may be only partially
371 bool propagatesFullPoison(const Instruction *I);
373 /// Return either nullptr or an operand of I such that I will trigger
374 /// undefined behavior if I is executed and that operand has a full-poison
375 /// value (all bits poison).
376 const Value *getGuaranteedNonFullPoisonOp(const Instruction *I);
378 /// Return true if this function can prove that if PoisonI is executed
379 /// and yields a full-poison value (all bits poison), then that will
380 /// trigger undefined behavior.
382 /// Note that this currently only considers the basic block that is
384 bool isKnownNotFullPoison(const Instruction *PoisonI);
386 /// \brief Specific patterns of select instructions we can match.
387 enum SelectPatternFlavor {
389 SPF_SMIN, /// Signed minimum
390 SPF_UMIN, /// Unsigned minimum
391 SPF_SMAX, /// Signed maximum
392 SPF_UMAX, /// Unsigned maximum
393 SPF_FMINNUM, /// Floating point minnum
394 SPF_FMAXNUM, /// Floating point maxnum
395 SPF_ABS, /// Absolute value
396 SPF_NABS /// Negated absolute value
398 /// \brief Behavior when a floating point min/max is given one NaN and one
399 /// non-NaN as input.
400 enum SelectPatternNaNBehavior {
401 SPNB_NA = 0, /// NaN behavior not applicable.
402 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
403 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
404 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
405 /// it has been determined that no operands can
408 struct SelectPatternResult {
409 SelectPatternFlavor Flavor;
410 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
411 /// SPF_FMINNUM or SPF_FMAXNUM.
412 bool Ordered; /// When implementing this min/max pattern as
413 /// fcmp; select, does the fcmp have to be
416 /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
417 /// and providing the out parameter results if we successfully match.
419 /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
420 /// not match that of the original select. If this is the case, the cast
421 /// operation (one of Trunc,SExt,Zext) that must be done to transform the
422 /// type of LHS and RHS into the type of V is returned in CastOp.
425 /// %1 = icmp slt i32 %a, i32 4
426 /// %2 = sext i32 %a to i64
427 /// %3 = select i1 %1, i64 %2, i64 4
429 /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
431 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
432 Instruction::CastOps *CastOp = nullptr);
434 /// Parse out a conservative ConstantRange from !range metadata.
436 /// E.g. if RangeMD is !{i32 0, i32 10, i32 15, i32 20} then return [0, 20).
437 ConstantRange getConstantRangeFromMetadata(MDNode &RangeMD);
439 /// Return true if RHS is known to be implied by LHS. A & B must be i1
440 /// (boolean) values or a vector of such values. Note that the truth table for
441 /// implication is the same as <=u on i1 values (but not <=s!). The truth
442 /// table for both is:
447 bool isImpliedCondition(Value *LHS, Value *RHS, const DataLayout &DL,
448 unsigned Depth = 0, AssumptionCache *AC = nullptr,
449 const Instruction *CxtI = nullptr,
450 const DominatorTree *DT = nullptr);
451 } // end namespace llvm