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