LLVM 24.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
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/FMF.h"
22#include "llvm/IR/InstrTypes.h"
24#include "llvm/IR/Intrinsics.h"
26#include <cassert>
27#include <cstdint>
28
29namespace llvm {
30
31class Operator;
32class AddOperator;
33class AssumptionCache;
34class DominatorTree;
35class GEPOperator;
37struct KnownBits;
38struct KnownFPClass;
39class Loop;
40class LoopInfo;
41class MDNode;
42class StringRef;
44class IntrinsicInst;
45template <typename T> class ArrayRef;
46
47constexpr unsigned MaxAnalysisRecursionDepth = 6;
48
49/// The max limit of the search depth in DecomposeGEPExpression() and
50/// getUnderlyingObject().
51constexpr unsigned MaxLookupSearchDepth = 10;
52
53/// Determine which bits of V are known to be either zero or one and return
54/// them in the KnownZero/KnownOne bit sets.
55///
56/// This function is defined on values with integer type, values with pointer
57/// type, and vectors of integers. In the case
58/// where V is a vector, the known zero and known one values are the
59/// same width as the vector element, and the bit is set only if it is true
60/// for all of the elements in the vector.
62 const DataLayout &DL,
63 AssumptionCache *AC = nullptr,
64 const Instruction *CxtI = nullptr,
65 const DominatorTree *DT = nullptr,
66 bool UseInstrInfo = true, unsigned Depth = 0);
67
68/// Returns the known bits rather than passing by reference.
70 AssumptionCache *AC = nullptr,
71 const Instruction *CxtI = nullptr,
72 const DominatorTree *DT = nullptr,
73 bool UseInstrInfo = true,
74 unsigned Depth = 0);
75
76/// Returns the known bits rather than passing by reference.
77LLVM_ABI KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
78 const DataLayout &DL,
79 AssumptionCache *AC = nullptr,
80 const Instruction *CxtI = nullptr,
81 const DominatorTree *DT = nullptr,
82 bool UseInstrInfo = true,
83 unsigned Depth = 0);
84
85LLVM_ABI KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
86 const SimplifyQuery &Q, unsigned Depth = 0);
87
89 unsigned Depth = 0);
90
92 const SimplifyQuery &Q, unsigned Depth = 0);
93
94/// Compute known bits from the range metadata.
95/// \p KnownZero the set of bits that are known to be zero
96/// \p KnownOne the set of bits that are known to be one
99
100/// Merge bits known from context-dependent facts into Known.
102 const SimplifyQuery &Q,
103 unsigned Depth = 0);
104
105/// Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
107 const KnownBits &KnownLHS,
108 const KnownBits &KnownRHS,
109 const SimplifyQuery &SQ,
110 unsigned Depth = 0);
111
112/// Adjust \p Known for the given select \p Arm to include information from the
113/// select \p Cond.
115 Value *Arm, bool Invert,
116 const SimplifyQuery &Q,
117 unsigned Depth = 0);
118
119/// Adjust \p Known for the given select \p Arm to include information from the
120/// select \p Cond.
122 Value *Arm, bool Invert,
123 const SimplifyQuery &Q,
124 unsigned Depth = 0);
125
127 /// Not known to have no common set bits.
129
130 /// Known to have no common set bits only if undef values are ignored.
132
133 /// Known to have no common set bits.
135};
136
137/// Return how strongly LHS and RHS are known to have no common set bits.
139 const WithCache<const Value *> &LHSCache,
140 const WithCache<const Value *> &RHSCache, const SimplifyQuery &SQ);
141
142/// Return true if LHS and RHS have no common bits set.
143LLVM_ABI bool haveNoCommonBitsSet(const WithCache<const Value *> &LHSCache,
144 const WithCache<const Value *> &RHSCache,
145 const SimplifyQuery &SQ);
146
147/// Return true if the given value is known to have exactly one bit set when
148/// defined. For vectors return true if every element is known to be a power
149/// of two when defined. Supports values with integer or pointer type and
150/// vectors of integers. If 'OrZero' is set, then return true if the given
151/// value is either a power of two or zero.
152LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
153 bool OrZero = false,
154 AssumptionCache *AC = nullptr,
155 const Instruction *CxtI = nullptr,
156 const DominatorTree *DT = nullptr,
157 bool UseInstrInfo = true,
158 unsigned Depth = 0);
159
160LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
161 const SimplifyQuery &Q,
162 unsigned Depth = 0);
163
164LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI);
165
166LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI);
167
168/// Return true if the given value is known to be non-zero when defined. For
169/// vectors, return true if every element is known to be non-zero when
170/// defined. For pointers, if the context instruction and dominator tree are
171/// specified, perform context-sensitive analysis and return true if the
172/// pointer couldn't possibly be null at the specified instruction.
173/// Supports values with integer or pointer type and vectors of integers.
174LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q,
175 unsigned Depth = 0);
176
177/// Return true if the two given values are negation.
178/// Currently can recoginze Value pair:
179/// 1: <X, Y> if X = sub (0, Y) or Y = sub (0, X)
180/// 2: <X, Y> if X = sub (A, B) and Y = sub (B, A)
181LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y,
182 bool NeedNSW = false, bool AllowPoison = true);
183
184/// Return true iff:
185/// 1. X is poison implies Y is poison.
186/// 2. X is true implies Y is false.
187/// 3. X is false implies Y is true.
188/// Otherwise, return false.
189LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y);
190
191/// Returns true if the give value is known to be non-negative.
192LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ,
193 unsigned Depth = 0);
194
195/// Returns true if the given value is known be positive (i.e. non-negative
196/// and non-zero).
197LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ,
198 unsigned Depth = 0);
199
200/// Returns true if the given value is known be negative (i.e. non-positive
201/// and non-zero).
202LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ,
203 unsigned Depth = 0);
204
205/// Return true if the given values are known to be non-equal when defined.
206/// Supports scalar integer types only.
207LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2,
208 const SimplifyQuery &SQ, unsigned Depth = 0);
209
210/// Return true if 'V & Mask' is known to be zero. We use this predicate to
211/// simplify operations downstream. Mask is known to be zero for bits that V
212/// cannot have.
213///
214/// This function is defined on values with integer type, values with pointer
215/// type, and vectors of integers. In the case
216/// where V is a vector, the mask, known zero, and known one values are the
217/// same width as the vector element, and the bit is set only if it is true
218/// for all of the elements in the vector.
219LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask,
220 const SimplifyQuery &SQ, unsigned Depth = 0);
221
222/// Return the number of times the sign bit of the register is replicated into
223/// the other bits. We know that at least 1 bit is always equal to the sign
224/// bit (itself), but other cases can give us information. For example,
225/// immediately after an "ashr X, 2", we know that the top 3 bits are all
226/// equal to each other, so we return 3. For vectors, return the number of
227/// sign bits for the vector element with the mininum number of known sign
228/// bits.
229LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL,
230 AssumptionCache *AC = nullptr,
231 const Instruction *CxtI = nullptr,
232 const DominatorTree *DT = nullptr,
233 bool UseInstrInfo = true,
234 unsigned Depth = 0);
235
236/// Get the upper bound on bit size for this Value \p Op as a signed integer.
237/// i.e. x == sext(trunc(x to MaxSignificantBits) to bitwidth(x)).
238/// Similar to the APInt::getSignificantBits function.
239LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op,
240 const DataLayout &DL,
241 AssumptionCache *AC = nullptr,
242 const Instruction *CxtI = nullptr,
243 const DominatorTree *DT = nullptr,
244 unsigned Depth = 0);
245
246/// Map a call instruction to an intrinsic ID. Libcalls which have equivalent
247/// intrinsics are treated as-if they were intrinsics.
249 const TargetLibraryInfo *TLI);
250
251/// Given an exploded icmp instruction, return true if the comparison only
252/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
253/// the result of the comparison is true when the input value is signed.
254LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS,
255 bool &TrueIfSigned);
256
257/// Determine which floating-point classes are valid for \p V, and return them
258/// in KnownFPClass bit sets.
259///
260/// This function is defined on values with floating-point type, values vectors
261/// of floating-point type, and arrays of floating-point type.
262
263/// \p InterestedClasses is a compile time optimization hint for which floating
264/// point classes should be queried. Queries not specified in \p
265/// InterestedClasses should be reliable if they are determined during the
266/// query.
267LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V,
268 const APInt &DemandedElts,
269 FPClassTest InterestedClasses,
270 const SimplifyQuery &SQ,
271 unsigned Depth = 0);
272
273LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V,
274 FPClassTest InterestedClasses,
275 const SimplifyQuery &SQ,
276 unsigned Depth = 0);
277
278LLVM_ABI KnownFPClass computeKnownFPClass(
279 const Value *V, const DataLayout &DL,
280 FPClassTest InterestedClasses = fcAllFlags,
281 const TargetLibraryInfo *TLI = nullptr, AssumptionCache *AC = nullptr,
282 const Instruction *CxtI = nullptr, const DominatorTree *DT = nullptr,
283 bool UseInstrInfo = true, unsigned Depth = 0);
284
285/// Wrapper to account for known fast math flags at the use instruction.
286LLVM_ABI KnownFPClass computeKnownFPClass(
287 const Value *V, const APInt &DemandedElts, FastMathFlags FMF,
288 FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth = 0);
289
290LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, FastMathFlags FMF,
291 FPClassTest InterestedClasses,
292 const SimplifyQuery &SQ,
293 unsigned Depth = 0);
294
295/// Return true if we can prove that the specified FP value is never equal to
296/// -0.0. Users should use caution when considering PreserveSign
297/// denormal-fp-math.
298LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ,
299 unsigned Depth = 0);
300
301/// Return true if we can prove that the specified FP value is either NaN or
302/// never less than -0.0.
303///
304/// NaN --> true
305/// +0 --> true
306/// -0 --> true
307/// x > +0 --> true
308/// x < -0 --> false
309LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V,
310 const SimplifyQuery &SQ,
311 unsigned Depth = 0);
312
313/// Return true if the floating-point scalar value is not an infinity or if
314/// the floating-point vector value has no infinities. Return false if a value
315/// could ever be infinity.
316LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ,
317 unsigned Depth = 0);
318
319/// Return true if the floating-point value can never contain a NaN or infinity.
320LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ,
321 unsigned Depth = 0);
322
323/// Return true if the floating-point scalar value is not a NaN or if the
324/// floating-point vector value has no NaN elements. Return false if a value
325/// could ever be NaN.
326LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ,
327 unsigned Depth = 0);
328
329/// Return false if we can prove that the specified FP value's sign bit is 0.
330/// Return true if we can prove that the specified FP value's sign bit is 1.
331/// Otherwise return std::nullopt.
332LLVM_ABI std::optional<bool> computeKnownFPSignBit(const Value *V,
333 const SimplifyQuery &SQ,
334 unsigned Depth = 0);
335
336/// Return true if the sign bit of the FP value can be ignored by the user when
337/// the value is zero.
338LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U);
339
340/// Return true if the sign bit of the FP value can be ignored by the user when
341/// the value is NaN.
342LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U);
343
344/// Return true if the floating-point value \p V is known to be an integer
345/// value.
346LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ,
347 FastMathFlags FMF);
348
349/// If the specified value can be set by repeating the same byte in memory,
350/// return the i8 value that it is represented with. This is true for all i8
351/// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
352/// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
353/// i16 0x1234), return null. If the value is entirely undef and padding,
354/// return undef.
355LLVM_ABI Value *isBytewiseValue(Value *V, const DataLayout &DL);
356
357/// Given an aggregate and an sequence of indices, see if the scalar value
358/// indexed is already around as a register, for example if it were inserted
359/// directly into the aggregate.
360///
361/// If InsertBefore is not empty, this function will duplicate (modified)
362/// insertvalues when a part of a nested struct is extracted.
364 Value *V, ArrayRef<unsigned> idx_range,
365 std::optional<BasicBlock::iterator> InsertBefore = std::nullopt);
366
367/// Analyze the specified pointer to see if it can be expressed as a base
368/// pointer plus a constant offset. Return the base and offset to the caller.
369///
370/// This is a wrapper around Value::stripAndAccumulateConstantOffsets that
371/// creates and later unpacks the required APInt.
373 const DataLayout &DL,
374 bool AllowNonInbounds = true) {
375 APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
376 Value *Base =
377 Ptr->stripAndAccumulateConstantOffsets(DL, OffsetAPInt, AllowNonInbounds);
378
379 Offset = OffsetAPInt.getSExtValue();
380 return Base;
381}
382inline const Value *
384 const DataLayout &DL,
385 bool AllowNonInbounds = true) {
386 return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset, DL,
387 AllowNonInbounds);
388}
389
390/// Represents offset+length into a ConstantDataArray.
392 /// ConstantDataArray pointer. nullptr indicates a zeroinitializer (a valid
393 /// initializer, it just doesn't fit the ConstantDataArray interface).
395
396 /// Slice starts at this Offset.
398
399 /// Length of the slice.
401
402 /// Moves the Offset and adjusts Length accordingly.
403 void move(uint64_t Delta) {
404 assert(Delta < Length);
405 Offset += Delta;
406 Length -= Delta;
407 }
408
409 /// Convenience accessor for elements in the slice.
410 uint64_t operator[](unsigned I) const {
411 return Array == nullptr ? 0 : Array->getElementAsInteger(I + Offset);
412 }
413};
414
415/// Returns true if the value \p V is a pointer into a ConstantDataArray.
416/// If successful \p Slice will point to a ConstantDataArray info object
417/// with an appropriate offset.
418LLVM_ABI bool getConstantDataArrayInfo(const Value *V,
419 ConstantDataArraySlice &Slice,
420 unsigned ElementSize,
421 uint64_t Offset = 0);
422
423/// This function computes the length of a null-terminated C string pointed to
424/// by V. If successful, it returns true and returns the string in Str. If
425/// unsuccessful, it returns false. This does not include the trailing null
426/// character by default. If TrimAtNul is set to false, then this returns any
427/// trailing null characters as well as any other characters that come after
428/// it.
429LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str,
430 bool TrimAtNul = true);
431
432/// If we can compute the length of the string pointed to by the specified
433/// pointer, return 'len+1'. If we can't, return 0.
434LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
435
436/// This function returns call pointer argument that is considered the same by
437/// aliasing rules. You CAN'T use it to replace one value with another. If
438/// \p MustPreserveOffset is true, the call must preserve the byte offset of
439/// the pointer within its underlying object. Offset preservation implies
440/// nullness preservation; pass true when callers reason about either offset or
441/// null equality (e.g. GEP decomposition, dereferenceability, isKnownNonZero).
442LLVM_ABI const Value *
444 bool MustPreserveOffset);
446 bool MustPreserveOffset) {
447 return const_cast<Value *>(getArgumentAliasingToReturnedPointer(
448 const_cast<const CallBase *>(Call), MustPreserveOffset));
449}
450
451/// {launder,strip}.invariant.group returns pointer that aliases its argument,
452/// and it only captures pointer by returning it.
453/// These intrinsics are not marked as nocapture, because returning is
454/// considered as capture. The arguments are not marked as returned neither,
455/// because it would make it useless. If \p MustPreserveOffset is true, the
456/// intrinsic must preserve the byte offset of the pointer within its
457/// underlying object (which excludes `llvm.ptrmask`, since masking off low
458/// bits changes the byte offset while still aliasing the same object).
460 const CallBase *Call, bool MustPreserveOffset);
461
462/// This method strips off any GEP address adjustments, pointer casts
463/// or `llvm.threadlocal.address` from the specified value \p V, returning the
464/// original object being addressed. Note that the returned value has pointer
465/// type if the specified value does. If the \p MaxLookup value is non-zero, it
466/// limits the number of instructions to be stripped off.
467LLVM_ABI const Value *
468getUnderlyingObject(const Value *V, unsigned MaxLookup = MaxLookupSearchDepth);
470 unsigned MaxLookup = MaxLookupSearchDepth) {
471 // Force const to avoid infinite recursion.
472 const Value *VConst = V;
473 return const_cast<Value *>(getUnderlyingObject(VConst, MaxLookup));
474}
475
476/// Like getUnderlyingObject(), but will try harder to find a single underlying
477/// object. In particular, this function also looks through selects and phis.
478LLVM_ABI const Value *getUnderlyingObjectAggressive(const Value *V);
479
480/// This method is similar to getUnderlyingObject except that it can
481/// look through phi and select instructions and return multiple objects.
482///
483/// If LoopInfo is passed, loop phis are further analyzed. If a pointer
484/// accesses different objects in each iteration, we don't look through the
485/// phi node. E.g. consider this loop nest:
486///
487/// int **A;
488/// for (i)
489/// for (j) {
490/// A[i][j] = A[i-1][j] * B[j]
491/// }
492///
493/// This is transformed by Load-PRE to stash away A[i] for the next iteration
494/// of the outer loop:
495///
496/// Curr = A[0]; // Prev_0
497/// for (i: 1..N) {
498/// Prev = Curr; // Prev = PHI (Prev_0, Curr)
499/// Curr = A[i];
500/// for (j: 0..N) {
501/// Curr[j] = Prev[j] * B[j]
502/// }
503/// }
504///
505/// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
506/// should not assume that Curr and Prev share the same underlying object thus
507/// it shouldn't look through the phi above.
508LLVM_ABI void getUnderlyingObjects(const Value *V,
509 SmallVectorImpl<const Value *> &Objects,
510 const LoopInfo *LI = nullptr,
511 unsigned MaxLookup = MaxLookupSearchDepth);
512
513/// This is a wrapper around getUnderlyingObjects and adds support for basic
514/// ptrtoint+arithmetic+inttoptr sequences.
515LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V,
516 SmallVectorImpl<Value *> &Objects);
517
518/// Returns unique alloca where the value comes from, or nullptr.
519/// If OffsetZero is true check that V points to the begining of the alloca.
520LLVM_ABI AllocaInst *findAllocaForValue(Value *V, bool OffsetZero = false);
521inline const AllocaInst *findAllocaForValue(const Value *V,
522 bool OffsetZero = false) {
523 return findAllocaForValue(const_cast<Value *>(V), OffsetZero);
524}
525
526/// Return true if the only users of this pointer are lifetime markers.
527LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V);
528
529/// Return true if the only users of this pointer are lifetime markers or
530/// droppable instructions.
532
533/// Return true if the instruction doesn't potentially cross vector lanes. This
534/// condition is weaker than checking that the instruction is lanewise: lanewise
535/// means that the same operation is splatted across all lanes, but we also
536/// include the case where there is a different operation on each lane, as long
537/// as the operation only uses data from that lane. An example of an operation
538/// that is not lanewise, but doesn't cross vector lanes is insertelement.
539LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I);
540
541/// Return true if the instruction does not have any effects besides
542/// calculating the result and does not have undefined behavior.
543///
544/// This method never returns true for an instruction that returns true for
545/// mayHaveSideEffects; however, this method also does some other checks in
546/// addition. It checks for undefined behavior, like dividing by zero or
547/// loading from an invalid pointer (but not for undefined results, like a
548/// shift with a shift amount larger than the width of the result). It checks
549/// for malloc and alloca because speculatively executing them might cause a
550/// memory leak. It also returns false for instructions related to control
551/// flow, specifically terminators and PHI nodes.
552///
553/// If the CtxI is specified this method performs context-sensitive analysis
554/// and returns true if it is safe to execute the instruction immediately
555/// before the CtxI. If the instruction has (transitive) operands that don't
556/// dominate CtxI, the analysis is performed under the assumption that these
557/// operands will also be speculated to a point before CxtI.
558///
559/// If the CtxI is NOT specified this method only looks at the instruction
560/// itself and its operands, so if this method returns true, it is safe to
561/// move the instruction as long as the correct dominance relationships for
562/// the operands and users hold.
563///
564/// If \p UseVariableInfo is true, the information from non-constant operands
565/// will be taken into account.
566///
567/// If \p IgnoreUBImplyingAttrs is true, UB-implying attributes will be ignored.
568/// The caller is responsible for correctly propagating them after hoisting.
569///
570/// This method can return true for instructions that read memory;
571/// for such instructions, moving them may change the resulting value.
573 const Instruction *I, const Instruction *CtxI = nullptr,
574 AssumptionCache *AC = nullptr, const DominatorTree *DT = nullptr,
575 const TargetLibraryInfo *TLI = nullptr, bool UseVariableInfo = true,
576 bool IgnoreUBImplyingAttrs = true);
577
580 AssumptionCache *AC = nullptr,
581 const DominatorTree *DT = nullptr,
582 const TargetLibraryInfo *TLI = nullptr,
583 bool UseVariableInfo = true,
584 bool IgnoreUBImplyingAttrs = true) {
585 // Take an iterator, and unwrap it into an Instruction *.
586 return isSafeToSpeculativelyExecute(I, &*CtxI, AC, DT, TLI, UseVariableInfo,
587 IgnoreUBImplyingAttrs);
588}
589
590/// Don't use information from its non-constant operands. This helper is used
591/// when its operands are going to be replaced.
593 const Instruction *I, bool IgnoreUBImplyingAttrs = true) {
594 return isSafeToSpeculativelyExecute(I, nullptr, nullptr, nullptr, nullptr,
595 /*UseVariableInfo=*/false,
596 IgnoreUBImplyingAttrs);
597}
598
599/// This returns the same result as isSafeToSpeculativelyExecute if Opcode is
600/// the actual opcode of Inst. If the provided and actual opcode differ, the
601/// function (virtually) overrides the opcode of Inst with the provided
602/// Opcode. There are come constraints in this case:
603/// * If Opcode has a fixed number of operands (eg, as binary operators do),
604/// then Inst has to have at least as many leading operands. The function
605/// will ignore all trailing operands beyond that number.
606/// * If Opcode allows for an arbitrary number of operands (eg, as CallInsts
607/// do), then all operands are considered.
608/// * The virtual instruction has to satisfy all typing rules of the provided
609/// Opcode.
610/// * This function is pessimistic in the following sense: If one actually
611/// materialized the virtual instruction, then isSafeToSpeculativelyExecute
612/// may say that the materialized instruction is speculatable whereas this
613/// function may have said that the instruction wouldn't be speculatable.
614/// This behavior is a shortcoming in the current implementation and not
615/// intentional.
617 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI = nullptr,
618 AssumptionCache *AC = nullptr, const DominatorTree *DT = nullptr,
619 const TargetLibraryInfo *TLI = nullptr, bool UseVariableInfo = true,
620 bool IgnoreUBImplyingAttrs = true);
621
622/// Returns true if the result or effects of the given instructions \p I
623/// depend values not reachable through the def use graph.
624/// * Memory dependence arises for example if the instruction reads from
625/// memory or may produce effects or undefined behaviour. Memory dependent
626/// instructions generally cannot be reorderd with respect to other memory
627/// dependent instructions.
628/// * Control dependence arises for example if the instruction may fault
629/// if lifted above a throwing call or infinite loop.
630LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I);
631
632/// Return true if it is an intrinsic that cannot be speculated but also
633/// cannot trap.
634LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I);
635
636/// Return true if it is valid to use the assumptions provided by an
637/// assume intrinsic, I, at the point in the control-flow identified by the
638/// context instruction, CxtI. By default, ephemeral values of the assumption
639/// are treated as an invalid context, to prevent the assumption from being used
640/// to optimize away its argument. If the caller can ensure that this won't
641/// happen, it can call with AllowEphemerals set to true to get more valid
642/// assumptions.
643LLVM_ABI bool isValidAssumeForContext(const Instruction *I,
644 const Instruction *CxtI,
645 const DominatorTree *DT = nullptr,
646 bool AllowEphemerals = false);
647
649 const SimplifyQuery &Q) {
651}
652
653/// Returns true, if no instruction between \p Assume and \p CtxI may free
654/// (including through synchronization).
655LLVM_ABI bool willNotFreeBetween(const Instruction *Assume,
656 const Instruction *CtxI);
657
658enum class OverflowResult {
659 /// Always overflows in the direction of signed/unsigned min value.
661 /// Always overflows in the direction of signed/unsigned max value.
663 /// May or may not overflow.
665 /// Never overflows.
667};
668
670 const Value *RHS,
671 const SimplifyQuery &SQ,
672 bool IsNSW = false);
674 const Value *RHS,
675 const SimplifyQuery &SQ);
677 const WithCache<const Value *> &LHS, const WithCache<const Value *> &RHS,
678 const SimplifyQuery &SQ);
680 const WithCache<const Value *> &LHS, const WithCache<const Value *> &RHS,
681 const SimplifyQuery &SQ);
682/// This version also leverages the sign bit of Add if known.
684 const SimplifyQuery &SQ);
686 const Value *RHS,
687 const SimplifyQuery &SQ);
689 const Value *RHS,
690 const SimplifyQuery &SQ);
691
692/// Returns true if the arithmetic part of the \p WO 's result is
693/// used only along the paths control dependent on the computation
694/// not overflowing, \p WO being an <op>.with.overflow intrinsic.
695LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
696 const DominatorTree &DT);
697
698/// Determine the possible constant range of vscale with the given bit width,
699/// based on the vscale_range function attribute.
700LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth);
701
702/// Determine the possible constant range of an integer or vector of integer
703/// value. This is intended as a cheap, non-recursive check.
704LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned,
705 const SimplifyQuery &SQ,
706 unsigned Depth = 0);
707
708/// Combine constant ranges from computeConstantRange() and computeKnownBits().
710 const WithCache<const Value *> &V, bool ForSigned, const SimplifyQuery &SQ);
711
712/// Return true if this function can prove that the instruction I will
713/// always transfer execution to one of its successors (including the next
714/// instruction that follows within a basic block). E.g. this is not
715/// guaranteed for function calls that could loop infinitely.
716///
717/// In other words, this function returns false for instructions that may
718/// transfer execution or fail to transfer execution in a way that is not
719/// captured in the CFG nor in the sequence of instructions within a basic
720/// block.
721///
722/// Undefined behavior is assumed not to happen, so e.g. division is
723/// guaranteed to transfer execution to the following instruction even
724/// though division by zero might cause undefined behavior.
726
727/// Returns true if this block does not contain a potential implicit exit.
728/// This is equivelent to saying that all instructions within the basic block
729/// are guaranteed to transfer execution to their successor within the basic
730/// block. This has the same assumptions w.r.t. undefined behavior as the
731/// instruction variant of this function.
733
734/// Return true if every instruction in the range (Begin, End) is
735/// guaranteed to transfer execution to its static successor. \p ScanLimit
736/// bounds the search to avoid scanning huge blocks.
737LLVM_ABI bool
740 unsigned ScanLimit = 32);
741
742/// Same as previous, but with range expressed via iterator_range.
744 iterator_range<BasicBlock::const_iterator> Range, unsigned ScanLimit = 32);
745
746/// Return true if this function can prove that the instruction I
747/// is executed for every iteration of the loop L.
748///
749/// Note that this currently only considers the loop header.
751 const Loop *L);
752
753/// Return true if \p PoisonOp's user yields poison or raises UB if its
754/// operand \p PoisonOp is poison.
755///
756/// If \p PoisonOp is a vector or an aggregate and the operation's result is a
757/// single value, any poison element in /p PoisonOp should make the result
758/// poison or raise UB.
759///
760/// To filter out operands that raise UB on poison, you can use
761/// getGuaranteedNonPoisonOp.
762LLVM_ABI bool propagatesPoison(const Use &PoisonOp);
763
764/// Return whether this intrinsic propagates poison for all operands.
766
767/// Return true if the given instruction must trigger undefined behavior
768/// when I is executed with any operands which appear in KnownPoison holding
769/// a poison value at the point of execution.
770LLVM_ABI bool mustTriggerUB(const Instruction *I,
771 const SmallPtrSetImpl<const Value *> &KnownPoison);
772
773/// Return true if this function can prove that if Inst is executed
774/// and yields a poison value or undef bits, then that will trigger
775/// undefined behavior.
776///
777/// Note that this currently only considers the basic block that is
778/// the parent of Inst.
779LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst);
780LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst);
781
782/// canCreateUndefOrPoison returns true if Op can create undef or poison from
783/// non-undef & non-poison operands.
784/// For vectors, canCreateUndefOrPoison returns true if there is potential
785/// poison or undef in any element of the result when vectors without
786/// undef/poison poison are given as operands.
787/// For example, given `Op = shl <2 x i32> %x, <0, 32>`, this function returns
788/// true. If Op raises immediate UB but never creates poison or undef
789/// (e.g. sdiv I, 0), canCreatePoison returns false.
790///
791/// \p ConsiderFlagsAndMetadata controls whether poison producing flags and
792/// metadata on the instruction are considered. This can be used to see if the
793/// instruction could still introduce undef or poison even without poison
794/// generating flags and metadata which might be on the instruction.
795/// (i.e. could the result of Op->dropPoisonGeneratingFlags() still create
796/// poison or undef)
797///
798/// canCreatePoison returns true if Op can create poison from non-poison
799/// operands.
800LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op,
801 bool ConsiderFlagsAndMetadata = true);
802LLVM_ABI bool canCreatePoison(const Operator *Op,
803 bool ConsiderFlagsAndMetadata = true);
804
805/// Return true if V is poison given that ValAssumedPoison is already poison.
806/// For example, if ValAssumedPoison is `icmp X, 10` and V is `icmp X, 5`,
807/// impliesPoison returns true.
808LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V);
809
810/// Return true if this function can prove that V does not have undef bits
811/// and is never poison. If V is an aggregate value or vector, check whether
812/// all elements (except padding) are not undef or poison.
813/// Note that this is different from canCreateUndefOrPoison because the
814/// function assumes Op's operands are not poison/undef.
815///
816/// If CtxI and DT are specified this method performs flow-sensitive analysis
817/// and returns true if it is guaranteed to be never undef or poison
818/// immediately before the CtxI.
819LLVM_ABI bool
820isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC = nullptr,
821 const Instruction *CtxI = nullptr,
822 const DominatorTree *DT = nullptr,
823 unsigned Depth = 0);
824
825/// Returns true if V cannot be poison, but may be undef.
826LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V,
827 AssumptionCache *AC = nullptr,
828 const Instruction *CtxI = nullptr,
829 const DominatorTree *DT = nullptr,
830 unsigned Depth = 0);
831
834 const DominatorTree *DT = nullptr,
835 unsigned Depth = 0) {
836 // Takes an iterator as a position, passes down to Instruction *
837 // implementation.
838 return isGuaranteedNotToBePoison(V, AC, &*CtxI, DT, Depth);
839}
840
841/// Returns true if V cannot be undef, but may be poison.
842LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V,
843 AssumptionCache *AC = nullptr,
844 const Instruction *CtxI = nullptr,
845 const DominatorTree *DT = nullptr,
846 unsigned Depth = 0);
847
848/// Return true if undefined behavior would provable be executed on the path to
849/// OnPathTo if Root produced a posion result. Note that this doesn't say
850/// anything about whether OnPathTo is actually executed or whether Root is
851/// actually poison. This can be used to assess whether a new use of Root can
852/// be added at a location which is control equivalent with OnPathTo (such as
853/// immediately before it) without introducing UB which didn't previously
854/// exist. Note that a false result conveys no information.
855LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root,
856 Instruction *OnPathTo,
857 DominatorTree *DT);
858
859/// Convert an integer comparison with a constant RHS into an equivalent
860/// form with the strictness flipped predicate. Return the new predicate and
861/// corresponding constant RHS if possible. Otherwise return std::nullopt.
862/// E.g., (icmp sgt X, 0) -> (icmp sle X, 1).
863/// For a samesign predicate, fail if adjusting the constant would change its
864/// sign bit, because that would change the comparison's poison domain.
865LLVM_ABI std::optional<std::pair<CmpPredicate, Constant *>>
866getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C);
867
868/// Specific patterns of select instructions we can match.
871 SPF_SMIN, /// Signed minimum
872 SPF_UMIN, /// Unsigned minimum
873 SPF_SMAX, /// Signed maximum
874 SPF_UMAX, /// Unsigned maximum
875 SPF_FMINNUM, /// Floating point minnum
876 SPF_FMAXNUM, /// Floating point maxnum
877 SPF_ABS, /// Absolute value
878 SPF_NABS /// Negated absolute value
879};
880
881/// Behavior when a floating point min/max is given one NaN and one
882/// non-NaN as input.
884 SPNB_NA = 0, /// NaN behavior not applicable.
885 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
886 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
887 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
888 /// it has been determined that no operands can
889 /// be NaN).
890};
891
894 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
895 /// SPF_FMINNUM or SPF_FMAXNUM.
896 bool Ordered; /// When implementing this min/max pattern as
897 /// fcmp; select, does the fcmp have to be
898 /// ordered?
899
900 /// Return true if \p SPF is a min or a max pattern.
902 return SPF != SPF_UNKNOWN && SPF != SPF_ABS && SPF != SPF_NABS;
903 }
904};
905
906/// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
907/// and providing the out parameter results if we successfully match.
908///
909/// For ABS/NABS, LHS will be set to the input to the abs idiom. RHS will be
910/// the negation instruction from the idiom.
911///
912/// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
913/// not match that of the original select. If this is the case, the cast
914/// operation (one of Trunc,SExt,Zext) that must be done to transform the
915/// type of LHS and RHS into the type of V is returned in CastOp.
916///
917/// For example:
918/// %1 = icmp slt i32 %a, i32 4
919/// %2 = sext i32 %a to i64
920/// %3 = select i1 %1, i64 %2, i64 4
921///
922/// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
923///
924LLVM_ABI SelectPatternResult
925matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
926 Instruction::CastOps *CastOp = nullptr, unsigned Depth = 0);
927
929 const Value *&RHS) {
930 Value *L = const_cast<Value *>(LHS);
931 Value *R = const_cast<Value *>(RHS);
932 auto Result = matchSelectPattern(const_cast<Value *>(V), L, R);
933 LHS = L;
934 RHS = R;
935 return Result;
936}
937
938/// Determine the pattern that a select with the given compare as its
939/// predicate and given values as its true/false operands would match.
940LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(
941 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
942 FastMathFlags FMF = FastMathFlags(), Instruction::CastOps *CastOp = nullptr,
943 unsigned Depth = 0);
944
945/// Determine the pattern for predicate `X Pred Y ? X : Y`.
946LLVM_ABI SelectPatternResult getSelectPattern(
947 CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior = SPNB_NA,
948 bool Ordered = false);
949
950/// Return the canonical comparison predicate for the specified
951/// minimum/maximum flavor.
952LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF,
953 bool Ordered = false);
954
955/// Convert given `SPF` to equivalent min/max intrinsic.
956/// Caller must ensure `SPF` is an integer min or max pattern.
957LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF);
958
959/// Return the inverse minimum/maximum flavor of the specified flavor.
960/// For example, signed minimum is the inverse of signed maximum.
961LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF);
962
964
965/// Return the minimum or maximum constant value for the specified integer
966/// min/max flavor and type.
967LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth);
968
969/// Check if the values in \p VL are select instructions that can be converted
970/// to a min or max (vector) intrinsic. Returns the intrinsic ID, if such a
971/// conversion is possible, together with a bool indicating whether all select
972/// conditions are only used by the selects. Otherwise return
973/// Intrinsic::not_intrinsic.
974LLVM_ABI std::pair<Intrinsic::ID, bool>
976
977/// Attempt to match a simple first order recurrence cycle of the form:
978/// %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
979/// %inc = binop %iv, %step
980/// OR
981/// %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
982/// %inc = binop %step, %iv
983///
984/// A first order recurrence is a formula with the form: X_n = f(X_(n-1))
985///
986/// A couple of notes on subtleties in that definition:
987/// * The Step does not have to be loop invariant. In math terms, it can
988/// be a free variable. We allow recurrences with both constant and
989/// variable coefficients. Callers may wish to filter cases where Step
990/// does not dominate P.
991/// * For non-commutative operators, we will match both forms. This
992/// results in some odd recurrence structures. Callers may wish to filter
993/// out recurrences where the phi is not the LHS of the returned operator.
994/// * Because of the structure matched, the caller can assume as a post
995/// condition of the match the presence of a Loop with P's parent as it's
996/// header *except* in unreachable code. (Dominance decays in unreachable
997/// code.)
998///
999/// NOTE: This is intentional simple. If you want the ability to analyze
1000/// non-trivial loop conditons, see ScalarEvolution instead.
1001LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO,
1002 Value *&Start, Value *&Step);
1003
1004/// Analogous to the above, but starting from the binary operator
1005LLVM_ABI bool matchSimpleRecurrence(const BinaryOperator *I, PHINode *&P,
1006 Value *&Start, Value *&Step);
1007
1008/// Attempt to match a simple value-accumulating recurrence of the form:
1009/// %llvm.intrinsic.acc = phi Ty [%Init, %Entry], [%llvm.intrinsic, %backedge]
1010/// %llvm.intrinsic = call Ty @llvm.intrinsic(%OtherOp, %llvm.intrinsic.acc)
1011/// OR
1012/// %llvm.intrinsic.acc = phi Ty [%Init, %Entry], [%llvm.intrinsic, %backedge]
1013/// %llvm.intrinsic = call Ty @llvm.intrinsic(%llvm.intrinsic.acc, %OtherOp)
1014///
1015/// The recurrence relation is of kind:
1016/// X_0 = %a (initial value),
1017/// X_i = call @llvm.binary.intrinsic(X_i-1, %b)
1018/// Where %b is not required to be loop-invariant.
1019LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I,
1020 PHINode *&P, Value *&Init,
1021 Value *&OtherOp);
1022
1023/// Attempt to match a simple value-accumulating recurrence of the form:
1024/// %llvm.intrinsic.acc = phi Ty [%Init, %Entry], [%llvm.intrinsic, %backedge]
1025/// %llvm.intrinsic = call Ty @llvm.intrinsic(%OtherOp0, %OtherOp1,
1026/// %llvm.intrinsic.acc)
1027/// OR
1028/// %llvm.intrinsic.acc = phi Ty [%Init, %Entry], [%llvm.intrinsic, %backedge]
1029/// %llvm.intrinsic = call Ty @llvm.intrinsic(%llvm.intrinsic.acc, %OtherOp0,
1030/// %OtherOp1)
1031///
1032/// The recurrence relation is of kind:
1033/// X_0 = %a (initial value),
1034/// X_i = call @llvm.ternary.intrinsic(X_i-1, %b, %c)
1035/// Where %b, %c are not required to be loop-invariant.
1036LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I,
1037 PHINode *&P, Value *&Init,
1038 Value *&OtherOp0,
1039 Value *&OtherOp1);
1040
1041/// Return true if RHS is known to be implied true by LHS. Return false if
1042/// RHS is known to be implied false by LHS. Otherwise, return std::nullopt if
1043/// no implication can be made. A & B must be i1 (boolean) values or a vector of
1044/// such values. Note that the truth table for implication is the same as <=u on
1045/// i1 values (but not
1046/// <=s!). The truth table for both is:
1047/// | T | F (B)
1048/// T | T | F
1049/// F | T | T
1050/// (A)
1051LLVM_ABI std::optional<bool>
1052isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL,
1053 bool LHSIsTrue = true, unsigned Depth = 0);
1054LLVM_ABI std::optional<bool>
1055isImpliedCondition(const Value *LHS, CmpPredicate RHSPred, const Value *RHSOp0,
1056 const Value *RHSOp1, const DataLayout &DL,
1057 bool LHSIsTrue = true, unsigned Depth = 0);
1058
1059/// Return the boolean condition value in the context of the given instruction
1060/// if it is known based on dominating conditions.
1061LLVM_ABI std::optional<bool>
1062isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI,
1063 const DataLayout &DL);
1064LLVM_ABI std::optional<bool>
1065isImpliedByDomCondition(CmpPredicate Pred, const Value *LHS, const Value *RHS,
1066 const Instruction *ContextI, const DataLayout &DL);
1067
1068/// Call \p InsertAffected on all Values whose known bits / value may be
1069/// affected by the condition \p Cond. Used by AssumptionCache and
1070/// DomConditionCache.
1071LLVM_ABI void
1072findValuesAffectedByCondition(Value *Cond, bool IsAssume,
1073 function_ref<void(Value *)> InsertAffected);
1074
1075/// Returns the inner value X if the expression has the form f(X)
1076/// where f(X) == 0 if and only if X == 0, otherwise returns nullptr.
1077LLVM_ABI Value *stripNullTest(Value *V);
1078LLVM_ABI const Value *stripNullTest(const Value *V);
1079
1080/// Enumerates all possible immediate values of V and inserts them into the set
1081/// \p Constants. If \p AllowUndefOrPoison is false, it fails when V may contain
1082/// undef/poison elements. Returns true if the result is complete. Otherwise,
1083/// the result is incomplete (more than MaxCount values).
1084/// NOTE: The constant values are not distinct.
1085LLVM_ABI bool
1086collectPossibleValues(const Value *V,
1087 SmallPtrSetImpl<const Constant *> &Constants,
1088 unsigned MaxCount, bool AllowUndefOrPoison = true);
1089
1090} // end namespace llvm
1091
1092#endif // LLVM_ANALYSIS_VALUETRACKING_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:215
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
const uint64_t BitWidth
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1583
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
A wrapper class for inspecting calls to intrinsic functions.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
Represents an op.with.overflow intrinsic.
CallInst * Call
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI 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...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
@ Offset
Definition DWP.cpp:578
@ 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.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
LLVM_ABI 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.
LLVM_ABI bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
LLVM_ABI 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...
LLVM_ABI 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.
LLVM_ABI 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.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset)
This function returns call pointer argument that is considered the same by aliasing rules.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI 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...
LLVM_ABI 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,...
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
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_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI 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...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI 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...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
LLVM_ABI 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'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI 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...
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), 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...
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
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.
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
LLVM_ABI 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.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI 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...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI 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...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI 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.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
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.
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
const Instruction * CxtI
const DominatorTree * DT