LLVM 19.0.0git
ValueTracking.h
Go to the documentation of this file.
1//===- llvm/Analysis/ValueTracking.h - Walk computations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_VALUETRACKING_H
15#define LLVM_ANALYSIS_VALUETRACKING_H
16
17#include "llvm/ADT/ArrayRef.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/FMF.h"
23#include "llvm/IR/InstrTypes.h"
24#include "llvm/IR/Intrinsics.h"
25#include <cassert>
26#include <cstdint>
27
28namespace llvm {
29
30class Operator;
31class AddOperator;
32class AllocaInst;
33class APInt;
34class AssumptionCache;
35class DominatorTree;
36class GEPOperator;
37class LoadInst;
38class WithOverflowInst;
39struct KnownBits;
40class Loop;
41class LoopInfo;
42class MDNode;
43class StringRef;
44class TargetLibraryInfo;
45class Value;
46
47constexpr unsigned MaxAnalysisRecursionDepth = 6;
48
49/// Determine which bits of V are known to be either zero or one and return
50/// them in the KnownZero/KnownOne bit sets.
51///
52/// This function is defined on values with integer type, values with pointer
53/// type, and vectors of integers. In the case
54/// where V is a vector, the known zero and known one values are the
55/// same width as the vector element, and the bit is set only if it is true
56/// for all of the elements in the vector.
57void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL,
58 unsigned Depth = 0, AssumptionCache *AC = nullptr,
59 const Instruction *CxtI = nullptr,
60 const DominatorTree *DT = nullptr,
61 bool UseInstrInfo = true);
62
63/// Returns the known bits rather than passing by reference.
65 unsigned Depth = 0, AssumptionCache *AC = nullptr,
66 const Instruction *CxtI = nullptr,
67 const DominatorTree *DT = nullptr,
68 bool UseInstrInfo = true);
69
70/// Returns the known bits rather than passing by reference.
71KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
72 const DataLayout &DL, unsigned Depth = 0,
73 AssumptionCache *AC = nullptr,
74 const Instruction *CxtI = nullptr,
75 const DominatorTree *DT = nullptr,
76 bool UseInstrInfo = true);
77
78KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
79 unsigned Depth, const SimplifyQuery &Q);
80
81KnownBits computeKnownBits(const Value *V, unsigned Depth,
82 const SimplifyQuery &Q);
83
84void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
85 const SimplifyQuery &Q);
86
87/// Compute known bits from the range metadata.
88/// \p KnownZero the set of bits that are known to be zero
89/// \p KnownOne the set of bits that are known to be one
90void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known);
91
92/// Merge bits known from context-dependent facts into Known.
93void computeKnownBitsFromContext(const Value *V, KnownBits &Known,
94 unsigned Depth, const SimplifyQuery &Q);
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 unsigned Depth, const SimplifyQuery &SQ);
101
102/// Return true if LHS and RHS have no common bits set.
104 const WithCache<const Value *> &RHSCache,
105 const SimplifyQuery &SQ);
106
107/// Return true if the given value is known to have exactly one bit set when
108/// defined. For vectors return true if every element is known to be a power
109/// of two when defined. Supports values with integer or pointer type and
110/// vectors of integers. If 'OrZero' is set, then return true if the given
111/// value is either a power of two or zero.
112bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
113 bool OrZero = false, unsigned Depth = 0,
114 AssumptionCache *AC = nullptr,
115 const Instruction *CxtI = nullptr,
116 const DominatorTree *DT = nullptr,
117 bool UseInstrInfo = true);
118
120
121/// Return true if the given value is known to be non-zero when defined. For
122/// vectors, return true if every element is known to be non-zero when
123/// defined. For pointers, if the context instruction and dominator tree are
124/// specified, perform context-sensitive analysis and return true if the
125/// pointer couldn't possibly be null at the specified instruction.
126/// Supports values with integer or pointer type and vectors of integers.
127bool isKnownNonZero(const Value *V, unsigned Depth, const SimplifyQuery &Q);
128
129/// Return true if the two given values are negation.
130/// Currently can recoginze Value pair:
131/// 1: <X, Y> if X = sub (0, Y) or Y = sub (0, X)
132/// 2: <X, Y> if X = sub (A, B) and Y = sub (B, A)
133bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW = false);
134
135/// Returns true if the give value is known to be non-negative.
136bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ,
137 unsigned Depth = 0);
138
139/// Returns true if the given value is known be positive (i.e. non-negative
140/// and non-zero).
141bool isKnownPositive(const Value *V, const SimplifyQuery &SQ,
142 unsigned Depth = 0);
143
144/// Returns true if the given value is known be negative (i.e. non-positive
145/// and non-zero).
146bool isKnownNegative(const Value *V, const SimplifyQuery &DL,
147 unsigned Depth = 0);
148
149/// Return true if the given values are known to be non-equal when defined.
150/// Supports scalar integer types only.
151bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL,
152 AssumptionCache *AC = nullptr,
153 const Instruction *CxtI = nullptr,
154 const DominatorTree *DT = nullptr,
155 bool UseInstrInfo = true);
156
157/// Return true if 'V & Mask' is known to be zero. We use this predicate to
158/// simplify operations downstream. Mask is known to be zero for bits that V
159/// cannot have.
160///
161/// This function is defined on values with integer type, values with pointer
162/// type, and vectors of integers. In the case
163/// where V is a vector, the mask, known zero, and known one values are the
164/// same width as the vector element, and the bit is set only if it is true
165/// for all of the elements in the vector.
166bool MaskedValueIsZero(const Value *V, const APInt &Mask,
167 const SimplifyQuery &DL, unsigned Depth = 0);
168
169/// Return the number of times the sign bit of the register is replicated into
170/// the other bits. We know that at least 1 bit is always equal to the sign
171/// bit (itself), but other cases can give us information. For example,
172/// immediately after an "ashr X, 2", we know that the top 3 bits are all
173/// equal to each other, so we return 3. For vectors, return the number of
174/// sign bits for the vector element with the mininum number of known sign
175/// bits.
176unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL,
177 unsigned Depth = 0, AssumptionCache *AC = nullptr,
178 const Instruction *CxtI = nullptr,
179 const DominatorTree *DT = nullptr,
180 bool UseInstrInfo = true);
181
182/// Get the upper bound on bit size for this Value \p Op as a signed integer.
183/// i.e. x == sext(trunc(x to MaxSignificantBits) to bitwidth(x)).
184/// Similar to the APInt::getSignificantBits function.
185unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL,
186 unsigned Depth = 0,
187 AssumptionCache *AC = nullptr,
188 const Instruction *CxtI = nullptr,
189 const DominatorTree *DT = nullptr);
190
191/// Map a call instruction to an intrinsic ID. Libcalls which have equivalent
192/// intrinsics are treated as-if they were intrinsics.
194 const TargetLibraryInfo *TLI);
195
196/// Given an exploded icmp instruction, return true if the comparison only
197/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
198/// the result of the comparison is true when the input value is signed.
200 bool &TrueIfSigned);
201
202/// Returns a pair of values, which if passed to llvm.is.fpclass, returns the
203/// same result as an fcmp with the given operands.
204///
205/// If \p LookThroughSrc is true, consider the input value when computing the
206/// mask.
207///
208/// If \p LookThroughSrc is false, ignore the source value (i.e. the first pair
209/// element will always be LHS.
210std::pair<Value *, FPClassTest> fcmpToClassTest(CmpInst::Predicate Pred,
211 const Function &F, Value *LHS,
212 Value *RHS,
213 bool LookThroughSrc = true);
214std::pair<Value *, FPClassTest> fcmpToClassTest(CmpInst::Predicate Pred,
215 const Function &F, Value *LHS,
216 const APFloat *ConstRHS,
217 bool LookThroughSrc = true);
218
219/// Compute the possible floating-point classes that \p LHS could be based on
220/// fcmp \Pred \p LHS, \p RHS.
221///
222/// \returns { TestedValue, ClassesIfTrue, ClassesIfFalse }
223///
224/// If the compare returns an exact class test, ClassesIfTrue == ~ClassesIfFalse
225///
226/// This is a less exact version of fcmpToClassTest (e.g. fcmpToClassTest will
227/// only succeed for a test of x > 0 implies positive, but not x > 1).
228///
229/// If \p LookThroughSrc is true, consider the input value when computing the
230/// mask. This may look through sign bit operations.
231///
232/// If \p LookThroughSrc is false, ignore the source value (i.e. the first pair
233/// element will always be LHS.
234///
235std::tuple<Value *, FPClassTest, FPClassTest>
237 Value *RHS, bool LookThroughSrc = true);
238std::tuple<Value *, FPClassTest, FPClassTest>
240 FPClassTest RHS, bool LookThroughSrc = true);
241std::tuple<Value *, FPClassTest, FPClassTest>
243 const APFloat &RHS, bool LookThroughSrc = true);
244
246 /// Floating-point classes the value could be one of.
248
249 /// std::nullopt if the sign bit is unknown, true if the sign bit is
250 /// definitely set or false if the sign bit is definitely unset.
251 std::optional<bool> SignBit;
252
254 return KnownFPClasses == Other.KnownFPClasses && SignBit == Other.SignBit;
255 }
256
257 /// Return true if it's known this can never be one of the mask entries.
258 bool isKnownNever(FPClassTest Mask) const {
259 return (KnownFPClasses & Mask) == fcNone;
260 }
261
262 bool isUnknown() const {
263 return KnownFPClasses == fcAllFlags && !SignBit;
264 }
265
266 /// Return true if it's known this can never be a nan.
267 bool isKnownNeverNaN() const {
268 return isKnownNever(fcNan);
269 }
270
271 /// Return true if it's known this can never be an infinity.
272 bool isKnownNeverInfinity() const {
273 return isKnownNever(fcInf);
274 }
275
276 /// Return true if it's known this can never be +infinity.
278 return isKnownNever(fcPosInf);
279 }
280
281 /// Return true if it's known this can never be -infinity.
283 return isKnownNever(fcNegInf);
284 }
285
286 /// Return true if it's known this can never be a subnormal
289 }
290
291 /// Return true if it's known this can never be a positive subnormal
294 }
295
296 /// Return true if it's known this can never be a negative subnormal
299 }
300
301 /// Return true if it's known this can never be a zero. This means a literal
302 /// [+-]0, and does not include denormal inputs implicitly treated as [+-]0.
303 bool isKnownNeverZero() const {
304 return isKnownNever(fcZero);
305 }
306
307 /// Return true if it's known this can never be a literal positive zero.
308 bool isKnownNeverPosZero() const {
309 return isKnownNever(fcPosZero);
310 }
311
312 /// Return true if it's known this can never be a negative zero. This means a
313 /// literal -0 and does not include denormal inputs implicitly treated as -0.
314 bool isKnownNeverNegZero() const {
315 return isKnownNever(fcNegZero);
316 }
317
318 /// Return true if it's know this can never be interpreted as a zero. This
319 /// extends isKnownNeverZero to cover the case where the assumed
320 /// floating-point mode for the function interprets denormals as zero.
321 bool isKnownNeverLogicalZero(const Function &F, Type *Ty) const;
322
323 /// Return true if it's know this can never be interpreted as a negative zero.
324 bool isKnownNeverLogicalNegZero(const Function &F, Type *Ty) const;
325
326 /// Return true if it's know this can never be interpreted as a positive zero.
327 bool isKnownNeverLogicalPosZero(const Function &F, Type *Ty) const;
328
333
334 /// Return true if we can prove that the analyzed floating-point value is
335 /// either NaN or never less than -0.0.
336 ///
337 /// NaN --> true
338 /// +0 --> true
339 /// -0 --> true
340 /// x > +0 --> true
341 /// x < -0 --> false
344 }
345
346 /// Return true if we can prove that the analyzed floating-point value is
347 /// either NaN or never greater than -0.0.
348 /// NaN --> true
349 /// +0 --> true
350 /// -0 --> true
351 /// x > +0 --> false
352 /// x < -0 --> true
355 }
356
358 KnownFPClasses = KnownFPClasses | RHS.KnownFPClasses;
359
360 if (SignBit != RHS.SignBit)
361 SignBit = std::nullopt;
362 return *this;
363 }
364
365 void knownNot(FPClassTest RuleOut) {
366 KnownFPClasses = KnownFPClasses & ~RuleOut;
367 if (isKnownNever(fcNan) && !SignBit) {
369 SignBit = false;
370 else if (isKnownNever(fcPositive))
371 SignBit = true;
372 }
373 }
374
375 void fneg() {
377 if (SignBit)
378 SignBit = !*SignBit;
379 }
380
381 void fabs() {
384
387
390
393
395 }
396
397 /// Return true if the sign bit must be 0, ignoring the sign of nans.
398 bool signBitIsZeroOrNaN() const {
399 return isKnownNever(fcNegative);
400 }
401
402 /// Assume the sign bit is zero.
405 SignBit = false;
406 }
407
408 /// Assume the sign bit is one.
411 SignBit = true;
412 }
413
414 void copysign(const KnownFPClass &Sign) {
415 // Don't know anything about the sign of the source. Expand the possible set
416 // to its opposite sign pair.
423 if (KnownFPClasses & fcInf)
425
426 // Sign bit is exactly preserved even for nans.
427 SignBit = Sign.SignBit;
428
429 // Clear sign bits based on the input sign mask.
430 if (Sign.isKnownNever(fcPositive | fcNan) || (SignBit && *SignBit))
432 if (Sign.isKnownNever(fcNegative | fcNan) || (SignBit && !*SignBit))
434 }
435
436 // Propagate knowledge that a non-NaN source implies the result can also not
437 // be a NaN. For unconstrained operations, signaling nans are not guaranteed
438 // to be quieted but cannot be introduced.
439 void propagateNaN(const KnownFPClass &Src, bool PreserveSign = false) {
440 if (Src.isKnownNever(fcNan)) {
442 if (PreserveSign)
443 SignBit = Src.SignBit;
444 } else if (Src.isKnownNever(fcSNan))
446 }
447
448 /// Propagate knowledge from a source value that could be a denormal or
449 /// zero. We have to be conservative since output flushing is not guaranteed,
450 /// so known-never-zero may not hold.
451 ///
452 /// This assumes a copy-like operation and will replace any currently known
453 /// information.
454 void propagateDenormal(const KnownFPClass &Src, const Function &F, Type *Ty);
455
456 /// Report known classes if \p Src is evaluated through a potentially
457 /// canonicalizing operation. We can assume signaling nans will not be
458 /// introduced, but cannot assume a denormal will be flushed under FTZ/DAZ.
459 ///
460 /// This assumes a copy-like operation and will replace any currently known
461 /// information.
462 void propagateCanonicalizingSrc(const KnownFPClass &Src, const Function &F,
463 Type *Ty);
464
465 void resetAll() { *this = KnownFPClass(); }
466};
467
469 LHS |= RHS;
470 return LHS;
471}
472
474 RHS |= LHS;
475 return std::move(RHS);
476}
477
478/// Determine which floating-point classes are valid for \p V, and return them
479/// in KnownFPClass bit sets.
480///
481/// This function is defined on values with floating-point type, values vectors
482/// of floating-point type, and arrays of floating-point type.
483
484/// \p InterestedClasses is a compile time optimization hint for which floating
485/// point classes should be queried. Queries not specified in \p
486/// InterestedClasses should be reliable if they are determined during the
487/// query.
488KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts,
489 FPClassTest InterestedClasses, unsigned Depth,
490 const SimplifyQuery &SQ);
491
492KnownFPClass computeKnownFPClass(const Value *V, FPClassTest InterestedClasses,
493 unsigned Depth, const SimplifyQuery &SQ);
494
496 const Value *V, const DataLayout &DL,
497 FPClassTest InterestedClasses = fcAllFlags, unsigned Depth = 0,
498 const TargetLibraryInfo *TLI = nullptr, AssumptionCache *AC = nullptr,
499 const Instruction *CxtI = nullptr, const DominatorTree *DT = nullptr,
500 bool UseInstrInfo = true) {
501 return computeKnownFPClass(
502 V, InterestedClasses, Depth,
503 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo));
504}
505
506/// Wrapper to account for known fast math flags at the use instruction.
508 FPClassTest InterestedClasses,
509 unsigned Depth,
510 const SimplifyQuery &SQ) {
511 if (FMF.noNaNs())
512 InterestedClasses &= ~fcNan;
513 if (FMF.noInfs())
514 InterestedClasses &= ~fcInf;
515
516 KnownFPClass Result = computeKnownFPClass(V, InterestedClasses, Depth, SQ);
517
518 if (FMF.noNaNs())
519 Result.KnownFPClasses &= ~fcNan;
520 if (FMF.noInfs())
521 Result.KnownFPClasses &= ~fcInf;
522 return Result;
523}
524
525/// Return true if we can prove that the specified FP value is never equal to
526/// -0.0. Users should use caution when considering PreserveSign
527/// denormal-fp-math.
528inline bool cannotBeNegativeZero(const Value *V, unsigned Depth,
529 const SimplifyQuery &SQ) {
531 return Known.isKnownNeverNegZero();
532}
533
534/// Return true if we can prove that the specified FP value is either NaN or
535/// never less than -0.0.
536///
537/// NaN --> true
538/// +0 --> true
539/// -0 --> true
540/// x > +0 --> true
541/// x < -0 --> false
542inline bool cannotBeOrderedLessThanZero(const Value *V, unsigned Depth,
543 const SimplifyQuery &SQ) {
544 KnownFPClass Known =
546 return Known.cannotBeOrderedLessThanZero();
547}
548
549/// Return true if the floating-point scalar value is not an infinity or if
550/// the floating-point vector value has no infinities. Return false if a value
551/// could ever be infinity.
552inline bool isKnownNeverInfinity(const Value *V, unsigned Depth,
553 const SimplifyQuery &SQ) {
555 return Known.isKnownNeverInfinity();
556}
557
558/// Return true if the floating-point value can never contain a NaN or infinity.
559inline bool isKnownNeverInfOrNaN(const Value *V, unsigned Depth,
560 const SimplifyQuery &SQ) {
562 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
563}
564
565/// Return true if the floating-point scalar value is not a NaN or if the
566/// floating-point vector value has no NaN elements. Return false if a value
567/// could ever be NaN.
568inline bool isKnownNeverNaN(const Value *V, unsigned Depth,
569 const SimplifyQuery &SQ) {
571 return Known.isKnownNeverNaN();
572}
573
574/// Return false if we can prove that the specified FP value's sign bit is 0.
575/// Return true if we can prove that the specified FP value's sign bit is 1.
576/// Otherwise return std::nullopt.
577inline std::optional<bool> computeKnownFPSignBit(const Value *V, unsigned Depth,
578 const SimplifyQuery &SQ) {
580 return Known.SignBit;
581}
582
583/// If the specified value can be set by repeating the same byte in memory,
584/// return the i8 value that it is represented with. This is true for all i8
585/// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
586/// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
587/// i16 0x1234), return null. If the value is entirely undef and padding,
588/// return undef.
589Value *isBytewiseValue(Value *V, const DataLayout &DL);
590
591/// Given an aggregate and an sequence of indices, see if the scalar value
592/// indexed is already around as a register, for example if it were inserted
593/// directly into the aggregate.
594///
595/// If InsertBefore is not empty, this function will duplicate (modified)
596/// insertvalues when a part of a nested struct is extracted.
597Value *FindInsertedValue(
598 Value *V, ArrayRef<unsigned> idx_range,
599 std::optional<BasicBlock::iterator> InsertBefore = std::nullopt);
600
601/// Analyze the specified pointer to see if it can be expressed as a base
602/// pointer plus a constant offset. Return the base and offset to the caller.
603///
604/// This is a wrapper around Value::stripAndAccumulateConstantOffsets that
605/// creates and later unpacks the required APInt.
607 const DataLayout &DL,
608 bool AllowNonInbounds = true) {
609 APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
610 Value *Base =
611 Ptr->stripAndAccumulateConstantOffsets(DL, OffsetAPInt, AllowNonInbounds);
612
613 Offset = OffsetAPInt.getSExtValue();
614 return Base;
615}
616inline const Value *
618 const DataLayout &DL,
619 bool AllowNonInbounds = true) {
620 return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset, DL,
621 AllowNonInbounds);
622}
623
624/// Returns true if the GEP is based on a pointer to a string (array of
625// \p CharSize integers) and is indexing into this string.
626bool isGEPBasedOnPointerToString(const GEPOperator *GEP, unsigned CharSize = 8);
627
628/// Represents offset+length into a ConstantDataArray.
630 /// ConstantDataArray pointer. nullptr indicates a zeroinitializer (a valid
631 /// initializer, it just doesn't fit the ConstantDataArray interface).
633
634 /// Slice starts at this Offset.
636
637 /// Length of the slice.
639
640 /// Moves the Offset and adjusts Length accordingly.
641 void move(uint64_t Delta) {
642 assert(Delta < Length);
643 Offset += Delta;
644 Length -= Delta;
645 }
646
647 /// Convenience accessor for elements in the slice.
648 uint64_t operator[](unsigned I) const {
649 return Array == nullptr ? 0 : Array->getElementAsInteger(I + Offset);
650 }
651};
652
653/// Returns true if the value \p V is a pointer into a ConstantDataArray.
654/// If successful \p Slice will point to a ConstantDataArray info object
655/// with an appropriate offset.
656bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice,
657 unsigned ElementSize, uint64_t Offset = 0);
658
659/// This function computes the length of a null-terminated C string pointed to
660/// by V. If successful, it returns true and returns the string in Str. If
661/// unsuccessful, it returns false. This does not include the trailing null
662/// character by default. If TrimAtNul is set to false, then this returns any
663/// trailing null characters as well as any other characters that come after
664/// it.
665bool getConstantStringInfo(const Value *V, StringRef &Str,
666 bool TrimAtNul = true);
667
668/// If we can compute the length of the string pointed to by the specified
669/// pointer, return 'len+1'. If we can't, return 0.
670uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
671
672/// This function returns call pointer argument that is considered the same by
673/// aliasing rules. You CAN'T use it to replace one value with another. If
674/// \p MustPreserveNullness is true, the call must preserve the nullness of
675/// the pointer.
676const Value *getArgumentAliasingToReturnedPointer(const CallBase *Call,
677 bool MustPreserveNullness);
679 bool MustPreserveNullness) {
680 return const_cast<Value *>(getArgumentAliasingToReturnedPointer(
681 const_cast<const CallBase *>(Call), MustPreserveNullness));
682}
683
684/// {launder,strip}.invariant.group returns pointer that aliases its argument,
685/// and it only captures pointer by returning it.
686/// These intrinsics are not marked as nocapture, because returning is
687/// considered as capture. The arguments are not marked as returned neither,
688/// because it would make it useless. If \p MustPreserveNullness is true,
689/// the intrinsic must preserve the nullness of the pointer.
691 const CallBase *Call, bool MustPreserveNullness);
692
693/// This method strips off any GEP address adjustments and pointer casts from
694/// the specified value, returning the original object being addressed. Note
695/// that the returned value has pointer type if the specified value does. If
696/// the MaxLookup value is non-zero, it limits the number of instructions to
697/// be stripped off.
698const Value *getUnderlyingObject(const Value *V, unsigned MaxLookup = 6);
699inline Value *getUnderlyingObject(Value *V, unsigned MaxLookup = 6) {
700 // Force const to avoid infinite recursion.
701 const Value *VConst = V;
702 return const_cast<Value *>(getUnderlyingObject(VConst, MaxLookup));
703}
704
705/// This method is similar to getUnderlyingObject except that it can
706/// look through phi and select instructions and return multiple objects.
707///
708/// If LoopInfo is passed, loop phis are further analyzed. If a pointer
709/// accesses different objects in each iteration, we don't look through the
710/// phi node. E.g. consider this loop nest:
711///
712/// int **A;
713/// for (i)
714/// for (j) {
715/// A[i][j] = A[i-1][j] * B[j]
716/// }
717///
718/// This is transformed by Load-PRE to stash away A[i] for the next iteration
719/// of the outer loop:
720///
721/// Curr = A[0]; // Prev_0
722/// for (i: 1..N) {
723/// Prev = Curr; // Prev = PHI (Prev_0, Curr)
724/// Curr = A[i];
725/// for (j: 0..N) {
726/// Curr[j] = Prev[j] * B[j]
727/// }
728/// }
729///
730/// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
731/// should not assume that Curr and Prev share the same underlying object thus
732/// it shouldn't look through the phi above.
733void getUnderlyingObjects(const Value *V,
734 SmallVectorImpl<const Value *> &Objects,
735 LoopInfo *LI = nullptr, unsigned MaxLookup = 6);
736
737/// This is a wrapper around getUnderlyingObjects and adds support for basic
738/// ptrtoint+arithmetic+inttoptr sequences.
739bool getUnderlyingObjectsForCodeGen(const Value *V,
740 SmallVectorImpl<Value *> &Objects);
741
742/// Returns unique alloca where the value comes from, or nullptr.
743/// If OffsetZero is true check that V points to the begining of the alloca.
744AllocaInst *findAllocaForValue(Value *V, bool OffsetZero = false);
745inline const AllocaInst *findAllocaForValue(const Value *V,
746 bool OffsetZero = false) {
747 return findAllocaForValue(const_cast<Value *>(V), OffsetZero);
748}
749
750/// Return true if the only users of this pointer are lifetime markers.
751bool onlyUsedByLifetimeMarkers(const Value *V);
752
753/// Return true if the only users of this pointer are lifetime markers or
754/// droppable instructions.
756
757/// Return true if speculation of the given load must be suppressed to avoid
758/// ordering or interfering with an active sanitizer. If not suppressed,
759/// dereferenceability and alignment must be proven separately. Note: This
760/// is only needed for raw reasoning; if you use the interface below
761/// (isSafeToSpeculativelyExecute), this is handled internally.
762bool mustSuppressSpeculation(const LoadInst &LI);
763
764/// Return true if the instruction does not have any effects besides
765/// calculating the result and does not have undefined behavior.
766///
767/// This method never returns true for an instruction that returns true for
768/// mayHaveSideEffects; however, this method also does some other checks in
769/// addition. It checks for undefined behavior, like dividing by zero or
770/// loading from an invalid pointer (but not for undefined results, like a
771/// shift with a shift amount larger than the width of the result). It checks
772/// for malloc and alloca because speculatively executing them might cause a
773/// memory leak. It also returns false for instructions related to control
774/// flow, specifically terminators and PHI nodes.
775///
776/// If the CtxI is specified this method performs context-sensitive analysis
777/// and returns true if it is safe to execute the instruction immediately
778/// before the CtxI.
779///
780/// If the CtxI is NOT specified this method only looks at the instruction
781/// itself and its operands, so if this method returns true, it is safe to
782/// move the instruction as long as the correct dominance relationships for
783/// the operands and users hold.
784///
785/// This method can return true for instructions that read memory;
786/// for such instructions, moving them may change the resulting value.
787bool isSafeToSpeculativelyExecute(const Instruction *I,
788 const Instruction *CtxI = nullptr,
789 AssumptionCache *AC = nullptr,
790 const DominatorTree *DT = nullptr,
791 const TargetLibraryInfo *TLI = nullptr);
792
793inline bool
795 AssumptionCache *AC = nullptr,
796 const DominatorTree *DT = nullptr,
797 const TargetLibraryInfo *TLI = nullptr) {
798 // Take an iterator, and unwrap it into an Instruction *.
799 return isSafeToSpeculativelyExecute(I, &*CtxI, AC, DT, TLI);
800}
801
802/// This returns the same result as isSafeToSpeculativelyExecute if Opcode is
803/// the actual opcode of Inst. If the provided and actual opcode differ, the
804/// function (virtually) overrides the opcode of Inst with the provided
805/// Opcode. There are come constraints in this case:
806/// * If Opcode has a fixed number of operands (eg, as binary operators do),
807/// then Inst has to have at least as many leading operands. The function
808/// will ignore all trailing operands beyond that number.
809/// * If Opcode allows for an arbitrary number of operands (eg, as CallInsts
810/// do), then all operands are considered.
811/// * The virtual instruction has to satisfy all typing rules of the provided
812/// Opcode.
813/// * This function is pessimistic in the following sense: If one actually
814/// materialized the virtual instruction, then isSafeToSpeculativelyExecute
815/// may say that the materialized instruction is speculatable whereas this
816/// function may have said that the instruction wouldn't be speculatable.
817/// This behavior is a shortcoming in the current implementation and not
818/// intentional.
820 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI = nullptr,
821 AssumptionCache *AC = nullptr, const DominatorTree *DT = nullptr,
822 const TargetLibraryInfo *TLI = nullptr);
823
824/// Returns true if the result or effects of the given instructions \p I
825/// depend values not reachable through the def use graph.
826/// * Memory dependence arises for example if the instruction reads from
827/// memory or may produce effects or undefined behaviour. Memory dependent
828/// instructions generally cannot be reorderd with respect to other memory
829/// dependent instructions.
830/// * Control dependence arises for example if the instruction may fault
831/// if lifted above a throwing call or infinite loop.
832bool mayHaveNonDefUseDependency(const Instruction &I);
833
834/// Return true if it is an intrinsic that cannot be speculated but also
835/// cannot trap.
836bool isAssumeLikeIntrinsic(const Instruction *I);
837
838/// Return true if it is valid to use the assumptions provided by an
839/// assume intrinsic, I, at the point in the control-flow identified by the
840/// context instruction, CxtI. By default, ephemeral values of the assumption
841/// are treated as an invalid context, to prevent the assumption from being used
842/// to optimize away its argument. If the caller can ensure that this won't
843/// happen, it can call with AllowEphemerals set to true to get more valid
844/// assumptions.
845bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
846 const DominatorTree *DT = nullptr,
847 bool AllowEphemerals = false);
848
849enum class OverflowResult {
850 /// Always overflows in the direction of signed/unsigned min value.
852 /// Always overflows in the direction of signed/unsigned max value.
854 /// May or may not overflow.
856 /// Never overflows.
858};
859
860OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS,
861 const SimplifyQuery &SQ);
862OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
863 const SimplifyQuery &SQ);
865computeOverflowForUnsignedAdd(const WithCache<const Value *> &LHS,
866 const WithCache<const Value *> &RHS,
867 const SimplifyQuery &SQ);
868OverflowResult computeOverflowForSignedAdd(const WithCache<const Value *> &LHS,
869 const WithCache<const Value *> &RHS,
870 const SimplifyQuery &SQ);
871/// This version also leverages the sign bit of Add if known.
873 const SimplifyQuery &SQ);
874OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS,
875 const SimplifyQuery &SQ);
876OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
877 const SimplifyQuery &SQ);
878
879/// Returns true if the arithmetic part of the \p WO 's result is
880/// used only along the paths control dependent on the computation
881/// not overflowing, \p WO being an <op>.with.overflow intrinsic.
882bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
883 const DominatorTree &DT);
884
885/// Determine the possible constant range of vscale with the given bit width,
886/// based on the vscale_range function attribute.
887ConstantRange getVScaleRange(const Function *F, unsigned BitWidth);
888
889/// Determine the possible constant range of an integer or vector of integer
890/// value. This is intended as a cheap, non-recursive check.
891ConstantRange computeConstantRange(const Value *V, bool ForSigned,
892 bool UseInstrInfo = true,
893 AssumptionCache *AC = nullptr,
894 const Instruction *CtxI = nullptr,
895 const DominatorTree *DT = nullptr,
896 unsigned Depth = 0);
897
898/// Combine constant ranges from computeConstantRange() and computeKnownBits().
899ConstantRange
900computeConstantRangeIncludingKnownBits(const WithCache<const Value *> &V,
901 bool ForSigned, const SimplifyQuery &SQ);
902
903/// Return true if this function can prove that the instruction I will
904/// always transfer execution to one of its successors (including the next
905/// instruction that follows within a basic block). E.g. this is not
906/// guaranteed for function calls that could loop infinitely.
907///
908/// In other words, this function returns false for instructions that may
909/// transfer execution or fail to transfer execution in a way that is not
910/// captured in the CFG nor in the sequence of instructions within a basic
911/// block.
912///
913/// Undefined behavior is assumed not to happen, so e.g. division is
914/// guaranteed to transfer execution to the following instruction even
915/// though division by zero might cause undefined behavior.
916bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
917
918/// Returns true if this block does not contain a potential implicit exit.
919/// This is equivelent to saying that all instructions within the basic block
920/// are guaranteed to transfer execution to their successor within the basic
921/// block. This has the same assumptions w.r.t. undefined behavior as the
922/// instruction variant of this function.
923bool isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB);
924
925/// Return true if every instruction in the range (Begin, End) is
926/// guaranteed to transfer execution to its static successor. \p ScanLimit
927/// bounds the search to avoid scanning huge blocks.
930 unsigned ScanLimit = 32);
931
932/// Same as previous, but with range expressed via iterator_range.
934 iterator_range<BasicBlock::const_iterator> Range, unsigned ScanLimit = 32);
935
936/// Return true if this function can prove that the instruction I
937/// is executed for every iteration of the loop L.
938///
939/// Note that this currently only considers the loop header.
940bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
941 const Loop *L);
942
943/// Return true if \p PoisonOp's user yields poison or raises UB if its
944/// operand \p PoisonOp is poison.
945///
946/// If \p PoisonOp is a vector or an aggregate and the operation's result is a
947/// single value, any poison element in /p PoisonOp should make the result
948/// poison or raise UB.
949///
950/// To filter out operands that raise UB on poison, you can use
951/// getGuaranteedNonPoisonOp.
952bool propagatesPoison(const Use &PoisonOp);
953
954/// Insert operands of I into Ops such that I will trigger undefined behavior
955/// if I is executed and that operand has a poison value.
956void getGuaranteedNonPoisonOps(const Instruction *I,
957 SmallVectorImpl<const Value *> &Ops);
958
959/// Insert operands of I into Ops such that I will trigger undefined behavior
960/// if I is executed and that operand is not a well-defined value
961/// (i.e. has undef bits or poison).
962void getGuaranteedWellDefinedOps(const Instruction *I,
963 SmallVectorImpl<const Value *> &Ops);
964
965/// Return true if the given instruction must trigger undefined behavior
966/// when I is executed with any operands which appear in KnownPoison holding
967/// a poison value at the point of execution.
968bool mustTriggerUB(const Instruction *I,
969 const SmallPtrSetImpl<const Value *> &KnownPoison);
970
971/// Return true if this function can prove that if Inst is executed
972/// and yields a poison value or undef bits, then that will trigger
973/// undefined behavior.
974///
975/// Note that this currently only considers the basic block that is
976/// the parent of Inst.
977bool programUndefinedIfUndefOrPoison(const Instruction *Inst);
978bool programUndefinedIfPoison(const Instruction *Inst);
979
980/// canCreateUndefOrPoison returns true if Op can create undef or poison from
981/// non-undef & non-poison operands.
982/// For vectors, canCreateUndefOrPoison returns true if there is potential
983/// poison or undef in any element of the result when vectors without
984/// undef/poison poison are given as operands.
985/// For example, given `Op = shl <2 x i32> %x, <0, 32>`, this function returns
986/// true. If Op raises immediate UB but never creates poison or undef
987/// (e.g. sdiv I, 0), canCreatePoison returns false.
988///
989/// \p ConsiderFlagsAndMetadata controls whether poison producing flags and
990/// metadata on the instruction are considered. This can be used to see if the
991/// instruction could still introduce undef or poison even without poison
992/// generating flags and metadata which might be on the instruction.
993/// (i.e. could the result of Op->dropPoisonGeneratingFlags() still create
994/// poison or undef)
995///
996/// canCreatePoison returns true if Op can create poison from non-poison
997/// operands.
998bool canCreateUndefOrPoison(const Operator *Op,
999 bool ConsiderFlagsAndMetadata = true);
1000bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata = true);
1001
1002/// Return true if V is poison given that ValAssumedPoison is already poison.
1003/// For example, if ValAssumedPoison is `icmp X, 10` and V is `icmp X, 5`,
1004/// impliesPoison returns true.
1005bool impliesPoison(const Value *ValAssumedPoison, const Value *V);
1006
1007/// Return true if this function can prove that V does not have undef bits
1008/// and is never poison. If V is an aggregate value or vector, check whether
1009/// all elements (except padding) are not undef or poison.
1010/// Note that this is different from canCreateUndefOrPoison because the
1011/// function assumes Op's operands are not poison/undef.
1012///
1013/// If CtxI and DT are specified this method performs flow-sensitive analysis
1014/// and returns true if it is guaranteed to be never undef or poison
1015/// immediately before the CtxI.
1016bool isGuaranteedNotToBeUndefOrPoison(const Value *V,
1017 AssumptionCache *AC = nullptr,
1018 const Instruction *CtxI = nullptr,
1019 const DominatorTree *DT = nullptr,
1020 unsigned Depth = 0);
1021
1022/// Returns true if V cannot be poison, but may be undef.
1023bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC = nullptr,
1024 const Instruction *CtxI = nullptr,
1025 const DominatorTree *DT = nullptr,
1026 unsigned Depth = 0);
1027
1030 const DominatorTree *DT = nullptr,
1031 unsigned Depth = 0) {
1032 // Takes an iterator as a position, passes down to Instruction *
1033 // implementation.
1034 return isGuaranteedNotToBePoison(V, AC, &*CtxI, DT, Depth);
1035}
1036
1037/// Returns true if V cannot be undef, but may be poison.
1038bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC = nullptr,
1039 const Instruction *CtxI = nullptr,
1040 const DominatorTree *DT = nullptr,
1041 unsigned Depth = 0);
1042
1043/// Return true if undefined behavior would provable be executed on the path to
1044/// OnPathTo if Root produced a posion result. Note that this doesn't say
1045/// anything about whether OnPathTo is actually executed or whether Root is
1046/// actually poison. This can be used to assess whether a new use of Root can
1047/// be added at a location which is control equivalent with OnPathTo (such as
1048/// immediately before it) without introducing UB which didn't previously
1049/// exist. Note that a false result conveys no information.
1050bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root,
1051 Instruction *OnPathTo,
1052 DominatorTree *DT);
1053
1054/// Specific patterns of select instructions we can match.
1057 SPF_SMIN, /// Signed minimum
1058 SPF_UMIN, /// Unsigned minimum
1059 SPF_SMAX, /// Signed maximum
1060 SPF_UMAX, /// Unsigned maximum
1061 SPF_FMINNUM, /// Floating point minnum
1062 SPF_FMAXNUM, /// Floating point maxnum
1063 SPF_ABS, /// Absolute value
1064 SPF_NABS /// Negated absolute value
1066
1067/// Behavior when a floating point min/max is given one NaN and one
1068/// non-NaN as input.
1070 SPNB_NA = 0, /// NaN behavior not applicable.
1071 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
1072 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
1073 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
1074 /// it has been determined that no operands can
1075 /// be NaN).
1077
1080 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
1081 /// SPF_FMINNUM or SPF_FMAXNUM.
1082 bool Ordered; /// When implementing this min/max pattern as
1083 /// fcmp; select, does the fcmp have to be
1084 /// ordered?
1085
1086 /// Return true if \p SPF is a min or a max pattern.
1088 return SPF != SPF_UNKNOWN && SPF != SPF_ABS && SPF != SPF_NABS;
1089 }
1090};
1091
1092/// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
1093/// and providing the out parameter results if we successfully match.
1094///
1095/// For ABS/NABS, LHS will be set to the input to the abs idiom. RHS will be
1096/// the negation instruction from the idiom.
1097///
1098/// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
1099/// not match that of the original select. If this is the case, the cast
1100/// operation (one of Trunc,SExt,Zext) that must be done to transform the
1101/// type of LHS and RHS into the type of V is returned in CastOp.
1102///
1103/// For example:
1104/// %1 = icmp slt i32 %a, i32 4
1105/// %2 = sext i32 %a to i64
1106/// %3 = select i1 %1, i64 %2, i64 4
1107///
1108/// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
1109///
1110SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
1111 Instruction::CastOps *CastOp = nullptr,
1112 unsigned Depth = 0);
1113
1115 const Value *&RHS) {
1116 Value *L = const_cast<Value *>(LHS);
1117 Value *R = const_cast<Value *>(RHS);
1118 auto Result = matchSelectPattern(const_cast<Value *>(V), L, R);
1119 LHS = L;
1120 RHS = R;
1121 return Result;
1122}
1123
1124/// Determine the pattern that a select with the given compare as its
1125/// predicate and given values as its true/false operands would match.
1126SelectPatternResult matchDecomposedSelectPattern(
1127 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
1128 Instruction::CastOps *CastOp = nullptr, unsigned Depth = 0);
1129
1130/// Return the canonical comparison predicate for the specified
1131/// minimum/maximum flavor.
1132CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered = false);
1133
1134/// Return the inverse minimum/maximum flavor of the specified flavor.
1135/// For example, signed minimum is the inverse of signed maximum.
1137
1139
1140/// Return the minimum or maximum constant value for the specified integer
1141/// min/max flavor and type.
1142APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth);
1143
1144/// Check if the values in \p VL are select instructions that can be converted
1145/// to a min or max (vector) intrinsic. Returns the intrinsic ID, if such a
1146/// conversion is possible, together with a bool indicating whether all select
1147/// conditions are only used by the selects. Otherwise return
1148/// Intrinsic::not_intrinsic.
1149std::pair<Intrinsic::ID, bool>
1150canConvertToMinOrMaxIntrinsic(ArrayRef<Value *> VL);
1151
1152/// Attempt to match a simple first order recurrence cycle of the form:
1153/// %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
1154/// %inc = binop %iv, %step
1155/// OR
1156/// %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
1157/// %inc = binop %step, %iv
1158///
1159/// A first order recurrence is a formula with the form: X_n = f(X_(n-1))
1160///
1161/// A couple of notes on subtleties in that definition:
1162/// * The Step does not have to be loop invariant. In math terms, it can
1163/// be a free variable. We allow recurrences with both constant and
1164/// variable coefficients. Callers may wish to filter cases where Step
1165/// does not dominate P.
1166/// * For non-commutative operators, we will match both forms. This
1167/// results in some odd recurrence structures. Callers may wish to filter
1168/// out recurrences where the phi is not the LHS of the returned operator.
1169/// * Because of the structure matched, the caller can assume as a post
1170/// condition of the match the presence of a Loop with P's parent as it's
1171/// header *except* in unreachable code. (Dominance decays in unreachable
1172/// code.)
1173///
1174/// NOTE: This is intentional simple. If you want the ability to analyze
1175/// non-trivial loop conditons, see ScalarEvolution instead.
1176bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start,
1177 Value *&Step);
1178
1179/// Analogous to the above, but starting from the binary operator
1180bool matchSimpleRecurrence(const BinaryOperator *I, PHINode *&P, Value *&Start,
1181 Value *&Step);
1182
1183/// Return true if RHS is known to be implied true by LHS. Return false if
1184/// RHS is known to be implied false by LHS. Otherwise, return std::nullopt if
1185/// no implication can be made. A & B must be i1 (boolean) values or a vector of
1186/// such values. Note that the truth table for implication is the same as <=u on
1187/// i1 values (but not
1188/// <=s!). The truth table for both is:
1189/// | T | F (B)
1190/// T | T | F
1191/// F | T | T
1192/// (A)
1193std::optional<bool> isImpliedCondition(const Value *LHS, const Value *RHS,
1194 const DataLayout &DL,
1195 bool LHSIsTrue = true,
1196 unsigned Depth = 0);
1197std::optional<bool> isImpliedCondition(const Value *LHS,
1198 CmpInst::Predicate RHSPred,
1199 const Value *RHSOp0, const Value *RHSOp1,
1200 const DataLayout &DL,
1201 bool LHSIsTrue = true,
1202 unsigned Depth = 0);
1203
1204/// Return the boolean condition value in the context of the given instruction
1205/// if it is known based on dominating conditions.
1206std::optional<bool> isImpliedByDomCondition(const Value *Cond,
1207 const Instruction *ContextI,
1208 const DataLayout &DL);
1209std::optional<bool> isImpliedByDomCondition(CmpInst::Predicate Pred,
1210 const Value *LHS, const Value *RHS,
1211 const Instruction *ContextI,
1212 const DataLayout &DL);
1213
1214/// Call \p InsertAffected on all Values whose known bits / value may be
1215/// affected by the condition \p Cond. Used by AssumptionCache and
1216/// DomConditionCache.
1217void findValuesAffectedByCondition(Value *Cond, bool IsAssume,
1218 function_ref<void(Value *)> InsertAffected);
1219
1220} // end namespace llvm
1221
1222#endif // LLVM_ANALYSIS_VALUETRACKING_H
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool End
Definition: ELF_riscv.cpp:480
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
Hexagon Common GEP
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:76
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1513
an instruction to allocate memory on the stack
Definition: Instructions.h:59
A cache of @llvm.assume calls within a function.
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:166
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1467
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:966
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition: Constants.h:692
uint64_t getElementAsInteger(unsigned i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
Definition: Constants.cpp:3005
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
bool noInfs() const
Definition: FMF.h:67
bool noNaNs() const
Definition: FMF.h:66
Metadata node.
Definition: Metadata.h:1067
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition: Operator.h:31
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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.
bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ Offset
Definition: DWP.cpp:456
OverflowResult
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
bool 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,...
bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &DL, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
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...
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false)
Return true if the two given values are negation.
bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
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.
const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveNullness)
This function returns call pointer argument that is considered the same by aliasing rules.
bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
bool isKnownNeverInfinity(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
void getGuaranteedNonPoisonOps(const Instruction *I, SmallVectorImpl< const Value * > &Ops)
Insert operands of I into Ops such that I will trigger undefined behavior if I is executed and that o...
bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value,...
bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to have exactly one bit set when defined.
bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
bool isKnownNeverInfOrNaN(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if the floating-point value can never contain a NaN or infinity.
CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
void computeKnownBitsFromContext(const Value *V, KnownBits &Known, unsigned Depth, const SimplifyQuery &Q)
Merge bits known from context-dependent facts into Known.
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.
ConstantRange computeConstantRange(const Value *V, bool ForSigned, bool UseInstrInfo=true, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, unsigned Depth, const SimplifyQuery &SQ)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
Definition: ValueTracking.h:47
void getGuaranteedWellDefinedOps(const Instruction *I, SmallVectorImpl< const Value * > &Ops)
Insert operands of I into Ops such that I will trigger undefined behavior if I is executed and that o...
FPClassTest fneg(FPClassTest Mask)
Return the test mask which returns true if the value's sign bit is flipped.
OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Compute the possible floating-point classes that LHS could be based on fcmp \Pred LHS,...
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.
bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveNullness)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool programUndefinedIfPoison(const Instruction *Inst)
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ Other
Any other memory.
void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
bool isKnownNegative(const Value *V, const SimplifyQuery &DL, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given values are known to be non-equal when defined.
@ Add
Sum of integers.
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.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
DWARFExpression::Operation Op
bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:191
SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
std::pair< Value *, FPClassTest > fcmpToClassTest(CmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Returns a pair of values, which if passed to llvm.is.fpclass, returns the same result as an fcmp with...
Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
std::optional< bool > computeKnownFPSignBit(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return false if we can prove that the specified FP value's sign bit is 0.
bool cannotBeOrderedLessThanZero(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return the number of times the sign bit of the register is replicated into the other bits.
bool cannotBeNegativeZero(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if we can prove that the specified FP value is never equal to -0.0.
OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
bool isKnownNeverNaN(const Value *V, unsigned Depth, const SimplifyQuery &SQ)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
bool isKnownNonZero(const Value *V, unsigned Depth, const SimplifyQuery &Q)
Return true if the given value is known to be non-zero when defined.
bool isGEPBasedOnPointerToString(const GEPOperator *GEP, unsigned CharSize=8)
Returns true if the GEP is based on a pointer to a string (array of.
APInt operator|(APInt a, const APInt &b)
Definition: APInt.h:2073
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.
KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, unsigned Depth, const SimplifyQuery &SQ)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
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...
bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Get the upper bound on bit size for this Value Op as a signed integer.
bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
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.
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.
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
bool isKnownNeverInfinity() const
Return true if it's known this can never be an infinity.
bool cannotBeOrderedGreaterThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never greater tha...
static constexpr FPClassTest OrderedGreaterThanZeroMask
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
bool isKnownNeverZero() const
Return true if it's known this can never be a zero.
void copysign(const KnownFPClass &Sign)
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
bool isKnownNeverLogicalNegZero(const Function &F, Type *Ty) const
Return true if it's know this can never be interpreted as a negative zero.
bool isKnownNeverLogicalPosZero(const Function &F, Type *Ty) const
Return true if it's know this can never be interpreted as a positive zero.
KnownFPClass & operator|=(const KnownFPClass &RHS)
void propagateCanonicalizingSrc(const KnownFPClass &Src, const Function &F, Type *Ty)
Report known classes if Src is evaluated through a potentially canonicalizing operation.
void propagateDenormal(const KnownFPClass &Src, const Function &F, Type *Ty)
Propagate knowledge from a source value that could be a denormal or zero.
bool isUnknown() const
bool isKnownNeverNegInfinity() const
Return true if it's known this can never be -infinity.
bool isKnownNeverNegSubnormal() const
Return true if it's known this can never be a negative subnormal.
bool isKnownNeverPosZero() const
Return true if it's known this can never be a literal positive zero.
std::optional< bool > SignBit
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
bool isKnownNeverNegZero() const
Return true if it's known this can never be a negative zero.
bool isKnownNeverLogicalZero(const Function &F, Type *Ty) const
Return true if it's know this can never be interpreted as a zero.
void propagateNaN(const KnownFPClass &Src, bool PreserveSign=false)
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
void signBitMustBeOne()
Assume the sign bit is one.
void signBitMustBeZero()
Assume the sign bit is zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
bool operator==(KnownFPClass Other) const
bool signBitIsZeroOrNaN() const
Return true if the sign bit must be 0, ignoring the sign of nans.
bool isKnownNeverPosSubnormal() const
Return true if it's known this can never be a positive subnormal.
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