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