LLVM 17.0.0git
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/SmallSet.h"
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/InstrTypes.h"
22#include "llvm/IR/Intrinsics.h"
23#include <cassert>
24#include <cstdint>
25
26namespace llvm {
27
28class Operator;
29class AddOperator;
30class AllocaInst;
31class APInt;
32class AssumptionCache;
33class DominatorTree;
34class GEPOperator;
35class LoadInst;
36class WithOverflowInst;
37struct KnownBits;
38class Loop;
39class LoopInfo;
40class MDNode;
41class OptimizationRemarkEmitter;
42class StringRef;
43class TargetLibraryInfo;
44class Value;
45
46constexpr unsigned MaxAnalysisRecursionDepth = 6;
47
48/// Determine which bits of V are known to be either zero or one and return
49/// them in the KnownZero/KnownOne bit sets.
50///
51/// This function is defined on values with integer type, values with pointer
52/// type, and vectors of integers. In the case
53/// where V is a vector, the known zero and known one values are the
54/// same width as the vector element, and the bit is set only if it is true
55/// for all of the elements in the vector.
56void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL,
57 unsigned Depth = 0, AssumptionCache *AC = nullptr,
58 const Instruction *CxtI = nullptr,
59 const DominatorTree *DT = nullptr,
60 OptimizationRemarkEmitter *ORE = nullptr,
61 bool UseInstrInfo = true);
62
63/// Determine which bits of V are known to be either zero or one and return
64/// them in the KnownZero/KnownOne bit sets.
65///
66/// This function is defined on values with integer type, values with pointer
67/// type, and vectors of integers. In the case
68/// where V is a vector, the known zero and known one values are the
69/// same width as the vector element, and the bit is set only if it is true
70/// for all of the demanded elements in the vector.
71void computeKnownBits(const Value *V, const APInt &DemandedElts,
72 KnownBits &Known, const DataLayout &DL,
73 unsigned Depth = 0, AssumptionCache *AC = nullptr,
74 const Instruction *CxtI = nullptr,
75 const DominatorTree *DT = nullptr,
76 OptimizationRemarkEmitter *ORE = nullptr,
77 bool UseInstrInfo = true);
78
79/// Returns the known bits rather than passing by reference.
81 unsigned Depth = 0, AssumptionCache *AC = nullptr,
82 const Instruction *CxtI = nullptr,
83 const DominatorTree *DT = nullptr,
84 OptimizationRemarkEmitter *ORE = nullptr,
85 bool UseInstrInfo = true);
86
87/// Returns the known bits rather than passing by reference.
88KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
89 const DataLayout &DL, unsigned Depth = 0,
90 AssumptionCache *AC = nullptr,
91 const Instruction *CxtI = nullptr,
92 const DominatorTree *DT = nullptr,
93 OptimizationRemarkEmitter *ORE = nullptr,
94 bool UseInstrInfo = true);
95
96/// Compute known bits from the range metadata.
97/// \p KnownZero the set of bits that are known to be zero
98/// \p KnownOne the set of bits that are known to be one
99void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known);
100
101/// Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
103 const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS,
104 unsigned Depth, const DataLayout &DL, AssumptionCache *AC = nullptr,
105 const Instruction *CxtI = nullptr, const DominatorTree *DT = nullptr,
106 OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true);
107
108/// Return true if LHS and RHS have no common bits set.
109bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
110 const DataLayout &DL, AssumptionCache *AC = nullptr,
111 const Instruction *CxtI = nullptr,
112 const DominatorTree *DT = nullptr,
113 bool UseInstrInfo = true);
114
115/// Return true if the given value is known to have exactly one bit set when
116/// defined. For vectors return true if every element is known to be a power
117/// of two when defined. Supports values with integer or pointer type and
118/// vectors of integers. If 'OrZero' is set, then return true if the given
119/// value is either a power of two or zero.
120bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
121 bool OrZero = false, unsigned Depth = 0,
122 AssumptionCache *AC = nullptr,
123 const Instruction *CxtI = nullptr,
124 const DominatorTree *DT = nullptr,
125 bool UseInstrInfo = true);
126
128
129/// Return true if the given value is known to be non-zero when defined. For
130/// vectors, return true if every element is known to be non-zero when
131/// defined. For pointers, if the context instruction and dominator tree are
132/// specified, perform context-sensitive analysis and return true if the
133/// pointer couldn't possibly be null at the specified instruction.
134/// Supports values with integer or pointer type and vectors of integers.
135bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth = 0,
136 AssumptionCache *AC = nullptr,
137 const Instruction *CxtI = nullptr,
138 const DominatorTree *DT = nullptr,
139 bool UseInstrInfo = true);
140
141/// Return true if the two given values are negation.
142/// Currently can recoginze Value pair:
143/// 1: <X, Y> if X = sub (0, Y) or Y = sub (0, X)
144/// 2: <X, Y> if X = sub (A, B) and Y = sub (B, A)
145bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW = false);
146
147/// Returns true if the give value is known to be non-negative.
148bool isKnownNonNegative(const Value *V, const DataLayout &DL,
149 unsigned Depth = 0, AssumptionCache *AC = nullptr,
150 const Instruction *CxtI = nullptr,
151 const DominatorTree *DT = nullptr,
152 bool UseInstrInfo = true);
153
154/// Returns true if the given value is known be positive (i.e. non-negative
155/// and non-zero).
156bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth = 0,
157 AssumptionCache *AC = nullptr,
158 const Instruction *CxtI = nullptr,
159 const DominatorTree *DT = nullptr,
160 bool UseInstrInfo = true);
161
162/// Returns true if the given value is known be negative (i.e. non-positive
163/// and non-zero).
164bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth = 0,
165 AssumptionCache *AC = nullptr,
166 const Instruction *CxtI = nullptr,
167 const DominatorTree *DT = nullptr,
168 bool UseInstrInfo = true);
169
170/// Return true if the given values are known to be non-equal when defined.
171/// Supports scalar integer types only.
172bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL,
173 AssumptionCache *AC = nullptr,
174 const Instruction *CxtI = nullptr,
175 const DominatorTree *DT = nullptr,
176 bool UseInstrInfo = true);
177
178/// Return true if 'V & Mask' is known to be zero. We use this predicate to
179/// simplify operations downstream. Mask is known to be zero for bits that V
180/// cannot have.
181///
182/// This function is defined on values with integer type, values with pointer
183/// type, and vectors of integers. In the case
184/// where V is a vector, the mask, known zero, and known one values are the
185/// same width as the vector element, and the bit is set only if it is true
186/// for all of the elements in the vector.
187bool MaskedValueIsZero(const Value *V, const APInt &Mask, const DataLayout &DL,
188 unsigned Depth = 0, AssumptionCache *AC = nullptr,
189 const Instruction *CxtI = nullptr,
190 const DominatorTree *DT = nullptr,
191 bool UseInstrInfo = true);
192
193/// Return the number of times the sign bit of the register is replicated into
194/// the other bits. We know that at least 1 bit is always equal to the sign
195/// bit (itself), but other cases can give us information. For example,
196/// immediately after an "ashr X, 2", we know that the top 3 bits are all
197/// equal to each other, so we return 3. For vectors, return the number of
198/// sign bits for the vector element with the mininum number of known sign
199/// bits.
200unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL,
201 unsigned Depth = 0, AssumptionCache *AC = nullptr,
202 const Instruction *CxtI = nullptr,
203 const DominatorTree *DT = nullptr,
204 bool UseInstrInfo = true);
205
206/// Get the upper bound on bit size for this Value \p Op as a signed integer.
207/// i.e. x == sext(trunc(x to MaxSignificantBits) to bitwidth(x)).
208/// Similar to the APInt::getSignificantBits function.
209unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL,
210 unsigned Depth = 0,
211 AssumptionCache *AC = nullptr,
212 const Instruction *CxtI = nullptr,
213 const DominatorTree *DT = nullptr);
214
215/// Map a call instruction to an intrinsic ID. Libcalls which have equivalent
216/// intrinsics are treated as-if they were intrinsics.
218 const TargetLibraryInfo *TLI);
219
220/// Returns a pair of values, which if passed to llvm.is.fpclass, returns the
221/// same result as an fcmp with the given operands.
222///
223/// If \p LookThroughSrc is true, consider the input value when computing the
224/// mask.
225///
226/// If \p LookThroughSrc is false, ignore the source value (i.e. the first pair
227/// element will always be LHS.
228std::pair<Value *, FPClassTest> fcmpToClassTest(CmpInst::Predicate Pred,
229 const Function &F, Value *LHS,
230 Value *RHS,
231 bool LookThroughSrc = true);
232
234 /// Floating-point classes the value could be one of.
236
237 /// std::nullopt if the sign bit is unknown, true if the sign bit is
238 /// definitely set or false if the sign bit is definitely unset.
239 std::optional<bool> SignBit;
240
242 KnownFPClasses = KnownFPClasses | RHS.KnownFPClasses;
243
244 if (SignBit != RHS.SignBit)
245 SignBit = std::nullopt;
246 return *this;
247 }
248
249 void knownNot(FPClassTest RuleOut) {
250 KnownFPClasses = KnownFPClasses & ~RuleOut;
251 }
252
253 void fneg() {
255 if (SignBit)
256 SignBit = !*SignBit;
257 }
258
259 void fabs() {
261 SignBit = false;
262 }
263
264 /// Assume the sign bit is zero.
268 SignBit = false;
269 }
270
271 void copysign(const KnownFPClass &Sign) {
272 // Start assuming nothing about the sign.
273 SignBit = Sign.SignBit;
274 if (!SignBit)
275 return;
276
277 if (*SignBit)
279 else
281 }
282
283 void resetAll() { *this = KnownFPClass(); }
284};
285
287 LHS |= RHS;
288 return LHS;
289}
290
292 RHS |= LHS;
293 return std::move(RHS);
294}
295
296/// Determine which floating-point classes are valid for \p V, and return them
297/// in KnownFPClass bit sets.
298///
299/// This function is defined on values with floating-point type, values vectors
300/// of floating-point type, and arrays of floating-point type.
301
302/// \p InterestedClasses is a compile time optimization hint for which floating
303/// point classes should be queried. Queries not specified in \p
304/// InterestedClasses should be reliable if they are determined during the
305/// query.
306KnownFPClass computeKnownFPClass(
307 const Value *V, const APInt &DemandedElts, const DataLayout &DL,
308 FPClassTest InterestedClasses = fcAllFlags, unsigned Depth = 0,
309 const TargetLibraryInfo *TLI = nullptr, AssumptionCache *AC = nullptr,
310 const Instruction *CxtI = nullptr, const DominatorTree *DT = nullptr,
311 OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true);
312
313KnownFPClass computeKnownFPClass(
314 const Value *V, const DataLayout &DL,
315 FPClassTest InterestedClasses = fcAllFlags, unsigned Depth = 0,
316 const TargetLibraryInfo *TLI = nullptr, AssumptionCache *AC = nullptr,
317 const Instruction *CxtI = nullptr, const DominatorTree *DT = nullptr,
318 OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true);
319
320/// Return true if we can prove that the specified FP value is never equal to
321/// -0.0.
322bool CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
323 unsigned Depth = 0);
324
325/// Return true if we can prove that the specified FP value is either NaN or
326/// never less than -0.0.
327///
328/// NaN --> true
329/// +0 --> true
330/// -0 --> true
331/// x > +0 --> true
332/// x < -0 --> false
333bool CannotBeOrderedLessThanZero(const Value *V, const TargetLibraryInfo *TLI);
334
335/// Return true if the floating-point scalar value is not an infinity or if
336/// the floating-point vector value has no infinities. Return false if a value
337/// could ever be infinity.
338bool isKnownNeverInfinity(const Value *V, const TargetLibraryInfo *TLI,
339 unsigned Depth = 0);
340
341/// Return true if the floating-point scalar value is not a NaN or if the
342/// floating-point vector value has no NaN elements. Return false if a value
343/// could ever be NaN.
344bool isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
345 unsigned Depth = 0);
346
347/// Return true if we can prove that the specified FP value's sign bit is 0.
348///
349/// NaN --> true/false (depending on the NaN's sign bit)
350/// +0 --> true
351/// -0 --> false
352/// x > +0 --> true
353/// x < -0 --> false
354bool SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI);
355
356/// If the specified value can be set by repeating the same byte in memory,
357/// return the i8 value that it is represented with. This is true for all i8
358/// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
359/// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
360/// i16 0x1234), return null. If the value is entirely undef and padding,
361/// return undef.
362Value *isBytewiseValue(Value *V, const DataLayout &DL);
363
364/// Given an aggregate and an sequence of indices, see if the scalar value
365/// indexed is already around as a register, for example if it were inserted
366/// directly into the aggregate.
367///
368/// If InsertBefore is not null, this function will duplicate (modified)
369/// insertvalues when a part of a nested struct is extracted.
370Value *FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
371 Instruction *InsertBefore = nullptr);
372
373/// Analyze the specified pointer to see if it can be expressed as a base
374/// pointer plus a constant offset. Return the base and offset to the caller.
375///
376/// This is a wrapper around Value::stripAndAccumulateConstantOffsets that
377/// creates and later unpacks the required APInt.
379 const DataLayout &DL,
380 bool AllowNonInbounds = true) {
381 APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
382 Value *Base =
383 Ptr->stripAndAccumulateConstantOffsets(DL, OffsetAPInt, AllowNonInbounds);
384
385 Offset = OffsetAPInt.getSExtValue();
386 return Base;
387}
388inline const Value *
390 const DataLayout &DL,
391 bool AllowNonInbounds = true) {
392 return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset, DL,
393 AllowNonInbounds);
394}
395
396/// Returns true if the GEP is based on a pointer to a string (array of
397// \p CharSize integers) and is indexing into this string.
398bool isGEPBasedOnPointerToString(const GEPOperator *GEP, unsigned CharSize = 8);
399
400/// Represents offset+length into a ConstantDataArray.
402 /// ConstantDataArray pointer. nullptr indicates a zeroinitializer (a valid
403 /// initializer, it just doesn't fit the ConstantDataArray interface).
405
406 /// Slice starts at this Offset.
408
409 /// Length of the slice.
411
412 /// Moves the Offset and adjusts Length accordingly.
413 void move(uint64_t Delta) {
414 assert(Delta < Length);
415 Offset += Delta;
416 Length -= Delta;
417 }
418
419 /// Convenience accessor for elements in the slice.
420 uint64_t operator[](unsigned I) const {
421 return Array == nullptr ? 0 : Array->getElementAsInteger(I + Offset);
422 }
423};
424
425/// Returns true if the value \p V is a pointer into a ConstantDataArray.
426/// If successful \p Slice will point to a ConstantDataArray info object
427/// with an appropriate offset.
428bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice,
429 unsigned ElementSize, uint64_t Offset = 0);
430
431/// This function computes the length of a null-terminated C string pointed to
432/// by V. If successful, it returns true and returns the string in Str. If
433/// unsuccessful, it returns false. This does not include the trailing null
434/// character by default. If TrimAtNul is set to false, then this returns any
435/// trailing null characters as well as any other characters that come after
436/// it.
437bool getConstantStringInfo(const Value *V, StringRef &Str,
438 bool TrimAtNul = true);
439
440/// If we can compute the length of the string pointed to by the specified
441/// pointer, return 'len+1'. If we can't, return 0.
442uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
443
444/// This function returns call pointer argument that is considered the same by
445/// aliasing rules. You CAN'T use it to replace one value with another. If
446/// \p MustPreserveNullness is true, the call must preserve the nullness of
447/// the pointer.
448const Value *getArgumentAliasingToReturnedPointer(const CallBase *Call,
449 bool MustPreserveNullness);
451 bool MustPreserveNullness) {
452 return const_cast<Value *>(getArgumentAliasingToReturnedPointer(
453 const_cast<const CallBase *>(Call), MustPreserveNullness));
454}
455
456/// {launder,strip}.invariant.group returns pointer that aliases its argument,
457/// and it only captures pointer by returning it.
458/// These intrinsics are not marked as nocapture, because returning is
459/// considered as capture. The arguments are not marked as returned neither,
460/// because it would make it useless. If \p MustPreserveNullness is true,
461/// the intrinsic must preserve the nullness of the pointer.
463 const CallBase *Call, bool MustPreserveNullness);
464
465/// This method strips off any GEP address adjustments and pointer casts from
466/// the specified value, returning the original object being addressed. Note
467/// that the returned value has pointer type if the specified value does. If
468/// the MaxLookup value is non-zero, it limits the number of instructions to
469/// be stripped off.
470const Value *getUnderlyingObject(const Value *V, unsigned MaxLookup = 6);
471inline Value *getUnderlyingObject(Value *V, unsigned MaxLookup = 6) {
472 // Force const to avoid infinite recursion.
473 const Value *VConst = V;
474 return const_cast<Value *>(getUnderlyingObject(VConst, MaxLookup));
475}
476
477/// This method is similar to getUnderlyingObject except that it can
478/// look through phi and select instructions and return multiple objects.
479///
480/// If LoopInfo is passed, loop phis are further analyzed. If a pointer
481/// accesses different objects in each iteration, we don't look through the
482/// phi node. E.g. consider this loop nest:
483///
484/// int **A;
485/// for (i)
486/// for (j) {
487/// A[i][j] = A[i-1][j] * B[j]
488/// }
489///
490/// This is transformed by Load-PRE to stash away A[i] for the next iteration
491/// of the outer loop:
492///
493/// Curr = A[0]; // Prev_0
494/// for (i: 1..N) {
495/// Prev = Curr; // Prev = PHI (Prev_0, Curr)
496/// Curr = A[i];
497/// for (j: 0..N) {
498/// Curr[j] = Prev[j] * B[j]
499/// }
500/// }
501///
502/// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
503/// should not assume that Curr and Prev share the same underlying object thus
504/// it shouldn't look through the phi above.
505void getUnderlyingObjects(const Value *V,
506 SmallVectorImpl<const Value *> &Objects,
507 LoopInfo *LI = nullptr, unsigned MaxLookup = 6);
508
509/// This is a wrapper around getUnderlyingObjects and adds support for basic
510/// ptrtoint+arithmetic+inttoptr sequences.
511bool getUnderlyingObjectsForCodeGen(const Value *V,
512 SmallVectorImpl<Value *> &Objects);
513
514/// Returns unique alloca where the value comes from, or nullptr.
515/// If OffsetZero is true check that V points to the begining of the alloca.
516AllocaInst *findAllocaForValue(Value *V, bool OffsetZero = false);
517inline const AllocaInst *findAllocaForValue(const Value *V,
518 bool OffsetZero = false) {
519 return findAllocaForValue(const_cast<Value *>(V), OffsetZero);
520}
521
522/// Return true if the only users of this pointer are lifetime markers.
523bool onlyUsedByLifetimeMarkers(const Value *V);
524
525/// Return true if the only users of this pointer are lifetime markers or
526/// droppable instructions.
528
529/// Return true if speculation of the given load must be suppressed to avoid
530/// ordering or interfering with an active sanitizer. If not suppressed,
531/// dereferenceability and alignment must be proven separately. Note: This
532/// is only needed for raw reasoning; if you use the interface below
533/// (isSafeToSpeculativelyExecute), this is handled internally.
534bool mustSuppressSpeculation(const LoadInst &LI);
535
536/// Return true if the instruction does not have any effects besides
537/// calculating the result and does not have undefined behavior.
538///
539/// This method never returns true for an instruction that returns true for
540/// mayHaveSideEffects; however, this method also does some other checks in
541/// addition. It checks for undefined behavior, like dividing by zero or
542/// loading from an invalid pointer (but not for undefined results, like a
543/// shift with a shift amount larger than the width of the result). It checks
544/// for malloc and alloca because speculatively executing them might cause a
545/// memory leak. It also returns false for instructions related to control
546/// flow, specifically terminators and PHI nodes.
547///
548/// If the CtxI is specified this method performs context-sensitive analysis
549/// and returns true if it is safe to execute the instruction immediately
550/// before the CtxI.
551///
552/// If the CtxI is NOT specified this method only looks at the instruction
553/// itself and its operands, so if this method returns true, it is safe to
554/// move the instruction as long as the correct dominance relationships for
555/// the operands and users hold.
556///
557/// This method can return true for instructions that read memory;
558/// for such instructions, moving them may change the resulting value.
559bool isSafeToSpeculativelyExecute(const Instruction *I,
560 const Instruction *CtxI = nullptr,
561 AssumptionCache *AC = nullptr,
562 const DominatorTree *DT = nullptr,
563 const TargetLibraryInfo *TLI = nullptr);
564
565/// This returns the same result as isSafeToSpeculativelyExecute if Opcode is
566/// the actual opcode of Inst. If the provided and actual opcode differ, the
567/// function (virtually) overrides the opcode of Inst with the provided
568/// Opcode. There are come constraints in this case:
569/// * If Opcode has a fixed number of operands (eg, as binary operators do),
570/// then Inst has to have at least as many leading operands. The function
571/// will ignore all trailing operands beyond that number.
572/// * If Opcode allows for an arbitrary number of operands (eg, as CallInsts
573/// do), then all operands are considered.
574/// * The virtual instruction has to satisfy all typing rules of the provided
575/// Opcode.
576/// * This function is pessimistic in the following sense: If one actually
577/// materialized the virtual instruction, then isSafeToSpeculativelyExecute
578/// may say that the materialized instruction is speculatable whereas this
579/// function may have said that the instruction wouldn't be speculatable.
580/// This behavior is a shortcoming in the current implementation and not
581/// intentional.
583 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI = nullptr,
584 AssumptionCache *AC = nullptr, const DominatorTree *DT = nullptr,
585 const TargetLibraryInfo *TLI = nullptr);
586
587/// Returns true if the result or effects of the given instructions \p I
588/// depend values not reachable through the def use graph.
589/// * Memory dependence arises for example if the instruction reads from
590/// memory or may produce effects or undefined behaviour. Memory dependent
591/// instructions generally cannot be reorderd with respect to other memory
592/// dependent instructions.
593/// * Control dependence arises for example if the instruction may fault
594/// if lifted above a throwing call or infinite loop.
595bool mayHaveNonDefUseDependency(const Instruction &I);
596
597/// Return true if it is an intrinsic that cannot be speculated but also
598/// cannot trap.
599bool isAssumeLikeIntrinsic(const Instruction *I);
600
601/// Return true if it is valid to use the assumptions provided by an
602/// assume intrinsic, I, at the point in the control-flow identified by the
603/// context instruction, CxtI.
604bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
605 const DominatorTree *DT = nullptr);
606
607enum class OverflowResult {
608 /// Always overflows in the direction of signed/unsigned min value.
610 /// Always overflows in the direction of signed/unsigned max value.
612 /// May or may not overflow.
614 /// Never overflows.
616};
617
618OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS,
619 const DataLayout &DL,
620 AssumptionCache *AC,
621 const Instruction *CxtI,
622 const DominatorTree *DT,
623 bool UseInstrInfo = true);
624OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
625 const DataLayout &DL,
626 AssumptionCache *AC,
627 const Instruction *CxtI,
628 const DominatorTree *DT,
629 bool UseInstrInfo = true);
630OverflowResult computeOverflowForUnsignedAdd(const Value *LHS, const Value *RHS,
631 const DataLayout &DL,
632 AssumptionCache *AC,
633 const Instruction *CxtI,
634 const DominatorTree *DT,
635 bool UseInstrInfo = true);
636OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS,
637 const DataLayout &DL,
638 AssumptionCache *AC = nullptr,
639 const Instruction *CxtI = nullptr,
640 const DominatorTree *DT = nullptr);
641/// This version also leverages the sign bit of Add if known.
643 const DataLayout &DL,
644 AssumptionCache *AC = nullptr,
645 const Instruction *CxtI = nullptr,
646 const DominatorTree *DT = nullptr);
647OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS,
648 const DataLayout &DL,
649 AssumptionCache *AC,
650 const Instruction *CxtI,
651 const DominatorTree *DT);
652OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
653 const DataLayout &DL,
654 AssumptionCache *AC,
655 const Instruction *CxtI,
656 const DominatorTree *DT);
657
658/// Returns true if the arithmetic part of the \p WO 's result is
659/// used only along the paths control dependent on the computation
660/// not overflowing, \p WO being an <op>.with.overflow intrinsic.
661bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
662 const DominatorTree &DT);
663
664/// Determine the possible constant range of vscale with the given bit width,
665/// based on the vscale_range function attribute.
666ConstantRange getVScaleRange(const Function *F, unsigned BitWidth);
667
668/// Determine the possible constant range of an integer or vector of integer
669/// value. This is intended as a cheap, non-recursive check.
670ConstantRange computeConstantRange(const Value *V, bool ForSigned,
671 bool UseInstrInfo = true,
672 AssumptionCache *AC = nullptr,
673 const Instruction *CtxI = nullptr,
674 const DominatorTree *DT = nullptr,
675 unsigned Depth = 0);
676
677/// Return true if this function can prove that the instruction I will
678/// always transfer execution to one of its successors (including the next
679/// instruction that follows within a basic block). E.g. this is not
680/// guaranteed for function calls that could loop infinitely.
681///
682/// In other words, this function returns false for instructions that may
683/// transfer execution or fail to transfer execution in a way that is not
684/// captured in the CFG nor in the sequence of instructions within a basic
685/// block.
686///
687/// Undefined behavior is assumed not to happen, so e.g. division is
688/// guaranteed to transfer execution to the following instruction even
689/// though division by zero might cause undefined behavior.
690bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
691
692/// Returns true if this block does not contain a potential implicit exit.
693/// This is equivelent to saying that all instructions within the basic block
694/// are guaranteed to transfer execution to their successor within the basic
695/// block. This has the same assumptions w.r.t. undefined behavior as the
696/// instruction variant of this function.
697bool isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB);
698
699/// Return true if every instruction in the range (Begin, End) is
700/// guaranteed to transfer execution to its static successor. \p ScanLimit
701/// bounds the search to avoid scanning huge blocks.
704 unsigned ScanLimit = 32);
705
706/// Same as previous, but with range expressed via iterator_range.
708 iterator_range<BasicBlock::const_iterator> Range, unsigned ScanLimit = 32);
709
710/// Return true if this function can prove that the instruction I
711/// is executed for every iteration of the loop L.
712///
713/// Note that this currently only considers the loop header.
714bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
715 const Loop *L);
716
717/// Return true if \p PoisonOp's user yields poison or raises UB if its
718/// operand \p PoisonOp is poison.
719///
720/// If \p PoisonOp is a vector or an aggregate and the operation's result is a
721/// single value, any poison element in /p PoisonOp should make the result
722/// poison or raise UB.
723///
724/// To filter out operands that raise UB on poison, you can use
725/// getGuaranteedNonPoisonOp.
726bool propagatesPoison(const Use &PoisonOp);
727
728/// Insert operands of I into Ops such that I will trigger undefined behavior
729/// if I is executed and that operand has a poison value.
730void getGuaranteedNonPoisonOps(const Instruction *I,
731 SmallVectorImpl<const Value *> &Ops);
732
733/// Insert operands of I into Ops such that I will trigger undefined behavior
734/// if I is executed and that operand is not a well-defined value
735/// (i.e. has undef bits or poison).
736void getGuaranteedWellDefinedOps(const Instruction *I,
737 SmallVectorImpl<const Value *> &Ops);
738
739/// Return true if the given instruction must trigger undefined behavior
740/// when I is executed with any operands which appear in KnownPoison holding
741/// a poison value at the point of execution.
742bool mustTriggerUB(const Instruction *I,
743 const SmallSet<const Value *, 16> &KnownPoison);
744
745/// Return true if this function can prove that if Inst is executed
746/// and yields a poison value or undef bits, then that will trigger
747/// undefined behavior.
748///
749/// Note that this currently only considers the basic block that is
750/// the parent of Inst.
751bool programUndefinedIfUndefOrPoison(const Instruction *Inst);
752bool programUndefinedIfPoison(const Instruction *Inst);
753
754/// canCreateUndefOrPoison returns true if Op can create undef or poison from
755/// non-undef & non-poison operands.
756/// For vectors, canCreateUndefOrPoison returns true if there is potential
757/// poison or undef in any element of the result when vectors without
758/// undef/poison poison are given as operands.
759/// For example, given `Op = shl <2 x i32> %x, <0, 32>`, this function returns
760/// true. If Op raises immediate UB but never creates poison or undef
761/// (e.g. sdiv I, 0), canCreatePoison returns false.
762///
763/// \p ConsiderFlagsAndMetadata controls whether poison producing flags and
764/// metadata on the instruction are considered. This can be used to see if the
765/// instruction could still introduce undef or poison even without poison
766/// generating flags and metadata which might be on the instruction.
767/// (i.e. could the result of Op->dropPoisonGeneratingFlags() still create
768/// poison or undef)
769///
770/// canCreatePoison returns true if Op can create poison from non-poison
771/// operands.
772bool canCreateUndefOrPoison(const Operator *Op,
773 bool ConsiderFlagsAndMetadata = true);
774bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata = true);
775
776/// Return true if V is poison given that ValAssumedPoison is already poison.
777/// For example, if ValAssumedPoison is `icmp X, 10` and V is `icmp X, 5`,
778/// impliesPoison returns true.
779bool impliesPoison(const Value *ValAssumedPoison, const Value *V);
780
781/// Return true if this function can prove that V does not have undef bits
782/// and is never poison. If V is an aggregate value or vector, check whether
783/// all elements (except padding) are not undef or poison.
784/// Note that this is different from canCreateUndefOrPoison because the
785/// function assumes Op's operands are not poison/undef.
786///
787/// If CtxI and DT are specified this method performs flow-sensitive analysis
788/// and returns true if it is guaranteed to be never undef or poison
789/// immediately before the CtxI.
790bool isGuaranteedNotToBeUndefOrPoison(const Value *V,
791 AssumptionCache *AC = nullptr,
792 const Instruction *CtxI = nullptr,
793 const DominatorTree *DT = nullptr,
794 unsigned Depth = 0);
795bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC = nullptr,
796 const Instruction *CtxI = nullptr,
797 const DominatorTree *DT = nullptr,
798 unsigned Depth = 0);
799
800/// Return true if undefined behavior would provable be executed on the path to
801/// OnPathTo if Root produced a posion result. Note that this doesn't say
802/// anything about whether OnPathTo is actually executed or whether Root is
803/// actually poison. This can be used to assess whether a new use of Root can
804/// be added at a location which is control equivalent with OnPathTo (such as
805/// immediately before it) without introducing UB which didn't previously
806/// exist. Note that a false result conveys no information.
807bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root,
808 Instruction *OnPathTo,
809 DominatorTree *DT);
810
811/// Specific patterns of select instructions we can match.
814 SPF_SMIN, /// Signed minimum
815 SPF_UMIN, /// Unsigned minimum
816 SPF_SMAX, /// Signed maximum
817 SPF_UMAX, /// Unsigned maximum
818 SPF_FMINNUM, /// Floating point minnum
819 SPF_FMAXNUM, /// Floating point maxnum
820 SPF_ABS, /// Absolute value
821 SPF_NABS /// Negated absolute value
823
824/// Behavior when a floating point min/max is given one NaN and one
825/// non-NaN as input.
827 SPNB_NA = 0, /// NaN behavior not applicable.
828 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
829 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
830 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
831 /// it has been determined that no operands can
832 /// be NaN).
834
837 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
838 /// SPF_FMINNUM or SPF_FMAXNUM.
839 bool Ordered; /// When implementing this min/max pattern as
840 /// fcmp; select, does the fcmp have to be
841 /// ordered?
842
843 /// Return true if \p SPF is a min or a max pattern.
845 return SPF != SPF_UNKNOWN && SPF != SPF_ABS && SPF != SPF_NABS;
846 }
847};
848
849/// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
850/// and providing the out parameter results if we successfully match.
851///
852/// For ABS/NABS, LHS will be set to the input to the abs idiom. RHS will be
853/// the negation instruction from the idiom.
854///
855/// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
856/// not match that of the original select. If this is the case, the cast
857/// operation (one of Trunc,SExt,Zext) that must be done to transform the
858/// type of LHS and RHS into the type of V is returned in CastOp.
859///
860/// For example:
861/// %1 = icmp slt i32 %a, i32 4
862/// %2 = sext i32 %a to i64
863/// %3 = select i1 %1, i64 %2, i64 4
864///
865/// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
866///
867SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
868 Instruction::CastOps *CastOp = nullptr,
869 unsigned Depth = 0);
870
872 const Value *&RHS) {
873 Value *L = const_cast<Value *>(LHS);
874 Value *R = const_cast<Value *>(RHS);
875 auto Result = matchSelectPattern(const_cast<Value *>(V), L, R);
876 LHS = L;
877 RHS = R;
878 return Result;
879}
880
881/// Determine the pattern that a select with the given compare as its
882/// predicate and given values as its true/false operands would match.
883SelectPatternResult matchDecomposedSelectPattern(
884 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
885 Instruction::CastOps *CastOp = nullptr, unsigned Depth = 0);
886
887/// Return the canonical comparison predicate for the specified
888/// minimum/maximum flavor.
889CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered = false);
890
891/// Return the inverse minimum/maximum flavor of the specified flavor.
892/// For example, signed minimum is the inverse of signed maximum.
894
896
897/// Return the minimum or maximum constant value for the specified integer
898/// min/max flavor and type.
899APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth);
900
901/// Check if the values in \p VL are select instructions that can be converted
902/// to a min or max (vector) intrinsic. Returns the intrinsic ID, if such a
903/// conversion is possible, together with a bool indicating whether all select
904/// conditions are only used by the selects. Otherwise return
905/// Intrinsic::not_intrinsic.
906std::pair<Intrinsic::ID, bool>
907canConvertToMinOrMaxIntrinsic(ArrayRef<Value *> VL);
908
909/// Attempt to match a simple first order recurrence cycle of the form:
910/// %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
911/// %inc = binop %iv, %step
912/// OR
913/// %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
914/// %inc = binop %step, %iv
915///
916/// A first order recurrence is a formula with the form: X_n = f(X_(n-1))
917///
918/// A couple of notes on subtleties in that definition:
919/// * The Step does not have to be loop invariant. In math terms, it can
920/// be a free variable. We allow recurrences with both constant and
921/// variable coefficients. Callers may wish to filter cases where Step
922/// does not dominate P.
923/// * For non-commutative operators, we will match both forms. This
924/// results in some odd recurrence structures. Callers may wish to filter
925/// out recurrences where the phi is not the LHS of the returned operator.
926/// * Because of the structure matched, the caller can assume as a post
927/// condition of the match the presence of a Loop with P's parent as it's
928/// header *except* in unreachable code. (Dominance decays in unreachable
929/// code.)
930///
931/// NOTE: This is intentional simple. If you want the ability to analyze
932/// non-trivial loop conditons, see ScalarEvolution instead.
933bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start,
934 Value *&Step);
935
936/// Analogous to the above, but starting from the binary operator
937bool matchSimpleRecurrence(const BinaryOperator *I, PHINode *&P, Value *&Start,
938 Value *&Step);
939
940/// Return true if RHS is known to be implied true by LHS. Return false if
941/// RHS is known to be implied false by LHS. Otherwise, return std::nullopt if
942/// no implication can be made. A & B must be i1 (boolean) values or a vector of
943/// such values. Note that the truth table for implication is the same as <=u on
944/// i1 values (but not
945/// <=s!). The truth table for both is:
946/// | T | F (B)
947/// T | T | F
948/// F | T | T
949/// (A)
950std::optional<bool> isImpliedCondition(const Value *LHS, const Value *RHS,
951 const DataLayout &DL,
952 bool LHSIsTrue = true,
953 unsigned Depth = 0);
954std::optional<bool> isImpliedCondition(const Value *LHS,
955 CmpInst::Predicate RHSPred,
956 const Value *RHSOp0, const Value *RHSOp1,
957 const DataLayout &DL,
958 bool LHSIsTrue = true,
959 unsigned Depth = 0);
960
961/// Return the boolean condition value in the context of the given instruction
962/// if it is known based on dominating conditions.
963std::optional<bool> isImpliedByDomCondition(const Value *Cond,
964 const Instruction *ContextI,
965 const DataLayout &DL);
966std::optional<bool> isImpliedByDomCondition(CmpInst::Predicate Pred,
967 const Value *LHS, const Value *RHS,
968 const Instruction *ContextI,
969 const DataLayout &DL);
970
971/// If Ptr1 is provably equal to Ptr2 plus a constant offset, return that
972/// offset. For example, Ptr1 might be &A[42], and Ptr2 might be &A[40]. In
973/// this case offset would be -8.
974std::optional<int64_t> isPointerOffset(const Value *Ptr1, const Value *Ptr2,
975 const DataLayout &DL);
976} // end namespace llvm
977
978#endif // LLVM_ANALYSIS_VALUETRACKING_H
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
SmallVector< MachineOperand, 4 > Cond
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
Hexagon Common GEP
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallSet class.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:75
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1516
an instruction to allocate memory on the stack
Definition: Instructions.h:58
A cache of @llvm.assume calls within a function.
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:88
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1186
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:718
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition: Constants.h:682
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:3070
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:166
Metadata node.
Definition: Metadata.h:943
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition: Operator.h:31
The optimization diagnostic interface.
Provides information about what library functions are available for the current target.
LLVM Value Representation.
Definition: Value.h:74
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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.
bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ Offset
Definition: DWP.cpp:406
OverflowResult
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
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.
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false)
Return true if the two given values are negation.
bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveNullness)
This function returns call pointer argument that is considered the same by aliasing rules.
OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
void getGuaranteedNonPoisonOps(const Instruction *I, SmallVectorImpl< const Value * > &Ops)
Insert operands of I into Ops such that I will trigger undefined behavior if I is executed and that o...
bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
FPClassTest fabs(FPClassTest Mask)
Return the test mask which returns true if the value's sign bit is cleared.
bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
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.
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 ...
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.
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value,...
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.
bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
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...
ConstantRange computeConstantRange(const Value *V, bool ForSigned, bool UseInstrInfo=true, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, const DataLayout &DL, FPClassTest InterestedClasses=fcAllFlags, unsigned Depth=0, const TargetLibraryInfo *TLI=nullptr, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
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...
SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
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...
constexpr unsigned MaxAnalysisRecursionDepth
Definition: ValueTracking.h:46
void getGuaranteedWellDefinedOps(const Instruction *I, SmallVectorImpl< const Value * > &Ops)
Insert operands of I into Ops such that I will trigger undefined behavior if I is executed and that o...
FPClassTest fneg(FPClassTest Mask)
Return the test mask which returns true if the value's sign bit is flipped.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMIN
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveNullness)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool programUndefinedIfPoison(const Instruction *Inst)
KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, unsigned Depth, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
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...
bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
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 'len+1'.
ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT)
bool mustTriggerUB(const Instruction *I, const SmallSet< const Value *, 16 > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
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.
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...
void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
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.
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.
@ Add
Sum of integers.
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:184
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...
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
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.
std::pair< Value *, FPClassTest > fcmpToClassTest(CmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Returns a pair of values, which if passed to llvm.is.fpclass, returns the same result as an fcmp with...
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...
bool SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI)
Return true if we can prove that the specified FP value's sign bit is 0.
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.
std::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.
std::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...
bool isGEPBasedOnPointerToString(const GEPOperator *GEP, unsigned CharSize=8)
Returns true if the GEP is based on a pointer to a string (array of.
APInt operator|(APInt a, const APInt &b)
Definition: APInt.h:2077
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
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....
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.
void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Get the upper bound on bit size for this Value Op as a signed integer.
bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
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 'V & Mask' is known to be zero.
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,...
OverflowResult computeOverflowForUnsignedAdd(const Value *LHS, const Value *RHS, const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT, bool UseInstrInfo=true)
std::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.
Represents offset+length into a ConstantDataArray.
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
uint64_t operator[](unsigned I) const
Convenience accessor for elements in the slice.
void move(uint64_t Delta)
Moves the Offset and adjusts Length accordingly.
const ConstantDataArray * Array
ConstantDataArray pointer.
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
void knownNot(FPClassTest RuleOut)
void copysign(const KnownFPClass &Sign)
KnownFPClass & operator|=(const KnownFPClass &RHS)
std::optional< bool > SignBit
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
void signBitIsZero()
Assume the sign bit is zero.
SelectPatternFlavor Flavor
bool Ordered
Only applicable if Flavor is SPF_FMINNUM or SPF_FMAXNUM.
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
SelectPatternNaNBehavior NaNBehavior