LLVM 24.0.0git
ConstantFolding.cpp
Go to the documentation of this file.
1//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
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 defines routines for folding instructions into constants.
10//
11// Also, to supplement the basic IR ConstantExpr simplifications,
12// this file defines some additional folding routines that can make use of
13// DataLayout information. These functions cannot go in IR due to library
14// dependency issues.
15//
16//===----------------------------------------------------------------------===//
17
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/APInt.h"
21#include "llvm/ADT/APSInt.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/StringRef.h"
32#include "llvm/Config/config.h"
33#include "llvm/IR/Constant.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/Function.h"
39#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/InstrTypes.h"
42#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/IntrinsicsAArch64.h"
47#include "llvm/IR/IntrinsicsAMDGPU.h"
48#include "llvm/IR/IntrinsicsARM.h"
49#include "llvm/IR/IntrinsicsNVPTX.h"
50#include "llvm/IR/IntrinsicsWebAssembly.h"
51#include "llvm/IR/IntrinsicsX86.h"
53#include "llvm/IR/Operator.h"
54#include "llvm/IR/Type.h"
55#include "llvm/IR/Value.h"
59#include <cassert>
60#include <cerrno>
61#include <cfenv>
62#include <cmath>
63#include <cstdint>
64
65using namespace llvm;
66
68 "disable-fp-call-folding",
69 cl::desc("Disable constant-folding of FP intrinsics and libcalls."),
70 cl::init(false), cl::Hidden);
71
72namespace {
73
74//===----------------------------------------------------------------------===//
75// Constant Folding internal helper functions
76//===----------------------------------------------------------------------===//
77
78static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
79 Constant *C, Type *SrcEltTy,
80 unsigned NumSrcElts,
81 const DataLayout &DL) {
82 // Now that we know that the input value is a vector of integers, just shift
83 // and insert them into our result.
84 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
85 for (unsigned i = 0; i != NumSrcElts; ++i) {
86 Constant *Element;
87 if (DL.isLittleEndian())
88 Element = C->getAggregateElement(NumSrcElts - i - 1);
89 else
90 Element = C->getAggregateElement(i);
91
92 if (isa_and_nonnull<UndefValue>(Element)) {
93 Result <<= BitShift;
94 continue;
95 }
96
97 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
98 if (!ElementCI)
99 return ConstantExpr::getBitCast(C, DestTy);
100
101 Result <<= BitShift;
102 Result |= ElementCI->getValue().zext(Result.getBitWidth());
103 }
104
105 return nullptr;
106}
107
108/// Check whether folding this bitcast into a byte vector would mix poison and
109/// non-poison bits in the same output lane. While integer types track poison on
110/// a per-value basis, byte types track it on a per-bit basis. However,
111/// `ConstantByte` cannot represent values with both poison and non-poison bits.
112///
113/// Source elements are grouped by the output lane they map to. Returns true if
114/// any group contains both poison and non-poison elements.
115static bool foldMixesPoisonBits(Constant *C, unsigned NumSrcElt,
116 unsigned NumDstElt) {
117 // If element counts don't divide evenly, bail out if a poison source element
118 // might span multiple destination lanes.
119 if (NumSrcElt % NumDstElt != 0)
120 return C->containsPoisonElement();
121 unsigned Ratio = NumSrcElt / NumDstElt;
122 for (unsigned i = 0; i != NumSrcElt; i += Ratio) {
123 bool HasPoison = false;
124 bool HasNonPoison = false;
125 for (unsigned j = 0; j != Ratio; ++j) {
126 Constant *Src = C->getAggregateElement(i + j);
127 // Conservatively bail out.
128 if (!Src)
129 return true;
130 if (isa<PoisonValue>(Src))
131 HasPoison = true;
132 else
133 HasNonPoison = true;
134 }
135 if (HasPoison && HasNonPoison)
136 return true;
137 }
138 return false;
139}
140
141/// Track which destination lanes of a bitcast are produced from poison bytes.
142/// A destination lane is marked if any source element mapped to it is poison.
143/// Returns false if an aggregate element cannot be inspected. The caller should
144/// bail out of folding.
145static bool computePoisonDstLanes(Constant *C, unsigned NumSrcElt,
146 unsigned NumDstElt,
147 SmallBitVector &PoisonDstElts) {
148 // If element counts don't divide evenly, bail out if a poison source element
149 // might span multiple destination lanes.
150 if ((NumDstElt < NumSrcElt ? NumSrcElt % NumDstElt : NumDstElt % NumSrcElt))
151 return !C->containsPoisonElement();
152 if (NumDstElt < NumSrcElt) {
153 unsigned Ratio = NumSrcElt / NumDstElt;
154 for (unsigned i = 0; i != NumDstElt; ++i) {
155 for (unsigned j = 0; j != Ratio; ++j) {
156 Constant *Src = C->getAggregateElement(i * Ratio + j);
157 if (!Src)
158 return false;
159 if (isa<PoisonValue>(Src)) {
160 PoisonDstElts[i] = true;
161 break;
162 }
163 }
164 }
165 } else {
166 unsigned Ratio = NumDstElt / NumSrcElt;
167 for (unsigned i = 0; i != NumSrcElt; ++i) {
168 Constant *Src = C->getAggregateElement(i);
169 if (!Src)
170 return false;
171 if (isa<PoisonValue>(Src))
172 PoisonDstElts.set(i * Ratio, (i + 1) * Ratio);
173 }
174 }
175 return true;
176}
177
178/// Constant fold bitcast, symbolically evaluating it with DataLayout.
179/// This always returns a non-null constant, but it may be a
180/// ConstantExpr if unfoldable.
181Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
182 assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) &&
183 "Invalid constantexpr bitcast!");
184
185 // Catch the obvious splat cases.
186 if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy, DL))
187 return Res;
188
189 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
190 // Handle a vector->scalar integer/fp cast.
191 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
192 unsigned NumSrcElts = cast<FixedVectorType>(VTy)->getNumElements();
193 Type *SrcEltTy = VTy->getElementType();
194
195 // Bitcasting a byte containing any poison bit to an integer or fp type
196 // yields poison.
197 if (SrcEltTy->isByteTy() && C->containsPoisonElement())
198 return PoisonValue::get(DestTy);
199
200 // If the vector is a vector of floating point or bytes, convert it to a
201 // vector of int to simplify things.
202 if (SrcEltTy->isFloatingPointTy() || SrcEltTy->isByteTy()) {
203 unsigned Width = SrcEltTy->getPrimitiveSizeInBits();
204 auto *SrcIVTy = FixedVectorType::get(
205 IntegerType::get(C->getContext(), Width), NumSrcElts);
206 // Ask IR to do the conversion now that #elts line up.
207 C = ConstantExpr::getBitCast(C, SrcIVTy);
208 }
209
210 APInt Result(DL.getTypeSizeInBits(DestTy), 0);
211 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
212 SrcEltTy, NumSrcElts, DL))
213 return CE;
214
215 if (isa<IntegerType>(DestTy))
216 return ConstantInt::get(DestTy, Result);
217
218 APFloat FP(DestTy->getFltSemantics(), Result);
219 return ConstantFP::get(DestTy->getContext(), FP);
220 }
221 }
222
223 // The code below only handles casts to vectors currently.
224 auto *DestVTy = dyn_cast<VectorType>(DestTy);
225 if (!DestVTy)
226 return ConstantExpr::getBitCast(C, DestTy);
227
228 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
229 // vector so the code below can handle it uniformly.
230 if (!isa<VectorType>(C->getType()) &&
232 Constant *Ops = C; // don't take the address of C!
233 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
234 }
235
236 // Some of what follows may extend to cover scalable vectors but the current
237 // implementation is fixed length specific.
238 if (!isa<FixedVectorType>(C->getType()))
239 return ConstantExpr::getBitCast(C, DestTy);
240
241 // If this is a bitcast from constant vector -> vector, fold it.
244 return ConstantExpr::getBitCast(C, DestTy);
245
246 // If the element types match, IR can fold it.
247 unsigned NumDstElt = cast<FixedVectorType>(DestVTy)->getNumElements();
248 unsigned NumSrcElt = cast<FixedVectorType>(C->getType())->getNumElements();
249 if (NumDstElt == NumSrcElt)
250 return ConstantExpr::getBitCast(C, DestTy);
251
252 Type *SrcEltTy = cast<VectorType>(C->getType())->getElementType();
253 Type *DstEltTy = DestVTy->getElementType();
254
255 // Otherwise, we're changing the number of elements in a vector, which
256 // requires endianness information to do the right thing. For example,
257 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
258 // folds to (little endian):
259 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
260 // and to (big endian):
261 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
262
263 // First thing is first. We only want to think about integer here, so if
264 // we have something in FP form, recast it as integer.
265 if (DstEltTy->isFloatingPointTy()) {
266 // Fold to an vector of integers with same size as our FP type.
267 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
268 auto *DestIVTy = FixedVectorType::get(
269 IntegerType::get(C->getContext(), FPWidth), NumDstElt);
270 // Recursively handle this integer conversion, if possible.
271 C = FoldBitCast(C, DestIVTy, DL);
272
273 // Finally, IR can handle this now that #elts line up.
274 return ConstantExpr::getBitCast(C, DestTy);
275 }
276
277 // Handle byte destination type by folding through integers.
278 if (DstEltTy->isByteTy()) {
279 // When combining elements into larger byte values, bail out if the fold
280 // mixes poison and non-poison bits in the same destination element. Byte
281 // types track poison per bit, and no constant value can represent that.
282 if (NumDstElt < NumSrcElt && foldMixesPoisonBits(C, NumSrcElt, NumDstElt))
283 return ConstantExpr::getBitCast(C, DestTy);
284
285 // Fold to a vector of integers with same size as the byte type.
286 unsigned ByteWidth = DstEltTy->getPrimitiveSizeInBits();
287 auto *DestIVTy = FixedVectorType::get(
288 IntegerType::get(C->getContext(), ByteWidth), NumDstElt);
289 C = FoldBitCast(C, DestIVTy, DL);
290 return ConstantExpr::getBitCast(C, DestTy);
291 }
292
293 // Okay, we know the destination is integer, if the input is FP, convert
294 // it to integer first.
295 if (SrcEltTy->isFloatingPointTy()) {
296 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
297 auto *SrcIVTy = FixedVectorType::get(
298 IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
299 // Ask IR to do the conversion now that #elts line up.
300 C = ConstantExpr::getBitCast(C, SrcIVTy);
301 assert((isa<ConstantVector>(C) || // FIXME: Remove ConstantVector.
303 "Constant folding cannot fail for plain fp->int bitcast!");
304 }
305
306 // Handle byte source type by folding through integers. Byte types track
307 // poison per bit, so any poison bit makes the destination lane poison.
308 // Record which destination lanes contain poison bits, before the generic
309 // fold below refines them to undef/zero, so they can be restored.
310 SmallBitVector PoisonDstElts(NumDstElt);
311 if (SrcEltTy->isByteTy()) {
312 if (!computePoisonDstLanes(C, NumSrcElt, NumDstElt, PoisonDstElts))
313 return ConstantExpr::getBitCast(C, DestTy);
314
315 unsigned ByteWidth = SrcEltTy->getPrimitiveSizeInBits();
316 auto *SrcIVTy = FixedVectorType::get(
317 IntegerType::get(C->getContext(), ByteWidth), NumSrcElt);
318 // Ask IR to do the conversion now that #elts line up.
319 C = ConstantExpr::getBitCast(C, SrcIVTy);
320 assert((isa<ConstantVector>(C) || // FIXME: Remove ConstantVector.
322 "Constant folding cannot fail for plain byte->int bitcast!");
323 }
324
325 // Now we know that the input and output vectors are both integer vectors
326 // of the same size, and that their #elements is not the same.
327 // Use data buffer for easy non-integer element ratio vectors handling,
328 // For example: <4 x i24> to <3 x i32>.
329 bool isLittleEndian = DL.isLittleEndian();
330 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
331 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
333 unsigned SrcElt = 0;
334
335 APInt Buffer(2 * std::max(SrcBitSize, DstBitSize), 0);
336 APInt UndefMask(Buffer.getBitWidth(), 0);
337 APInt PoisonMask(Buffer.getBitWidth(), 0);
338 unsigned BufferBitSize = 0;
339
340 while (Result.size() != NumDstElt) {
341 // Load SrcElts into Buffer.
342 while (BufferBitSize < DstBitSize) {
343 Constant *Element = C->getAggregateElement(SrcElt++);
344 if (!Element) // Reject constantexpr elements
345 return ConstantExpr::getBitCast(C, DestTy);
346
347 // Shift Buffer & Masks to fit next SrcElt.
348 if (!isLittleEndian) {
349 Buffer <<= SrcBitSize;
350 UndefMask <<= SrcBitSize;
351 PoisonMask <<= SrcBitSize;
352 }
353
354 APInt SrcValue;
355 unsigned BitPosition = isLittleEndian ? BufferBitSize : 0;
356 if (isa<UndefValue>(Element)) {
357 // Set masks fragments bits.
358 UndefMask.setBits(BitPosition, BitPosition + SrcBitSize);
359 if (isa<PoisonValue>(Element))
360 PoisonMask.setBits(BitPosition, BitPosition + SrcBitSize);
361 SrcValue = APInt::getZero(SrcBitSize);
362 } else {
363 auto *Src = dyn_cast<ConstantInt>(Element);
364 if (!Src)
365 return ConstantExpr::getBitCast(C, DestTy);
366 SrcValue = Src->getValue();
367 }
368
369 // Insert src element bits into Buffer on correct position.
370 Buffer.insertBits(SrcValue, BitPosition);
371 BufferBitSize += SrcBitSize;
372 }
373
374 // Create DstElts from Buffer.
375 while (BufferBitSize >= DstBitSize) {
376 unsigned ShiftAmt = isLittleEndian ? 0 : BufferBitSize - DstBitSize;
377 // Emit undef/poison, if all undef mask fragment bits are set.
378 if (UndefMask.extractBits(DstBitSize, ShiftAmt).isAllOnes()) {
379 // Push poison, if any bit in poison mask fragment is set.
380 if (!PoisonMask.extractBits(DstBitSize, ShiftAmt).isZero()) {
381 Result.push_back(PoisonValue::get(DstEltTy));
382 } else {
383 Result.push_back(UndefValue::get(DstEltTy));
384 }
385 } else {
386 // Create and push DstElt.
387 APInt Elt = Buffer.extractBits(DstBitSize, ShiftAmt);
388 Result.push_back(ConstantInt::get(DstEltTy, Elt));
389 }
390
391 // Shift unused Buffer fragment to lower bits.
392 if (isLittleEndian) {
393 Buffer.lshrInPlace(DstBitSize);
394 UndefMask.lshrInPlace(DstBitSize);
395 PoisonMask.lshrInPlace(DstBitSize);
396 }
397 BufferBitSize -= DstBitSize;
398 }
399 }
400
401 // Restore destination lanes whose source bytes contained poison bits.
402 for (unsigned I : PoisonDstElts.set_bits())
403 Result[I] = PoisonValue::get(DstEltTy);
404
405 return ConstantVector::get(Result);
406}
407
408} // end anonymous namespace
409
410/// If this constant is a constant offset from a global, return the global and
411/// the constant. Because of constantexprs, this function is recursive.
413 APInt &Offset, const DataLayout &DL,
414 DSOLocalEquivalent **DSOEquiv) {
415 if (DSOEquiv)
416 *DSOEquiv = nullptr;
417
418 // Trivial case, constant is the global.
419 if ((GV = dyn_cast<GlobalValue>(C))) {
420 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
421 Offset = APInt(BitWidth, 0);
422 return true;
423 }
424
425 if (auto *FoundDSOEquiv = dyn_cast<DSOLocalEquivalent>(C)) {
426 if (DSOEquiv)
427 *DSOEquiv = FoundDSOEquiv;
428 GV = FoundDSOEquiv->getGlobalValue();
429 unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
430 Offset = APInt(BitWidth, 0);
431 return true;
432 }
433
434 // Otherwise, if this isn't a constant expr, bail out.
435 auto *CE = dyn_cast<ConstantExpr>(C);
436 if (!CE) return false;
437
438 // Look through ptr->int and ptr->ptr casts.
439 if (CE->getOpcode() == Instruction::PtrToInt ||
440 CE->getOpcode() == Instruction::PtrToAddr)
441 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL,
442 DSOEquiv);
443
444 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
445 auto *GEP = dyn_cast<GEPOperator>(CE);
446 if (!GEP)
447 return false;
448
449 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
450 APInt TmpOffset(BitWidth, 0);
451
452 // If the base isn't a global+constant, we aren't either.
453 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL,
454 DSOEquiv))
455 return false;
456
457 // Otherwise, add any offset that our operands provide.
458 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
459 return false;
460
461 Offset = TmpOffset;
462 return true;
463}
464
466 const DataLayout &DL) {
467 do {
468 Type *SrcTy = C->getType();
469 if (SrcTy == DestTy)
470 return C;
471
472 TypeSize DestSize = DL.getTypeSizeInBits(DestTy);
473 TypeSize SrcSize = DL.getTypeSizeInBits(SrcTy);
474 if (!TypeSize::isKnownGE(SrcSize, DestSize))
475 return nullptr;
476
477 // Catch the obvious splat cases (since all-zeros can coerce non-integral
478 // pointers legally).
479 if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy, DL))
480 return Res;
481
482 // If the type sizes are the same and a cast is legal, just directly
483 // cast the constant.
484 // But be careful not to coerce non-integral pointers illegally.
485 if (SrcSize == DestSize &&
486 DL.isNonIntegralPointerType(SrcTy->getScalarType()) ==
487 DL.isNonIntegralPointerType(DestTy->getScalarType())) {
488 Instruction::CastOps Cast = Instruction::BitCast;
489 // If we are going from a pointer to int or vice versa, we spell the cast
490 // differently.
491 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
492 Cast = Instruction::IntToPtr;
493 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
494 Cast = Instruction::PtrToInt;
495
496 if (CastInst::castIsValid(Cast, C, DestTy))
497 return ConstantFoldCastOperand(Cast, C, DestTy, DL);
498 }
499
500 // If this isn't an aggregate type, there is nothing we can do to drill down
501 // and find a bitcastable constant.
502 if (!SrcTy->isAggregateType() && !SrcTy->isVectorTy())
503 return nullptr;
504
505 // We're simulating a load through a pointer that was bitcast to point to
506 // a different type, so we can try to walk down through the initial
507 // elements of an aggregate to see if some part of the aggregate is
508 // castable to implement the "load" semantic model.
509 if (SrcTy->isStructTy()) {
510 // Struct types might have leading zero-length elements like [0 x i32],
511 // which are certainly not what we are looking for, so skip them.
512 unsigned Elem = 0;
513 Constant *ElemC;
514 do {
515 ElemC = C->getAggregateElement(Elem++);
516 } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()).isZero());
517 C = ElemC;
518 } else {
519 // For non-byte-sized vector elements, the first element is not
520 // necessarily located at the vector base address.
521 if (auto *VT = dyn_cast<VectorType>(SrcTy))
522 if (!DL.typeSizeEqualsStoreSize(VT->getElementType()))
523 return nullptr;
524
525 C = C->getAggregateElement(0u);
526 }
527 } while (C);
528
529 return nullptr;
530}
531
532namespace {
533
534/// Recursive helper to read bits out of global. C is the constant being copied
535/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
536/// results into and BytesLeft is the number of bytes left in
537/// the CurPtr buffer. DL is the DataLayout. When IsByteLoad is true, do not
538/// unwrap inttoptr constant expressions. The caller would reconstruct those
539/// bits as a ConstantByte, dropping the pointer's provenance.
540bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
541 unsigned BytesLeft, const DataLayout &DL,
542 bool IsByteLoad = false) {
543 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
544 "Out of range access");
545
546 // Reading type padding, return zero.
547 if (ByteOffset >= DL.getTypeStoreSize(C->getType()))
548 return true;
549
550 // If this element is zero or undefined, we can just return since *CurPtr is
551 // zero initialized.
553 return true;
554
555 auto *CI = dyn_cast<ConstantInt>(C);
556 if (CI && CI->getType()->isIntegerTy()) {
557 if ((CI->getBitWidth() & 7) != 0)
558 return false;
559 const APInt &Val = CI->getValue();
560 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
561
562 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
563 unsigned n = ByteOffset;
564 if (!DL.isLittleEndian())
565 n = IntBytes - n - 1;
566 CurPtr[i] = Val.extractBits(8, n * 8).getZExtValue();
567 ++ByteOffset;
568 }
569 return true;
570 }
571
572 auto *CFP = dyn_cast<ConstantFP>(C);
573 if (CFP && CFP->getType()->isFloatingPointTy()) {
574 if (CFP->getType()->isDoubleTy()) {
575 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
576 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL,
577 IsByteLoad);
578 }
579 if (CFP->getType()->isFloatTy()){
580 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
581 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL,
582 IsByteLoad);
583 }
584 if (CFP->getType()->isHalfTy()){
585 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
586 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL,
587 IsByteLoad);
588 }
589 return false;
590 }
591
592 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
593 const StructLayout *SL = DL.getStructLayout(CS->getType());
594 unsigned Index = SL->getElementContainingOffset(ByteOffset);
595 uint64_t CurEltOffset = SL->getElementOffset(Index);
596 ByteOffset -= CurEltOffset;
597
598 while (true) {
599 // If the element access is to the element itself and not to tail padding,
600 // read the bytes from the element.
601 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
602
603 if (ByteOffset < EltSize &&
604 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
605 BytesLeft, DL, IsByteLoad))
606 return false;
607
608 ++Index;
609
610 // Check to see if we read from the last struct element, if so we're done.
611 if (Index == CS->getType()->getNumElements())
612 return true;
613
614 // If we read all of the bytes we needed from this element we're done.
615 uint64_t NextEltOffset = SL->getElementOffset(Index);
616
617 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
618 return true;
619
620 // Move to the next element of the struct.
621 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
622 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
623 ByteOffset = 0;
624 CurEltOffset = NextEltOffset;
625 }
626 // not reached.
627 }
628
632 uint64_t NumElts, EltSize;
633 Type *EltTy;
634 if (auto *AT = dyn_cast<ArrayType>(C->getType())) {
635 NumElts = AT->getNumElements();
636 EltTy = AT->getElementType();
637 EltSize = DL.getTypeAllocSize(EltTy);
638 } else {
639 NumElts = cast<FixedVectorType>(C->getType())->getNumElements();
640 EltTy = cast<FixedVectorType>(C->getType())->getElementType();
641 // TODO: For non-byte-sized vectors, current implementation assumes there is
642 // padding to the next byte boundary between elements.
643 if (!DL.typeSizeEqualsStoreSize(EltTy))
644 return false;
645
646 EltSize = DL.getTypeStoreSize(EltTy);
647 }
648 uint64_t Index = ByteOffset / EltSize;
649 uint64_t Offset = ByteOffset - Index * EltSize;
650
651 for (; Index != NumElts; ++Index) {
652 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
653 BytesLeft, DL, IsByteLoad))
654 return false;
655
656 uint64_t BytesWritten = EltSize - Offset;
657 assert(BytesWritten <= EltSize && "Not indexing into this element?");
658 if (BytesWritten >= BytesLeft)
659 return true;
660
661 Offset = 0;
662 BytesLeft -= BytesWritten;
663 CurPtr += BytesWritten;
664 }
665 return true;
666 }
667
668 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
669 if (CE->getOpcode() == Instruction::IntToPtr &&
670 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
671 // Folding byte loads through the integer operand would rebuild the result
672 // as a `ConstantByte`, dropping the pointer's provenance.
673 if (IsByteLoad)
674 return false;
675 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
676 BytesLeft, DL, IsByteLoad);
677 }
678 }
679
680 // Otherwise, unknown initializer type.
681 return false;
682}
683
684/// OrigLoadTy is the original type being loaded, while LoadTy is the type
685/// currently being folded (which may be integer type mapped from OrigLoadTy).
686Constant *FoldReinterpretLoadFromConst(Constant *C, Type *LoadTy,
687 Type *OrigLoadTy, int64_t Offset,
688 const DataLayout &DL) {
689 // Bail out early. Not expect to load from scalable global variable.
690 if (isa<ScalableVectorType>(LoadTy))
691 return nullptr;
692
693 auto *IntType = dyn_cast<IntegerType>(LoadTy);
694
695 // If this isn't an integer load we can't fold it directly.
696 if (!IntType) {
697 // If this is a non-integer load, we can try folding it as an int load and
698 // then bitcast the result. This can be useful for union cases. Note
699 // that address spaces don't matter here since we're not going to result in
700 // an actual new load.
701 if (!LoadTy->isFloatingPointTy() && !LoadTy->isPointerTy() &&
702 !LoadTy->isByteTy() && !LoadTy->isVectorTy())
703 return nullptr;
704
705 Type *MapTy = Type::getIntNTy(C->getContext(),
706 DL.getTypeSizeInBits(LoadTy).getFixedValue());
707 if (Constant *Res =
708 FoldReinterpretLoadFromConst(C, MapTy, OrigLoadTy, Offset, DL)) {
709 if (Res->isNullValue() && !LoadTy->isX86_AMXTy())
710 // Materializing a zero can be done trivially without a bitcast
711 return Constant::getNullValue(LoadTy);
712 Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy;
713 Res = FoldBitCast(Res, CastTy, DL);
714 if (LoadTy->isPtrOrPtrVectorTy()) {
715 // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr
716 if (Res->isNullValue() && !LoadTy->isX86_AMXTy())
717 return Constant::getNullValue(LoadTy);
718 if (DL.isNonIntegralPointerType(LoadTy->getScalarType()))
719 // Be careful not to replace a load of an addrspace value with an inttoptr here
720 return nullptr;
721 Res = ConstantExpr::getIntToPtr(Res, LoadTy);
722 }
723 return Res;
724 }
725 return nullptr;
726 }
727
728 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
729 // Allow folding of large type loads (e.g. <16 x double>).
730 if (BytesLoaded > 128 || BytesLoaded == 0)
731 return nullptr;
732
733 // For scalar integer load, use smaller limit to avoid regression during
734 // memcmp expansion. Codegen may generate inefficient string operations.
735 if (BytesLoaded > 32 && OrigLoadTy->isIntegerTy())
736 return nullptr;
737
738 // If we're not accessing anything in this constant, the result is undefined.
739 if (Offset <= -1 * static_cast<int64_t>(BytesLoaded))
740 return PoisonValue::get(IntType);
741
742 // TODO: We should be able to support scalable types.
743 TypeSize InitializerSize = DL.getTypeAllocSize(C->getType());
744 if (InitializerSize.isScalable())
745 return nullptr;
746
747 // If we're not accessing anything in this constant, the result is undefined.
748 if (Offset >= (int64_t)InitializerSize.getFixedValue())
749 return PoisonValue::get(IntType);
750
751 SmallVector<unsigned char, 64> RawBytes(BytesLoaded);
752 unsigned char *CurPtr = RawBytes.data();
753 unsigned BytesLeft = BytesLoaded;
754
755 // If we're loading off the beginning of the global, some bytes may be valid.
756 if (Offset < 0) {
757 CurPtr += -Offset;
758 BytesLeft += Offset;
759 Offset = 0;
760 }
761
762 if (!ReadDataFromGlobal(C, Offset, CurPtr, BytesLeft, DL,
763 /*IsByteLoad=*/OrigLoadTy->isByteOrByteVectorTy()))
764 return nullptr;
765
766 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
767 if (DL.isLittleEndian()) {
768 ResultVal = RawBytes[BytesLoaded - 1];
769 for (unsigned i = 1; i != BytesLoaded; ++i) {
770 ResultVal <<= 8;
771 ResultVal |= RawBytes[BytesLoaded - 1 - i];
772 }
773 } else {
774 ResultVal = RawBytes[0];
775 for (unsigned i = 1; i != BytesLoaded; ++i) {
776 ResultVal <<= 8;
777 ResultVal |= RawBytes[i];
778 }
779 }
780
781 return ConstantInt::get(IntType->getContext(), ResultVal);
782}
783
784} // anonymous namespace
785
786// If GV is a constant with an initializer read its representation starting
787// at Offset and return it as a constant array of unsigned char. Otherwise
788// return null.
790 uint64_t Offset) {
791 if (!GV->isConstant() || !GV->hasDefinitiveInitializer())
792 return nullptr;
793
794 const DataLayout &DL = GV->getDataLayout();
795 Constant *Init = const_cast<Constant *>(GV->getInitializer());
796 TypeSize InitSize = DL.getTypeAllocSize(Init->getType());
797 if (InitSize < Offset)
798 return nullptr;
799
800 uint64_t NBytes = InitSize - Offset;
801 if (NBytes > UINT16_MAX)
802 // Bail for large initializers in excess of 64K to avoid allocating
803 // too much memory.
804 // Offset is assumed to be less than or equal than InitSize (this
805 // is enforced in ReadDataFromGlobal).
806 return nullptr;
807
808 SmallVector<unsigned char, 256> RawBytes(static_cast<size_t>(NBytes));
809 unsigned char *CurPtr = RawBytes.data();
810
811 if (!ReadDataFromGlobal(Init, Offset, CurPtr, NBytes, DL))
812 return nullptr;
813
814 return ConstantDataArray::get(GV->getContext(), RawBytes);
815}
816
817/// If this Offset points exactly to the start of an aggregate element, return
818/// that element, otherwise return nullptr.
820 const DataLayout &DL) {
821 if (Offset.isZero())
822 return Base;
823
825 return nullptr;
826
827 Type *ElemTy = Base->getType();
828 SmallVector<APInt> Indices = DL.getGEPIndicesForOffset(ElemTy, Offset);
829 if (!Offset.isZero() || !Indices[0].isZero())
830 return nullptr;
831
832 Constant *C = Base;
833 for (const APInt &Index : drop_begin(Indices)) {
834 if (Index.isNegative() || Index.getActiveBits() >= 32)
835 return nullptr;
836
837 C = C->getAggregateElement(Index.getZExtValue());
838 if (!C)
839 return nullptr;
840 }
841
842 return C;
843}
844
846 const APInt &Offset,
847 const DataLayout &DL) {
848 if (Constant *AtOffset = getConstantAtOffset(C, Offset, DL))
849 if (Constant *Result = ConstantFoldLoadThroughBitcast(AtOffset, Ty, DL))
850 return Result;
851
852 // Explicitly check for out-of-bounds access, so we return poison even if the
853 // constant is a uniform value.
854 TypeSize Size = DL.getTypeAllocSize(C->getType());
855 if (!Size.isScalable() && Offset.sge(Size.getFixedValue()))
856 return PoisonValue::get(Ty);
857
858 // Try an offset-independent fold of a uniform value.
859 if (Constant *Result = ConstantFoldLoadFromUniformValue(C, Ty, DL))
860 return Result;
861
862 // Try hard to fold loads from bitcasted strange and non-type-safe things.
863 if (Offset.getSignificantBits() <= 64)
864 if (Constant *Result =
865 FoldReinterpretLoadFromConst(C, Ty, Ty, Offset.getSExtValue(), DL))
866 return Result;
867
868 return nullptr;
869}
870
875
878 const DataLayout &DL) {
879 // We can only fold loads from constant globals with a definitive initializer.
880 // Check this upfront, to skip expensive offset calculations.
882 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
883 return nullptr;
884
885 C = cast<Constant>(C->stripAndAccumulateConstantOffsets(
886 DL, Offset, /* AllowNonInbounds */ true));
887
888 if (C == GV)
889 if (Constant *Result = ConstantFoldLoadFromConst(GV->getInitializer(), Ty,
890 Offset, DL))
891 return Result;
892
893 // If this load comes from anywhere in a uniform constant global, the value
894 // is always the same, regardless of the loaded offset.
895 return ConstantFoldLoadFromUniformValue(GV->getInitializer(), Ty, DL);
896}
897
899 const DataLayout &DL) {
900 APInt Offset(DL.getIndexTypeSizeInBits(C->getType()), 0);
901 return ConstantFoldLoadFromConstPtr(C, Ty, std::move(Offset), DL);
902}
903
905 const DataLayout &DL) {
906 if (isa<PoisonValue>(C))
907 return PoisonValue::get(Ty);
908 if (isa<UndefValue>(C))
909 return UndefValue::get(Ty);
910 // If padding is needed when storing C to memory, then it isn't considered as
911 // uniform.
912 if (!DL.typeSizeEqualsStoreSize(C->getType()))
913 return nullptr;
914 if (C->isNullValue() && !Ty->isX86_AMXTy())
915 return Constant::getNullValue(Ty);
916 if (C->isAllOnesValue() &&
917 (Ty->isIntOrIntVectorTy() || Ty->isByteOrByteVectorTy() ||
918 Ty->isFPOrFPVectorTy()))
919 return Constant::getAllOnesValue(Ty);
920 return nullptr;
921}
922
923namespace {
924
925/// One of Op0/Op1 is a constant expression.
926/// Attempt to symbolically evaluate the result of a binary operator merging
927/// these together. If target data info is available, it is provided as DL,
928/// otherwise DL is null.
929Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
930 const DataLayout &DL) {
931 // SROA
932
933 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
934 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
935 // bits.
936
937 if (Opc == Instruction::And) {
938 KnownBits Known0 = computeKnownBits(Op0, DL);
939 KnownBits Known1 = computeKnownBits(Op1, DL);
940 if ((Known1.One | Known0.Zero).isAllOnes()) {
941 // All the bits of Op0 that the 'and' could be masking are already zero.
942 return Op0;
943 }
944 if ((Known0.One | Known1.Zero).isAllOnes()) {
945 // All the bits of Op1 that the 'and' could be masking are already zero.
946 return Op1;
947 }
948
949 Known0 &= Known1;
950 if (Known0.isConstant())
951 return ConstantInt::get(Op0->getType(), Known0.getConstant());
952 }
953
954 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
955 // constant. This happens frequently when iterating over a global array.
956 if (Opc == Instruction::Sub) {
957 GlobalValue *GV1, *GV2;
958 APInt Offs1, Offs2;
959
960 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
961 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
962 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
963
964 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
965 // PtrToInt may change the bitwidth so we have convert to the right size
966 // first.
967 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
968 Offs2.zextOrTrunc(OpSize));
969 }
970 }
971
972 return nullptr;
973}
974
975/// If array indices are not pointer-sized integers, explicitly cast them so
976/// that they aren't implicitly casted by the getelementptr.
977Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
978 Type *ResultTy, GEPNoWrapFlags NW,
979 std::optional<ConstantRange> InRange,
980 const DataLayout &DL, const TargetLibraryInfo *TLI) {
981 Type *IntIdxTy = DL.getIndexType(ResultTy);
982 Type *IntIdxScalarTy = IntIdxTy->getScalarType();
983
984 bool Any = false;
986 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
987 if ((i == 1 ||
989 SrcElemTy, Ops.slice(1, i - 1)))) &&
990 Ops[i]->getType()->getScalarType() != IntIdxScalarTy) {
991 Any = true;
992 Type *NewType =
993 Ops[i]->getType()->isVectorTy() ? IntIdxTy : IntIdxScalarTy;
995 CastInst::getCastOpcode(Ops[i], true, NewType, true), Ops[i], NewType,
996 DL);
997 if (!NewIdx)
998 return nullptr;
999 NewIdxs.push_back(NewIdx);
1000 } else
1001 NewIdxs.push_back(Ops[i]);
1002 }
1003
1004 if (!Any)
1005 return nullptr;
1006
1007 Constant *C = ConstantExpr::getGetElementPtr(DL, SrcElemTy, Ops[0], NewIdxs,
1008 NW, InRange);
1009 if (!C)
1010 return nullptr;
1011 return ConstantFoldConstant(C, DL, TLI);
1012}
1013
1014/// If we can symbolically evaluate the GEP constant expression, do so.
1015Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
1017 const DataLayout &DL,
1018 const TargetLibraryInfo *TLI) {
1019 Type *SrcElemTy = GEP->getSourceElementType();
1020 Type *ResTy = GEP->getType();
1021 if (!SrcElemTy->isSized() || isa<ScalableVectorType>(SrcElemTy))
1022 return nullptr;
1023
1024 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, GEP->getNoWrapFlags(),
1025 GEP->getInRange(), DL, TLI))
1026 return C;
1027
1028 Constant *Ptr = Ops[0];
1029 if (!Ptr->getType()->isPointerTy())
1030 return nullptr;
1031
1032 Type *IntIdxTy = DL.getIndexType(Ptr->getType());
1033
1034 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1035 if (!isa<ConstantInt>(Ops[i]) || !Ops[i]->getType()->isIntegerTy())
1036 return nullptr;
1037
1038 unsigned BitWidth = DL.getTypeSizeInBits(IntIdxTy);
1039 APInt Offset = APInt(
1040 BitWidth,
1041 DL.getIndexedOffsetInType(
1042 SrcElemTy, ArrayRef((Value *const *)Ops.data() + 1, Ops.size() - 1)),
1043 /*isSigned=*/true, /*implicitTrunc=*/true);
1044
1045 std::optional<ConstantRange> InRange = GEP->getInRange();
1046 if (InRange)
1047 InRange = InRange->sextOrTrunc(BitWidth);
1048
1049 // If this is a GEP of a GEP, fold it all into a single GEP.
1050 GEPNoWrapFlags NW = GEP->getNoWrapFlags();
1051 bool Overflow = false;
1052 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
1053 NW &= GEP->getNoWrapFlags();
1054
1055 SmallVector<Value *, 4> NestedOps(llvm::drop_begin(GEP->operands()));
1056
1057 // Do not try the incorporate the sub-GEP if some index is not a number.
1058 bool AllConstantInt = true;
1059 for (Value *NestedOp : NestedOps)
1060 if (!isa<ConstantInt>(NestedOp)) {
1061 AllConstantInt = false;
1062 break;
1063 }
1064 if (!AllConstantInt)
1065 break;
1066
1067 // Adjust inrange offset and intersect inrange attributes
1068 if (auto GEPRange = GEP->getInRange()) {
1069 auto AdjustedGEPRange = GEPRange->sextOrTrunc(BitWidth).subtract(Offset);
1070 InRange =
1071 InRange ? InRange->intersectWith(AdjustedGEPRange) : AdjustedGEPRange;
1072 }
1073
1074 Ptr = cast<Constant>(GEP->getOperand(0));
1075 SrcElemTy = GEP->getSourceElementType();
1076 Offset = Offset.sadd_ov(
1077 APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps),
1078 /*isSigned=*/true, /*implicitTrunc=*/true),
1079 Overflow);
1080 }
1081
1082 // Preserving nusw (without inbounds) also requires that the offset
1083 // additions did not overflow.
1084 if (NW.hasNoUnsignedSignedWrap() && !NW.isInBounds() && Overflow)
1086
1087 // If the base value for this address is a literal integer value, fold the
1088 // getelementptr to the resulting integer value casted to the pointer type.
1089 APInt BaseIntVal(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
1090 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
1091 if (CE->getOpcode() == Instruction::IntToPtr) {
1092 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
1093 BaseIntVal = Base->getValue().zextOrTrunc(BaseIntVal.getBitWidth());
1094 }
1095 }
1096
1097 if ((Ptr->isNullValue() || BaseIntVal != 0) &&
1098 !DL.mustNotIntroduceIntToPtr(Ptr->getType())) {
1099
1100 // If the index size is smaller than the pointer size, add to the low
1101 // bits only.
1102 BaseIntVal.insertBits(BaseIntVal.trunc(BitWidth) + Offset, 0);
1103 Constant *C = ConstantInt::get(Ptr->getContext(), BaseIntVal);
1104 return ConstantExpr::getIntToPtr(C, ResTy);
1105 }
1106
1107 // Try to infer inbounds for GEPs of globals.
1108 if (!NW.isInBounds() && Offset.isNonNegative()) {
1109 bool CanBeNull;
1110 uint64_t DerefBytes = Ptr->getPointerDereferenceableBytes(
1111 DL, CanBeNull, /*CanBeFreed=*/nullptr);
1112 if (DerefBytes != 0 && !CanBeNull && Offset.sle(DerefBytes))
1114 }
1115
1116 // nusw + nneg -> nuw
1117 if (NW.hasNoUnsignedSignedWrap() && Offset.isNonNegative())
1119
1120 // Otherwise canonicalize this to a single ptradd.
1121 LLVMContext &Ctx = Ptr->getContext();
1122 return ConstantExpr::getPtrAdd(Ptr, ConstantInt::get(Ctx, Offset), NW,
1123 InRange);
1124}
1125
1126/// Attempt to constant fold an instruction with the
1127/// specified opcode and operands. If successful, the constant result is
1128/// returned, if not, null is returned. Note that this function can fail when
1129/// attempting to fold instructions like loads and stores, which have no
1130/// constant expression form.
1131Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
1133 const DataLayout &DL,
1134 const TargetLibraryInfo *TLI,
1135 bool AllowNonDeterministic) {
1136 Type *DestTy = InstOrCE->getType();
1137
1138 if (Instruction::isUnaryOp(Opcode))
1139 return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL);
1140
1141 if (Instruction::isBinaryOp(Opcode)) {
1142 switch (Opcode) {
1143 default:
1144 break;
1145 case Instruction::FAdd:
1146 case Instruction::FSub:
1147 case Instruction::FMul:
1148 case Instruction::FDiv:
1149 case Instruction::FRem:
1150 // Handle floating point instructions separately to account for denormals
1151 // TODO: If a constant expression is being folded rather than an
1152 // instruction, denormals will not be flushed/treated as zero
1153 if (const auto *I = dyn_cast<Instruction>(InstOrCE)) {
1154 return ConstantFoldFPInstOperands(Opcode, Ops[0], Ops[1], DL, I,
1155 AllowNonDeterministic);
1156 }
1157 }
1158 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1159 }
1160
1161 if (Instruction::isCast(Opcode))
1162 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1163
1164 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
1165 Type *SrcElemTy = GEP->getSourceElementType();
1167 return nullptr;
1168
1169 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1170 return C;
1171
1172 return ConstantExpr::getGetElementPtr(DL, SrcElemTy, Ops[0], Ops.slice(1),
1173 GEP->getNoWrapFlags(),
1174 GEP->getInRange());
1175 }
1176
1177 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1178 return CE->getWithOperands(Ops);
1179
1180 switch (Opcode) {
1181 default: return nullptr;
1182 case Instruction::ICmp:
1183 case Instruction::FCmp: {
1184 auto *C = cast<CmpInst>(InstOrCE);
1185 return ConstantFoldCompareInstOperands(C->getPredicate(), Ops[0], Ops[1],
1186 DL, TLI, C->getFunction());
1187 }
1188 case Instruction::Freeze:
1189 return isGuaranteedNotToBeUndefOrPoison(Ops[0]) ? Ops[0] : nullptr;
1190 case Instruction::Call:
1191 if (auto *F = dyn_cast<Function>(Ops.back())) {
1192 const auto *Call = cast<CallBase>(InstOrCE);
1193 if (canConstantFoldCallTo(Call, F, TLI))
1194 return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI,
1195 AllowNonDeterministic);
1196 }
1197 return nullptr;
1198 case Instruction::Select:
1199 return ConstantFoldSelectInstruction(Ops[0], Ops[1], Ops[2]);
1200 case Instruction::ExtractElement:
1202 case Instruction::ExtractValue:
1204 Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices());
1205 case Instruction::InsertElement:
1206 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1207 case Instruction::InsertValue:
1209 Ops[0], Ops[1], cast<InsertValueInst>(InstOrCE)->getIndices());
1210 case Instruction::ShuffleVector:
1212 Ops[0], Ops[1], cast<ShuffleVectorInst>(InstOrCE)->getShuffleMask());
1213 case Instruction::Load: {
1214 const auto *LI = dyn_cast<LoadInst>(InstOrCE);
1215 if (LI->isVolatile())
1216 return nullptr;
1217 return ConstantFoldLoadFromConstPtr(Ops[0], LI->getType(), DL);
1218 }
1219 }
1220}
1221
1222} // end anonymous namespace
1223
1224//===----------------------------------------------------------------------===//
1225// Constant Folding public APIs
1226//===----------------------------------------------------------------------===//
1227
1228namespace {
1229
1230Constant *
1231ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1232 const TargetLibraryInfo *TLI,
1235 return const_cast<Constant *>(C);
1236
1238 for (const Use &OldU : C->operands()) {
1239 Constant *OldC = cast<Constant>(&OldU);
1240 Constant *NewC = OldC;
1241 // Recursively fold the ConstantExpr's operands. If we have already folded
1242 // a ConstantExpr, we don't have to process it again.
1243 if (isa<ConstantVector>(OldC) || isa<ConstantExpr>(OldC)) {
1244 auto It = FoldedOps.find(OldC);
1245 if (It == FoldedOps.end()) {
1246 NewC = ConstantFoldConstantImpl(OldC, DL, TLI, FoldedOps);
1247 FoldedOps.insert({OldC, NewC});
1248 } else {
1249 NewC = It->second;
1250 }
1251 }
1252 Ops.push_back(NewC);
1253 }
1254
1255 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1256 if (Constant *Res = ConstantFoldInstOperandsImpl(
1257 CE, CE->getOpcode(), Ops, DL, TLI, /*AllowNonDeterministic=*/true))
1258 return Res;
1259 return const_cast<Constant *>(C);
1260 }
1261
1263 return ConstantVector::get(Ops);
1264}
1265
1266} // end anonymous namespace
1267
1269 const DataLayout &DL,
1270 const TargetLibraryInfo *TLI) {
1271 // Handle PHI nodes quickly here...
1272 if (auto *PN = dyn_cast<PHINode>(I)) {
1273 Constant *CommonValue = nullptr;
1274
1276 for (Value *Incoming : PN->incoming_values()) {
1277 // If the incoming value is undef then skip it. Note that while we could
1278 // skip the value if it is equal to the phi node itself we choose not to
1279 // because that would break the rule that constant folding only applies if
1280 // all operands are constants.
1281 if (isa<UndefValue>(Incoming))
1282 continue;
1283 // If the incoming value is not a constant, then give up.
1284 auto *C = dyn_cast<Constant>(Incoming);
1285 if (!C)
1286 return nullptr;
1287 // Fold the PHI's operands.
1288 C = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1289 // If the incoming value is a different constant to
1290 // the one we saw previously, then give up.
1291 if (CommonValue && C != CommonValue)
1292 return nullptr;
1293 CommonValue = C;
1294 }
1295
1296 // If we reach here, all incoming values are the same constant or undef.
1297 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1298 }
1299
1300 // Scan the operand list, checking to see if they are all constants, if so,
1301 // hand off to ConstantFoldInstOperandsImpl.
1302 if (!all_of(I->operands(), [](const Use &U) { return isa<Constant>(U); }))
1303 return nullptr;
1304
1307 for (const Use &OpU : I->operands()) {
1308 auto *Op = cast<Constant>(&OpU);
1309 // Fold the Instruction's operands.
1310 Op = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps);
1311 Ops.push_back(Op);
1312 }
1313
1314 return ConstantFoldInstOperands(I, Ops, DL, TLI);
1315}
1316
1318 const TargetLibraryInfo *TLI) {
1320 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1321}
1322
1325 const DataLayout &DL,
1326 const TargetLibraryInfo *TLI,
1327 bool AllowNonDeterministic) {
1328 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI,
1329 AllowNonDeterministic);
1330}
1331
1333 Constant *Ops0, Constant *Ops1,
1334 const DataLayout &DL,
1335 const TargetLibraryInfo *TLI,
1336 const Function *CxtF) {
1337 CmpInst::Predicate Predicate = (CmpInst::Predicate)IntPredicate;
1338 // fold: icmp (inttoptr x), null -> icmp x, 0
1339 // fold: icmp null, (inttoptr x) -> icmp 0, x
1340 // fold: icmp (ptrtoint x), 0 -> icmp x, null
1341 // fold: icmp 0, (ptrtoint x) -> icmp null, x
1342 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1343 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1344 //
1345 // FIXME: The following comment is out of data and the DataLayout is here now.
1346 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1347 // around to know if bit truncation is happening.
1348 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1349 if (Ops1->isNullValue()) {
1350 if (CE0->getOpcode() == Instruction::IntToPtr) {
1351 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1352 // Convert the integer value to the right size to ensure we get the
1353 // proper extension or truncation.
1354 if (Constant *C = ConstantFoldIntegerCast(CE0->getOperand(0), IntPtrTy,
1355 /*IsSigned*/ false, DL)) {
1356 Constant *Null = Constant::getNullValue(C->getType());
1357 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1358 }
1359 }
1360
1361 // icmp only compares the address part of the pointer, so only do this
1362 // transform if the integer size matches the address size.
1363 if (CE0->getOpcode() == Instruction::PtrToInt ||
1364 CE0->getOpcode() == Instruction::PtrToAddr) {
1365 Type *AddrTy = DL.getAddressType(CE0->getOperand(0)->getType());
1366 if (CE0->getType() == AddrTy) {
1367 Constant *C = CE0->getOperand(0);
1368 Constant *Null = Constant::getNullValue(C->getType());
1369 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1370 }
1371 }
1372 }
1373
1374 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1375 if (CE0->getOpcode() == CE1->getOpcode()) {
1376 if (CE0->getOpcode() == Instruction::IntToPtr) {
1377 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1378
1379 // Convert the integer value to the right size to ensure we get the
1380 // proper extension or truncation.
1381 Constant *C0 = ConstantFoldIntegerCast(CE0->getOperand(0), IntPtrTy,
1382 /*IsSigned*/ false, DL);
1383 Constant *C1 = ConstantFoldIntegerCast(CE1->getOperand(0), IntPtrTy,
1384 /*IsSigned*/ false, DL);
1385 if (C0 && C1)
1386 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1387 }
1388
1389 // icmp only compares the address part of the pointer, so only do this
1390 // transform if the integer size matches the address size.
1391 if (CE0->getOpcode() == Instruction::PtrToInt ||
1392 CE0->getOpcode() == Instruction::PtrToAddr) {
1393 Type *AddrTy = DL.getAddressType(CE0->getOperand(0)->getType());
1394 if (CE0->getType() == AddrTy &&
1395 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1397 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1398 }
1399 }
1400 }
1401 }
1402
1403 // Convert pointer comparison (base+offset1) pred (base+offset2) into
1404 // offset1 pred offset2, for the case where the offset is inbounds. This
1405 // only works for equality and unsigned comparison, as inbounds permits
1406 // crossing the sign boundary. However, the offset comparison itself is
1407 // signed.
1408 if (Ops0->getType()->isPointerTy() && !ICmpInst::isSigned(Predicate)) {
1409 unsigned IndexWidth = DL.getIndexTypeSizeInBits(Ops0->getType());
1410 APInt Offset0(IndexWidth, 0);
1411 bool IsEqPred = ICmpInst::isEquality(Predicate);
1412 Value *Stripped0 = Ops0->stripAndAccumulateConstantOffsets(
1413 DL, Offset0, /*AllowNonInbounds=*/IsEqPred,
1414 /*AllowInvariantGroup=*/false, /*ExternalAnalysis=*/nullptr,
1415 /*LookThroughIntToPtr=*/IsEqPred);
1416 APInt Offset1(IndexWidth, 0);
1417 Value *Stripped1 = Ops1->stripAndAccumulateConstantOffsets(
1418 DL, Offset1, /*AllowNonInbounds=*/IsEqPred,
1419 /*AllowInvariantGroup=*/false, /*ExternalAnalysis=*/nullptr,
1420 /*LookThroughIntToPtr=*/IsEqPred);
1421 if (Stripped0 == Stripped1)
1422 return ConstantInt::getBool(
1423 Ops0->getContext(),
1424 ICmpInst::compare(Offset0, Offset1,
1425 ICmpInst::getSignedPredicate(Predicate)));
1426 }
1427 } else if (isa<ConstantExpr>(Ops1)) {
1428 // If RHS is a constant expression, but the left side isn't, swap the
1429 // operands and try again.
1430 Predicate = ICmpInst::getSwappedPredicate(Predicate);
1431 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
1432 }
1433
1434 if (CmpInst::isFPPredicate(Predicate)) {
1435 // Flush any denormal constant float input according to denormal handling
1436 // mode.
1437 Ops0 = FlushFPConstant(Ops0, CxtF, /*IsOutput=*/false);
1438 if (!Ops0)
1439 return nullptr;
1440 Ops1 = FlushFPConstant(Ops1, CxtF, /*IsOutput=*/false);
1441 if (!Ops1)
1442 return nullptr;
1443 }
1444
1445 return ConstantFoldCompareInstruction(Predicate, Ops0, Ops1);
1446}
1447
1449 const DataLayout &DL) {
1451
1452 return ConstantFoldUnaryInstruction(Opcode, Op);
1453}
1454
1456 Constant *RHS,
1457 const DataLayout &DL) {
1459 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1460 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1461 return C;
1462
1464 return ConstantExpr::get(Opcode, LHS, RHS);
1465 return ConstantFoldBinaryInstruction(Opcode, LHS, RHS);
1466}
1467
1470 switch (Mode) {
1472 return nullptr;
1473 case DenormalMode::IEEE:
1474 return ConstantFP::get(Ty, APF);
1476 return ConstantFP::get(
1477 Ty, APFloat::getZero(APF.getSemantics(), APF.isNegative()));
1479 return ConstantFP::get(Ty, APFloat::getZero(APF.getSemantics(), false));
1480 default:
1481 break;
1482 }
1483
1484 llvm_unreachable("unknown denormal mode");
1485}
1486
1487/// Return the denormal mode that can be assumed when executing a floating point
1488/// operation at \p CtxI.
1490 if (!CtxF)
1491 return DenormalMode::getDynamic();
1492 return CtxF->getDenormalMode(Ty->getScalarType()->getFltSemantics());
1493}
1494
1495static ConstantFP *
1496flushDenormalConstantFP(ConstantFP *CFP, const Function *CxtF, bool IsOutput) {
1497 const APFloat &APF = CFP->getValueAPF();
1498 if (!APF.isDenormal())
1499 return CFP;
1500
1502 return flushDenormalConstant(CFP->getType(), APF,
1503 IsOutput ? Mode.Output : Mode.Input);
1504}
1505
1507 bool IsOutput) {
1508 if (ConstantFP *CFP = dyn_cast<ConstantFP>(Operand))
1509 return flushDenormalConstantFP(CFP, CxtF, IsOutput);
1510
1512 return Operand;
1513
1514 Type *Ty = Operand->getType();
1515 VectorType *VecTy = dyn_cast<VectorType>(Ty);
1516 if (VecTy) {
1517 if (auto *Splat = dyn_cast_or_null<ConstantFP>(Operand->getSplatValue())) {
1518 ConstantFP *Folded = flushDenormalConstantFP(Splat, CxtF, IsOutput);
1519 if (!Folded)
1520 return nullptr;
1521 return ConstantVector::getSplat(VecTy->getElementCount(), Folded);
1522 }
1523
1524 Ty = VecTy->getElementType();
1525 }
1526
1527 if (isa<ConstantExpr>(Operand))
1528 return Operand;
1529
1530 if (const auto *CV = dyn_cast<ConstantVector>(Operand)) {
1532 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1533 Constant *Element = CV->getAggregateElement(i);
1534 if (isa<UndefValue>(Element)) {
1535 NewElts.push_back(Element);
1536 continue;
1537 }
1538
1539 ConstantFP *CFP = dyn_cast<ConstantFP>(Element);
1540 if (!CFP)
1541 return nullptr;
1542
1543 ConstantFP *Folded = flushDenormalConstantFP(CFP, CxtF, IsOutput);
1544 if (!Folded)
1545 return nullptr;
1546 NewElts.push_back(Folded);
1547 }
1548
1549 return ConstantVector::get(NewElts);
1550 }
1551
1552 if (const auto *CDV = dyn_cast<ConstantDataVector>(Operand)) {
1554 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I) {
1555 const APFloat &Elt = CDV->getElementAsAPFloat(I);
1556 if (!Elt.isDenormal()) {
1557 NewElts.push_back(ConstantFP::get(Ty, Elt));
1558 } else {
1559 DenormalMode Mode = getInstrDenormalMode(CxtF, Ty);
1560 ConstantFP *Folded =
1561 flushDenormalConstant(Ty, Elt, IsOutput ? Mode.Output : Mode.Input);
1562 if (!Folded)
1563 return nullptr;
1564 NewElts.push_back(Folded);
1565 }
1566 }
1567
1568 return ConstantVector::get(NewElts);
1569 }
1570
1571 return nullptr;
1572}
1573
1575 Constant *RHS, const DataLayout &DL,
1576 const Instruction *I,
1577 bool AllowNonDeterministic) {
1578 if (Instruction::isBinaryOp(Opcode)) {
1579 // Flush denormal inputs if needed.
1580 Constant *Op0 =
1581 FlushFPConstant(LHS, I->getFunction(), /* IsOutput */ false);
1582 if (!Op0)
1583 return nullptr;
1584 Constant *Op1 =
1585 FlushFPConstant(RHS, I->getFunction(), /* IsOutput */ false);
1586 if (!Op1)
1587 return nullptr;
1588
1589 // If nsz or an algebraic FMF flag is set, the result of the FP operation
1590 // may change due to future optimization. Don't constant fold them if
1591 // non-deterministic results are not allowed.
1592 if (!AllowNonDeterministic)
1594 if (FP->hasNoSignedZeros() || FP->hasAllowReassoc() ||
1595 FP->hasAllowContract() || FP->hasAllowReciprocal())
1596 return nullptr;
1597
1598 // Calculate constant result.
1599 Constant *C = ConstantFoldBinaryOpOperands(Opcode, Op0, Op1, DL);
1600 if (!C)
1601 return nullptr;
1602
1603 // Flush denormal output if needed.
1604 C = FlushFPConstant(C, I->getFunction(), /* IsOutput */ true);
1605 if (!C)
1606 return nullptr;
1607
1608 // The precise NaN value is non-deterministic.
1609 if (!AllowNonDeterministic && C->isNaN())
1610 return nullptr;
1611
1612 return C;
1613 }
1614 // If instruction lacks a parent/function and the denormal mode cannot be
1615 // determined, use the default (IEEE).
1616 return ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
1617}
1618
1620 Type *DestTy, const DataLayout &DL) {
1621 assert(Instruction::isCast(Opcode));
1622
1623 if (auto *CE = dyn_cast<ConstantExpr>(C))
1624 if (CE->isCast())
1625 if (unsigned NewOp = CastInst::isEliminableCastPair(
1626 Instruction::CastOps(CE->getOpcode()),
1627 Instruction::CastOps(Opcode), CE->getOperand(0)->getType(),
1628 C->getType(), DestTy, &DL))
1629 return ConstantFoldCastOperand(NewOp, CE->getOperand(0), DestTy, DL);
1630
1631 switch (Opcode) {
1632 default:
1633 llvm_unreachable("Missing case");
1634 case Instruction::PtrToAddr:
1635 case Instruction::PtrToInt:
1636 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1637 Constant *FoldedValue = nullptr;
1638 // If the input is an inttoptr, eliminate the pair. This requires knowing
1639 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1640 if (CE->getOpcode() == Instruction::IntToPtr) {
1641 // zext/trunc the inttoptr to pointer/address size.
1642 Type *MidTy = Opcode == Instruction::PtrToInt
1643 ? DL.getAddressType(CE->getType())
1644 : DL.getIntPtrType(CE->getType());
1645 FoldedValue = ConstantFoldIntegerCast(CE->getOperand(0), MidTy,
1646 /*IsSigned=*/false, DL);
1647 } else if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
1648 // If we have GEP, we can perform the following folds:
1649 // (ptrtoint/ptrtoaddr (gep null, x)) -> x
1650 // (ptrtoint/ptrtoaddr (gep (gep null, x), y) -> x + y, etc.
1651 unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1652 APInt BaseOffset(BitWidth, 0);
1653 auto *Base = cast<Constant>(GEP->stripAndAccumulateConstantOffsets(
1654 DL, BaseOffset, /*AllowNonInbounds=*/true));
1655 if (Base->isNullValue()) {
1656 FoldedValue = ConstantInt::get(CE->getContext(), BaseOffset);
1657 } else {
1658 // ptrtoint/ptrtoaddr (gep i8, Ptr, (sub 0, V))
1659 // -> sub (ptrtoint/ptrtoaddr Ptr), V
1660 if (GEP->getNumIndices() == 1 &&
1661 GEP->getSourceElementType()->isIntegerTy(8)) {
1662 auto *Ptr = cast<Constant>(GEP->getPointerOperand());
1663 auto *Sub = dyn_cast<ConstantExpr>(GEP->getOperand(1));
1664 Type *IntIdxTy = DL.getIndexType(Ptr->getType());
1665 if (Sub && Sub->getType() == IntIdxTy &&
1666 Sub->getOpcode() == Instruction::Sub &&
1667 Sub->getOperand(0)->isNullValue())
1668 FoldedValue = ConstantExpr::getSub(
1669 ConstantExpr::getCast(Opcode, Ptr, IntIdxTy),
1670 Sub->getOperand(1));
1671 }
1672 }
1673 }
1674 if (FoldedValue) {
1675 // Do a zext or trunc to get to the ptrtoint/ptrtoaddr dest size.
1676 return ConstantFoldIntegerCast(FoldedValue, DestTy, /*IsSigned=*/false,
1677 DL);
1678 }
1679 }
1680 break;
1681 case Instruction::IntToPtr:
1682 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1683 // the int size is >= the ptr size and the address spaces are the same.
1684 // This requires knowing the width of a pointer, so it can't be done in
1685 // ConstantExpr::getCast.
1686 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1687 if (CE->getOpcode() == Instruction::PtrToInt) {
1688 Constant *SrcPtr = CE->getOperand(0);
1689 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1690 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1691
1692 if (MidIntSize >= SrcPtrSize) {
1693 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1694 if (SrcAS == DestTy->getPointerAddressSpace())
1695 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1696 }
1697 }
1698 }
1699 break;
1700 case Instruction::Trunc:
1701 case Instruction::ZExt:
1702 case Instruction::SExt:
1703 case Instruction::FPTrunc:
1704 case Instruction::FPExt:
1705 case Instruction::UIToFP:
1706 case Instruction::SIToFP:
1707 case Instruction::FPToUI:
1708 case Instruction::FPToSI:
1709 case Instruction::AddrSpaceCast:
1710 break;
1711 case Instruction::BitCast:
1712 return FoldBitCast(C, DestTy, DL);
1713 }
1714
1716 return ConstantExpr::getCast(Opcode, C, DestTy);
1717 return ConstantFoldCastInstruction(Opcode, C, DestTy);
1718}
1719
1721 bool IsSigned, const DataLayout &DL) {
1722 Type *SrcTy = C->getType();
1723 if (SrcTy == DestTy)
1724 return C;
1725 if (SrcTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1726 return ConstantFoldCastOperand(Instruction::Trunc, C, DestTy, DL);
1727 if (IsSigned)
1728 return ConstantFoldCastOperand(Instruction::SExt, C, DestTy, DL);
1729 return ConstantFoldCastOperand(Instruction::ZExt, C, DestTy, DL);
1730}
1731
1732//===----------------------------------------------------------------------===//
1733// Constant Folding for Calls
1734//
1735
1736/// Returns true if the intrinsic can be constant folded, given \p IsStrictFP.
1737static bool canConstantFoldIntrinsic(Intrinsic::ID ID, bool IsStrictFP) {
1738 switch (ID) {
1739 // Operations that do not operate floating-point numbers and do not depend on
1740 // FP environment can be folded even in strictfp functions.
1741 case Intrinsic::bswap:
1742 case Intrinsic::ctpop:
1743 case Intrinsic::ctlz:
1744 case Intrinsic::cttz:
1745 case Intrinsic::fshl:
1746 case Intrinsic::fshr:
1747 case Intrinsic::clmul:
1748 case Intrinsic::pdep:
1749 case Intrinsic::pext:
1750 case Intrinsic::launder_invariant_group:
1751 case Intrinsic::masked_load:
1752 case Intrinsic::get_active_lane_mask:
1753 case Intrinsic::abs:
1754 case Intrinsic::smax:
1755 case Intrinsic::smin:
1756 case Intrinsic::umax:
1757 case Intrinsic::umin:
1758 case Intrinsic::scmp:
1759 case Intrinsic::ucmp:
1760 case Intrinsic::sadd_with_overflow:
1761 case Intrinsic::uadd_with_overflow:
1762 case Intrinsic::ssub_with_overflow:
1763 case Intrinsic::usub_with_overflow:
1764 case Intrinsic::smul_with_overflow:
1765 case Intrinsic::umul_with_overflow:
1766 case Intrinsic::smulh:
1767 case Intrinsic::umulh:
1768 case Intrinsic::sadd_sat:
1769 case Intrinsic::uadd_sat:
1770 case Intrinsic::ssub_sat:
1771 case Intrinsic::usub_sat:
1772 case Intrinsic::smul_fix:
1773 case Intrinsic::smul_fix_sat:
1774 case Intrinsic::bitreverse:
1775 case Intrinsic::is_constant:
1776 case Intrinsic::vector_reduce_add:
1777 case Intrinsic::vector_reduce_mul:
1778 case Intrinsic::vector_reduce_and:
1779 case Intrinsic::vector_reduce_or:
1780 case Intrinsic::vector_reduce_xor:
1781 case Intrinsic::vector_reduce_smin:
1782 case Intrinsic::vector_reduce_smax:
1783 case Intrinsic::vector_reduce_umin:
1784 case Intrinsic::vector_reduce_umax:
1785 case Intrinsic::vector_partial_reduce_add:
1786 case Intrinsic::vector_extract:
1787 case Intrinsic::vector_insert:
1788 case Intrinsic::vector_interleave2:
1789 case Intrinsic::vector_interleave3:
1790 case Intrinsic::vector_interleave4:
1791 case Intrinsic::vector_interleave5:
1792 case Intrinsic::vector_interleave6:
1793 case Intrinsic::vector_interleave7:
1794 case Intrinsic::vector_interleave8:
1795 case Intrinsic::vector_deinterleave2:
1796 case Intrinsic::vector_deinterleave3:
1797 case Intrinsic::vector_deinterleave4:
1798 case Intrinsic::vector_deinterleave5:
1799 case Intrinsic::vector_deinterleave6:
1800 case Intrinsic::vector_deinterleave7:
1801 case Intrinsic::vector_deinterleave8:
1802 // Target intrinsics
1803 case Intrinsic::amdgcn_perm:
1804 case Intrinsic::amdgcn_wave_reduce_umin:
1805 case Intrinsic::amdgcn_wave_reduce_umax:
1806 case Intrinsic::amdgcn_wave_reduce_max:
1807 case Intrinsic::amdgcn_wave_reduce_min:
1808 case Intrinsic::amdgcn_wave_reduce_and:
1809 case Intrinsic::amdgcn_wave_reduce_or:
1810 case Intrinsic::amdgcn_wave_reduce_xor:
1811 case Intrinsic::amdgcn_wave_reduce_add:
1812 case Intrinsic::amdgcn_wave_reduce_sub:
1813 case Intrinsic::amdgcn_s_wqm:
1814 case Intrinsic::amdgcn_s_quadmask:
1815 case Intrinsic::amdgcn_s_bitreplicate:
1816 case Intrinsic::arm_mve_vctp8:
1817 case Intrinsic::arm_mve_vctp16:
1818 case Intrinsic::arm_mve_vctp32:
1819 case Intrinsic::arm_mve_vctp64:
1820 case Intrinsic::aarch64_sve_convert_from_svbool:
1821 case Intrinsic::wasm_alltrue:
1822 case Intrinsic::wasm_anytrue:
1823 case Intrinsic::wasm_dot:
1824 // WebAssembly float semantics are always known
1825 case Intrinsic::wasm_trunc_signed:
1826 case Intrinsic::wasm_trunc_unsigned:
1827 return true;
1828
1829 // Floating point operations cannot be folded in strictfp functions in
1830 // general case. They can be folded if FP environment is known to compiler.
1831 case Intrinsic::minnum:
1832 case Intrinsic::maxnum:
1833 case Intrinsic::minimum:
1834 case Intrinsic::maximum:
1835 case Intrinsic::minimumnum:
1836 case Intrinsic::maximumnum:
1837 case Intrinsic::log:
1838 case Intrinsic::log2:
1839 case Intrinsic::log10:
1840 case Intrinsic::exp:
1841 case Intrinsic::exp2:
1842 case Intrinsic::exp10:
1843 case Intrinsic::sqrt:
1844 case Intrinsic::sin:
1845 case Intrinsic::cos:
1846 case Intrinsic::sincos:
1847 case Intrinsic::sinh:
1848 case Intrinsic::cosh:
1849 case Intrinsic::atan:
1850 case Intrinsic::pow:
1851 case Intrinsic::powi:
1852 case Intrinsic::ldexp:
1853 case Intrinsic::fma:
1854 case Intrinsic::fmuladd:
1855 case Intrinsic::frexp:
1856 case Intrinsic::fptoui_sat:
1857 case Intrinsic::fptosi_sat:
1858 case Intrinsic::amdgcn_cos:
1859 case Intrinsic::amdgcn_cubeid:
1860 case Intrinsic::amdgcn_cubema:
1861 case Intrinsic::amdgcn_cubesc:
1862 case Intrinsic::amdgcn_cubetc:
1863 case Intrinsic::amdgcn_fmul_legacy:
1864 case Intrinsic::amdgcn_fma_legacy:
1865 case Intrinsic::amdgcn_fract:
1866 case Intrinsic::amdgcn_sin:
1867 // The intrinsics below depend on rounding mode in MXCSR.
1868 case Intrinsic::x86_sse_cvtss2si:
1869 case Intrinsic::x86_sse_cvtss2si64:
1870 case Intrinsic::x86_sse_cvttss2si:
1871 case Intrinsic::x86_sse_cvttss2si64:
1872 case Intrinsic::x86_sse2_cvtsd2si:
1873 case Intrinsic::x86_sse2_cvtsd2si64:
1874 case Intrinsic::x86_sse2_cvttsd2si:
1875 case Intrinsic::x86_sse2_cvttsd2si64:
1876 case Intrinsic::x86_avx512_vcvtss2si32:
1877 case Intrinsic::x86_avx512_vcvtss2si64:
1878 case Intrinsic::x86_avx512_cvttss2si:
1879 case Intrinsic::x86_avx512_cvttss2si64:
1880 case Intrinsic::x86_avx512_vcvtsd2si32:
1881 case Intrinsic::x86_avx512_vcvtsd2si64:
1882 case Intrinsic::x86_avx512_cvttsd2si:
1883 case Intrinsic::x86_avx512_cvttsd2si64:
1884 case Intrinsic::x86_avx512_vcvtss2usi32:
1885 case Intrinsic::x86_avx512_vcvtss2usi64:
1886 case Intrinsic::x86_avx512_cvttss2usi:
1887 case Intrinsic::x86_avx512_cvttss2usi64:
1888 case Intrinsic::x86_avx512_vcvtsd2usi32:
1889 case Intrinsic::x86_avx512_vcvtsd2usi64:
1890 case Intrinsic::x86_avx512_cvttsd2usi:
1891 case Intrinsic::x86_avx512_cvttsd2usi64:
1892
1893 // NVVM FMax intrinsics
1894 case Intrinsic::nvvm_fmax_d:
1895 case Intrinsic::nvvm_fmax_f:
1896 case Intrinsic::nvvm_fmax_ftz_f:
1897 case Intrinsic::nvvm_fmax_ftz_nan_f:
1898 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
1899 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
1900 case Intrinsic::nvvm_fmax_nan_f:
1901 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
1902 case Intrinsic::nvvm_fmax_xorsign_abs_f:
1903
1904 // NVVM FMin intrinsics
1905 case Intrinsic::nvvm_fmin_d:
1906 case Intrinsic::nvvm_fmin_f:
1907 case Intrinsic::nvvm_fmin_ftz_f:
1908 case Intrinsic::nvvm_fmin_ftz_nan_f:
1909 case Intrinsic::nvvm_fmin_ftz_nan_xorsign_abs_f:
1910 case Intrinsic::nvvm_fmin_ftz_xorsign_abs_f:
1911 case Intrinsic::nvvm_fmin_nan_f:
1912 case Intrinsic::nvvm_fmin_nan_xorsign_abs_f:
1913 case Intrinsic::nvvm_fmin_xorsign_abs_f:
1914
1915 // NVVM float/double to int32/uint32 conversion intrinsics
1916 case Intrinsic::nvvm_f2i_rm:
1917 case Intrinsic::nvvm_f2i_rn:
1918 case Intrinsic::nvvm_f2i_rp:
1919 case Intrinsic::nvvm_f2i_rz:
1920 case Intrinsic::nvvm_f2i_rm_ftz:
1921 case Intrinsic::nvvm_f2i_rn_ftz:
1922 case Intrinsic::nvvm_f2i_rp_ftz:
1923 case Intrinsic::nvvm_f2i_rz_ftz:
1924 case Intrinsic::nvvm_f2ui_rm:
1925 case Intrinsic::nvvm_f2ui_rn:
1926 case Intrinsic::nvvm_f2ui_rp:
1927 case Intrinsic::nvvm_f2ui_rz:
1928 case Intrinsic::nvvm_f2ui_rm_ftz:
1929 case Intrinsic::nvvm_f2ui_rn_ftz:
1930 case Intrinsic::nvvm_f2ui_rp_ftz:
1931 case Intrinsic::nvvm_f2ui_rz_ftz:
1932 case Intrinsic::nvvm_d2i_rm:
1933 case Intrinsic::nvvm_d2i_rn:
1934 case Intrinsic::nvvm_d2i_rp:
1935 case Intrinsic::nvvm_d2i_rz:
1936 case Intrinsic::nvvm_d2ui_rm:
1937 case Intrinsic::nvvm_d2ui_rn:
1938 case Intrinsic::nvvm_d2ui_rp:
1939 case Intrinsic::nvvm_d2ui_rz:
1940
1941 // NVVM float/double to int64/uint64 conversion intrinsics
1942 case Intrinsic::nvvm_f2ll_rm:
1943 case Intrinsic::nvvm_f2ll_rn:
1944 case Intrinsic::nvvm_f2ll_rp:
1945 case Intrinsic::nvvm_f2ll_rz:
1946 case Intrinsic::nvvm_f2ll_rm_ftz:
1947 case Intrinsic::nvvm_f2ll_rn_ftz:
1948 case Intrinsic::nvvm_f2ll_rp_ftz:
1949 case Intrinsic::nvvm_f2ll_rz_ftz:
1950 case Intrinsic::nvvm_f2ull_rm:
1951 case Intrinsic::nvvm_f2ull_rn:
1952 case Intrinsic::nvvm_f2ull_rp:
1953 case Intrinsic::nvvm_f2ull_rz:
1954 case Intrinsic::nvvm_f2ull_rm_ftz:
1955 case Intrinsic::nvvm_f2ull_rn_ftz:
1956 case Intrinsic::nvvm_f2ull_rp_ftz:
1957 case Intrinsic::nvvm_f2ull_rz_ftz:
1958 case Intrinsic::nvvm_d2ll_rm:
1959 case Intrinsic::nvvm_d2ll_rn:
1960 case Intrinsic::nvvm_d2ll_rp:
1961 case Intrinsic::nvvm_d2ll_rz:
1962 case Intrinsic::nvvm_d2ull_rm:
1963 case Intrinsic::nvvm_d2ull_rn:
1964 case Intrinsic::nvvm_d2ull_rp:
1965 case Intrinsic::nvvm_d2ull_rz:
1966
1967 // NVVM math intrinsics:
1968 case Intrinsic::nvvm_ceil_d:
1969 case Intrinsic::nvvm_ceil_f:
1970 case Intrinsic::nvvm_ceil_ftz_f:
1971
1972 case Intrinsic::nvvm_fabs:
1973 case Intrinsic::nvvm_fabs_ftz:
1974
1975 case Intrinsic::nvvm_floor_d:
1976 case Intrinsic::nvvm_floor_f:
1977 case Intrinsic::nvvm_floor_ftz_f:
1978
1979 case Intrinsic::nvvm_rcp_rm_d:
1980 case Intrinsic::nvvm_rcp_rm_f:
1981 case Intrinsic::nvvm_rcp_rm_ftz_f:
1982 case Intrinsic::nvvm_rcp_rn_d:
1983 case Intrinsic::nvvm_rcp_rn_f:
1984 case Intrinsic::nvvm_rcp_rn_ftz_f:
1985 case Intrinsic::nvvm_rcp_rp_d:
1986 case Intrinsic::nvvm_rcp_rp_f:
1987 case Intrinsic::nvvm_rcp_rp_ftz_f:
1988 case Intrinsic::nvvm_rcp_rz_d:
1989 case Intrinsic::nvvm_rcp_rz_f:
1990 case Intrinsic::nvvm_rcp_rz_ftz_f:
1991
1992 case Intrinsic::nvvm_round_d:
1993 case Intrinsic::nvvm_round_f:
1994 case Intrinsic::nvvm_round_ftz_f:
1995
1996 case Intrinsic::nvvm_saturate_d:
1997 case Intrinsic::nvvm_saturate_f:
1998 case Intrinsic::nvvm_saturate_ftz_f:
1999
2000 case Intrinsic::nvvm_sqrt_f:
2001 case Intrinsic::nvvm_sqrt_rn_d:
2002 case Intrinsic::nvvm_sqrt_rn_f:
2003 case Intrinsic::nvvm_sqrt_rn_ftz_f:
2004 return !IsStrictFP;
2005
2006 // NVVM add intrinsics with explicit rounding modes
2007 case Intrinsic::nvvm_fadd:
2008 case Intrinsic::nvvm_fadd_ftz:
2009
2010 // NVVM div intrinsics with explicit rounding modes
2011 case Intrinsic::nvvm_div_rm_d:
2012 case Intrinsic::nvvm_div_rn_d:
2013 case Intrinsic::nvvm_div_rp_d:
2014 case Intrinsic::nvvm_div_rz_d:
2015 case Intrinsic::nvvm_div_rm_f:
2016 case Intrinsic::nvvm_div_rn_f:
2017 case Intrinsic::nvvm_div_rp_f:
2018 case Intrinsic::nvvm_div_rz_f:
2019 case Intrinsic::nvvm_div_rm_ftz_f:
2020 case Intrinsic::nvvm_div_rn_ftz_f:
2021 case Intrinsic::nvvm_div_rp_ftz_f:
2022 case Intrinsic::nvvm_div_rz_ftz_f:
2023
2024 // NVVM mul intrinsics with explicit rounding modes
2025 case Intrinsic::nvvm_mul_rm_d:
2026 case Intrinsic::nvvm_mul_rn_d:
2027 case Intrinsic::nvvm_mul_rp_d:
2028 case Intrinsic::nvvm_mul_rz_d:
2029 case Intrinsic::nvvm_mul_rm_f:
2030 case Intrinsic::nvvm_mul_rn_f:
2031 case Intrinsic::nvvm_mul_rp_f:
2032 case Intrinsic::nvvm_mul_rz_f:
2033 case Intrinsic::nvvm_mul_rm_ftz_f:
2034 case Intrinsic::nvvm_mul_rn_ftz_f:
2035 case Intrinsic::nvvm_mul_rp_ftz_f:
2036 case Intrinsic::nvvm_mul_rz_ftz_f:
2037
2038 // NVVM fma intrinsics with explicit rounding modes
2039 case Intrinsic::nvvm_fma_rm_d:
2040 case Intrinsic::nvvm_fma_rn_d:
2041 case Intrinsic::nvvm_fma_rp_d:
2042 case Intrinsic::nvvm_fma_rz_d:
2043 case Intrinsic::nvvm_fma_rm_f:
2044 case Intrinsic::nvvm_fma_rn_f:
2045 case Intrinsic::nvvm_fma_rp_f:
2046 case Intrinsic::nvvm_fma_rz_f:
2047 case Intrinsic::nvvm_fma_rm_ftz_f:
2048 case Intrinsic::nvvm_fma_rn_ftz_f:
2049 case Intrinsic::nvvm_fma_rp_ftz_f:
2050 case Intrinsic::nvvm_fma_rz_ftz_f:
2051
2052 // Sign operations are actually bitwise operations, they do not raise
2053 // exceptions even for SNANs.
2054 case Intrinsic::fabs:
2055 case Intrinsic::copysign:
2056 case Intrinsic::is_fpclass:
2057 // Non-constrained variants of rounding operations means default FP
2058 // environment, they can be folded in any case.
2059 case Intrinsic::ceil:
2060 case Intrinsic::floor:
2061 case Intrinsic::round:
2062 case Intrinsic::roundeven:
2063 case Intrinsic::trunc:
2064 case Intrinsic::nearbyint:
2065 case Intrinsic::rint:
2066 case Intrinsic::canonicalize:
2067
2068 // Constrained intrinsics can be folded if FP environment is known
2069 // to compiler.
2070 case Intrinsic::experimental_constrained_fma:
2071 case Intrinsic::experimental_constrained_fmuladd:
2072 case Intrinsic::experimental_constrained_fadd:
2073 case Intrinsic::experimental_constrained_fsub:
2074 case Intrinsic::experimental_constrained_fmul:
2075 case Intrinsic::experimental_constrained_fdiv:
2076 case Intrinsic::experimental_constrained_frem:
2077 case Intrinsic::experimental_constrained_ceil:
2078 case Intrinsic::experimental_constrained_floor:
2079 case Intrinsic::experimental_constrained_round:
2080 case Intrinsic::experimental_constrained_roundeven:
2081 case Intrinsic::experimental_constrained_trunc:
2082 case Intrinsic::experimental_constrained_nearbyint:
2083 case Intrinsic::experimental_constrained_rint:
2084 case Intrinsic::experimental_constrained_fcmp:
2085 case Intrinsic::experimental_constrained_fcmps:
2086
2087 case Intrinsic::experimental_cttz_elts:
2088 return true;
2089 default:
2090 return false;
2091 }
2092}
2093
2094/// Given a function's return type and its operands, determine if any of them of
2095/// of floating-point type.
2097 return RetTy->isFloatingPointTy() || any_of(Ops, [](Value *V) {
2098 return V->getType()->isFloatingPointTy();
2099 });
2100}
2101
2103 const TargetLibraryInfo *TLI) {
2104 if (Call->isNoBuiltin())
2105 return false;
2106 if (Call->getFunctionType() != F->getFunctionType())
2107 return false;
2108
2109 // Allow FP calls (both libcalls and intrinsics) to avoid being folded.
2110 // This can be useful for GPU targets or in cross-compilation scenarios
2111 // when the exact target FP behaviour is required, and the host compiler's
2112 // behaviour may be slightly different from the device's run-time behaviour.
2115 F->getReturnType(),
2116 ArrayRef<Value *>((Value *const *)(F->arg_begin()), F->arg_size())))
2117 return false;
2118
2119 if (F->getIntrinsicID() != Intrinsic::not_intrinsic)
2120 return canConstantFoldIntrinsic(F->getIntrinsicID(), Call->isStrictFP());
2121
2122 if (!TLI || Call->isStrictFP())
2123 return false;
2124
2125 LibFunc Func = TLI->getLibFunc(*F);
2126 if (Func == NotLibFunc)
2127 return false;
2128
2129 switch (Func) {
2130 case LibFunc_acos:
2131 case LibFunc_acosf:
2132 case LibFunc_acos_finite:
2133 case LibFunc_acosf_finite:
2134 case LibFunc_asin:
2135 case LibFunc_asinf:
2136 case LibFunc_asin_finite:
2137 case LibFunc_asinf_finite:
2138 case LibFunc_atan:
2139 case LibFunc_atanf:
2140 case LibFunc_atan2:
2141 case LibFunc_atan2f:
2142 case LibFunc_atan2_finite:
2143 case LibFunc_atan2f_finite:
2144 case LibFunc_ceil:
2145 case LibFunc_ceilf:
2146 case LibFunc_cosh:
2147 case LibFunc_coshf:
2148 case LibFunc_cosh_finite:
2149 case LibFunc_coshf_finite:
2150 case LibFunc_cos:
2151 case LibFunc_cosf:
2152 case LibFunc_erf:
2153 case LibFunc_erff:
2154 case LibFunc_exp:
2155 case LibFunc_expf:
2156 case LibFunc_exp_finite:
2157 case LibFunc_expf_finite:
2158 case LibFunc_exp2:
2159 case LibFunc_exp2f:
2160 case LibFunc_exp2_finite:
2161 case LibFunc_exp2f_finite:
2162 case LibFunc_fabs:
2163 case LibFunc_fabsf:
2164 case LibFunc_floor:
2165 case LibFunc_floorf:
2166 case LibFunc_fmod:
2167 case LibFunc_fmodf:
2168 case LibFunc_ilogb:
2169 case LibFunc_ilogbf:
2170 case LibFunc_log:
2171 case LibFunc_logf:
2172 case LibFunc_log_finite:
2173 case LibFunc_logf_finite:
2174 case LibFunc_logb:
2175 case LibFunc_logbf:
2176 case LibFunc_logl:
2177 case LibFunc_log2:
2178 case LibFunc_log2f:
2179 case LibFunc_log2_finite:
2180 case LibFunc_log2f_finite:
2181 case LibFunc_log10:
2182 case LibFunc_log10f:
2183 case LibFunc_log10_finite:
2184 case LibFunc_log10f_finite:
2185 case LibFunc_log1p:
2186 case LibFunc_log1pf:
2187 case LibFunc_nearbyint:
2188 case LibFunc_nearbyintf:
2189 case LibFunc_nextafter:
2190 case LibFunc_nextafterf:
2191 case LibFunc_nexttoward:
2192 case LibFunc_nexttowardf:
2193 case LibFunc_pow:
2194 case LibFunc_powf:
2195 case LibFunc_pow_finite:
2196 case LibFunc_powf_finite:
2197 case LibFunc_remainder:
2198 case LibFunc_remainderf:
2199 case LibFunc_rint:
2200 case LibFunc_rintf:
2201 case LibFunc_round:
2202 case LibFunc_roundf:
2203 case LibFunc_roundeven:
2204 case LibFunc_roundevenf:
2205 case LibFunc_sin:
2206 case LibFunc_sinf:
2207 case LibFunc_sinh:
2208 case LibFunc_sinhf:
2209 case LibFunc_sinh_finite:
2210 case LibFunc_sinhf_finite:
2211 case LibFunc_sqrt:
2212 case LibFunc_sqrtf:
2213 case LibFunc_tan:
2214 case LibFunc_tanf:
2215 case LibFunc_tanh:
2216 case LibFunc_tanhf:
2217 case LibFunc_trunc:
2218 case LibFunc_truncf:
2219 return true;
2220 default:
2221 return false;
2222 }
2223}
2224
2225namespace {
2226
2227Constant *GetConstantFoldFPValue(double V, Type *Ty) {
2228 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isBFloatTy()) {
2229 APFloat APF(V);
2230 bool unused;
2231 APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
2232 return ConstantFP::get(Ty->getContext(), APF);
2233 }
2234 if (Ty->isDoubleTy())
2235 return ConstantFP::get(Ty->getContext(), APFloat(V));
2236 llvm_unreachable("Can only constant fold half/float/double/bfloat");
2237}
2238
2239#if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128)
2240Constant *GetConstantFoldFPValue128(float128 V, Type *Ty) {
2241 if (Ty->isFP128Ty())
2242 return ConstantFP::get(Ty, V);
2243 llvm_unreachable("Can only constant fold fp128");
2244}
2245#endif
2246
2247/// Clear the floating-point exception state.
2248inline void llvm_fenv_clearexcept() {
2249#if defined(FE_ALL_EXCEPT)
2250 feclearexcept(FE_ALL_EXCEPT);
2251#endif
2252 errno = 0;
2253}
2254
2255/// Test if a floating-point exception was raised.
2256inline bool llvm_fenv_testexcept() {
2257 int errno_val = errno;
2258 if (errno_val == ERANGE || errno_val == EDOM)
2259 return true;
2260#if defined(FE_ALL_EXCEPT) && defined(FE_INEXACT)
2261 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
2262 return true;
2263#endif
2264 return false;
2265}
2266
2267static APFloat FTZPreserveSign(const APFloat &V) {
2268 if (V.isDenormal())
2269 return APFloat::getZero(V.getSemantics(), V.isNegative());
2270 return V;
2271}
2272
2273static APFloat FlushToPositiveZero(const APFloat &V) {
2274 if (V.isDenormal())
2275 return APFloat::getZero(V.getSemantics(), false);
2276 return V;
2277}
2278
2279static APFloat FlushWithDenormKind(const APFloat &V,
2280 DenormalMode::DenormalModeKind DenormKind) {
2283 switch (DenormKind) {
2285 return V;
2287 return FTZPreserveSign(V);
2289 return FlushToPositiveZero(V);
2290 default:
2291 llvm_unreachable("Invalid denormal mode!");
2292 }
2293}
2294
2295Constant *ConstantFoldFP(double (*NativeFP)(double), const APFloat &V, Type *Ty,
2296 DenormalMode DenormMode = DenormalMode::getIEEE()) {
2297 if (!DenormMode.isValid() ||
2298 DenormMode.Input == DenormalMode::DenormalModeKind::Dynamic ||
2299 DenormMode.Output == DenormalMode::DenormalModeKind::Dynamic)
2300 return nullptr;
2301
2302 llvm_fenv_clearexcept();
2303 auto Input = FlushWithDenormKind(V, DenormMode.Input);
2304 double Result = NativeFP(Input.convertToDouble());
2305 if (llvm_fenv_testexcept()) {
2306 llvm_fenv_clearexcept();
2307 return nullptr;
2308 }
2309
2310 Constant *Output = GetConstantFoldFPValue(Result, Ty);
2311 if (DenormMode.Output == DenormalMode::DenormalModeKind::IEEE)
2312 return Output;
2313 const auto *CFP = static_cast<ConstantFP *>(Output);
2314 const auto Res = FlushWithDenormKind(CFP->getValueAPF(), DenormMode.Output);
2315 return ConstantFP::get(Ty->getContext(), Res);
2316}
2317
2318#if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128)
2319Constant *ConstantFoldFP128(float128 (*NativeFP)(float128), const APFloat &V,
2320 Type *Ty) {
2321 llvm_fenv_clearexcept();
2322 float128 Result = NativeFP(V.convertToQuad());
2323 if (llvm_fenv_testexcept()) {
2324 llvm_fenv_clearexcept();
2325 return nullptr;
2326 }
2327
2328 return GetConstantFoldFPValue128(Result, Ty);
2329}
2330#endif
2331
2332Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
2333 const APFloat &V, const APFloat &W, Type *Ty) {
2334 llvm_fenv_clearexcept();
2335 double Result = NativeFP(V.convertToDouble(), W.convertToDouble());
2336 if (llvm_fenv_testexcept()) {
2337 llvm_fenv_clearexcept();
2338 return nullptr;
2339 }
2340
2341 return GetConstantFoldFPValue(Result, Ty);
2342}
2343
2344Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
2345 auto *OpVT = cast<VectorType>(Op->getType());
2346
2347 // This is the same as the underlying binops - poison propagates.
2348 if (Op->containsPoisonElement())
2349 return PoisonValue::get(OpVT->getElementType());
2350
2351 // Shortcut non-accumulating reductions.
2352 if (Constant *SplatVal = Op->getSplatValue()) {
2353 switch (IID) {
2354 case Intrinsic::vector_reduce_and:
2355 case Intrinsic::vector_reduce_or:
2356 case Intrinsic::vector_reduce_smin:
2357 case Intrinsic::vector_reduce_smax:
2358 case Intrinsic::vector_reduce_umin:
2359 case Intrinsic::vector_reduce_umax:
2360 return SplatVal;
2361 case Intrinsic::vector_reduce_add:
2362 if (SplatVal->isNullValue())
2363 return SplatVal;
2364 break;
2365 case Intrinsic::vector_reduce_mul:
2366 if (SplatVal->isNullValue() || SplatVal->isOneValue())
2367 return SplatVal;
2368 break;
2369 case Intrinsic::vector_reduce_xor:
2370 if (SplatVal->isNullValue())
2371 return SplatVal;
2372 if (OpVT->getElementCount().isKnownMultipleOf(2))
2373 return Constant::getNullValue(OpVT->getElementType());
2374 break;
2375 }
2376 }
2377
2379 if (!VT)
2380 return nullptr;
2381
2382 auto *EltC = dyn_cast_or_null<ConstantInt>(Op->getAggregateElement(0U));
2383 if (!EltC)
2384 return nullptr;
2385
2386 APInt Acc = EltC->getValue();
2387 for (unsigned I = 1, E = VT->getNumElements(); I != E; I++) {
2388 if (!(EltC = dyn_cast_or_null<ConstantInt>(Op->getAggregateElement(I))))
2389 return nullptr;
2390 const APInt &X = EltC->getValue();
2391 switch (IID) {
2392 case Intrinsic::vector_reduce_add:
2393 Acc = Acc + X;
2394 break;
2395 case Intrinsic::vector_reduce_mul:
2396 Acc = Acc * X;
2397 break;
2398 case Intrinsic::vector_reduce_and:
2399 Acc = Acc & X;
2400 break;
2401 case Intrinsic::vector_reduce_or:
2402 Acc = Acc | X;
2403 break;
2404 case Intrinsic::vector_reduce_xor:
2405 Acc = Acc ^ X;
2406 break;
2407 case Intrinsic::vector_reduce_smin:
2408 Acc = APIntOps::smin(Acc, X);
2409 break;
2410 case Intrinsic::vector_reduce_smax:
2411 Acc = APIntOps::smax(Acc, X);
2412 break;
2413 case Intrinsic::vector_reduce_umin:
2414 Acc = APIntOps::umin(Acc, X);
2415 break;
2416 case Intrinsic::vector_reduce_umax:
2417 Acc = APIntOps::umax(Acc, X);
2418 break;
2419 }
2420 }
2421
2422 return ConstantInt::get(Op->getContext(), Acc);
2423}
2424
2425/// Fold a vector partial reduction add using the deterministic grouping
2426/// chosen by TargetLowering::expandPartialReduceMLA. Although the
2427/// LangRef leaves the grouping unspecified, input element I is accumulated
2428/// into result lane I % NumAccElts, with each accumulator element seeding
2429/// its corresponding result lane. Returns nullptr if any element cannot be
2430/// folded.
2431static Constant *constantFoldVectorPartialReduceAdd(Constant *Acc,
2432 Constant *Input,
2433 const DataLayout &DL) {
2434 auto *AccTy = cast<FixedVectorType>(Acc->getType());
2435 // A fixed result type does not guarantee a fixed input type.
2436 auto *InputTy = dyn_cast<FixedVectorType>(Input->getType());
2437 if (!InputTy)
2438 return nullptr;
2439
2440 unsigned NumAccElts = AccTy->getNumElements();
2441 unsigned NumInputElts = InputTy->getNumElements();
2442
2443 SmallVector<Constant *> ResultElts(NumAccElts);
2444 for (unsigned I = 0; I < NumAccElts; ++I) {
2445 ResultElts[I] = Acc->getAggregateElement(I);
2446 if (!ResultElts[I])
2447 return nullptr;
2448 }
2449
2450 for (unsigned I = 0; I < NumInputElts; ++I) {
2451 Constant *InputElt = Input->getAggregateElement(I);
2452 if (!InputElt)
2453 return nullptr;
2454
2455 unsigned ResultIdx = I % NumAccElts;
2457 Instruction::Add, ResultElts[ResultIdx], InputElt, DL);
2458 if (!Folded)
2459 return nullptr;
2460
2461 ResultElts[ResultIdx] = Folded;
2462 }
2463
2464 return ConstantVector::get(ResultElts);
2465}
2466
2467/// Attempt to fold an SSE floating point to integer conversion of a constant
2468/// floating point. If roundTowardZero is false, the default IEEE rounding is
2469/// used (toward nearest, ties to even). This matches the behavior of the
2470/// non-truncating SSE instructions in the default rounding mode. The desired
2471/// integer type Ty is used to select how many bits are available for the
2472/// result. Returns null if the conversion cannot be performed, otherwise
2473/// returns the Constant value resulting from the conversion.
2474Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
2475 Type *Ty, bool IsSigned) {
2476 // All of these conversion intrinsics form an integer of at most 64bits.
2477 unsigned ResultWidth = Ty->getIntegerBitWidth();
2478 assert(ResultWidth <= 64 &&
2479 "Can only constant fold conversions to 64 and 32 bit ints");
2480
2481 uint64_t UIntVal;
2482 bool isExact = false;
2486 Val.convertToInteger(MutableArrayRef(UIntVal), ResultWidth,
2487 IsSigned, mode, &isExact);
2488 if (status != APFloat::opOK &&
2489 (!roundTowardZero || status != APFloat::opInexact))
2490 return nullptr;
2491 return ConstantInt::get(Ty, UIntVal, IsSigned);
2492}
2493
2494double getValueAsDouble(ConstantFP *Op) {
2495 Type *Ty = Op->getType();
2496
2497 if (Ty->isBFloatTy() || Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2498 return Op->getValueAPF().convertToDouble();
2499
2500 bool unused;
2501 APFloat APF = Op->getValueAPF();
2503 return APF.convertToDouble();
2504}
2505
2506static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
2507 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
2508 C = &CI->getValue();
2509 return true;
2510 }
2511 if (isa<UndefValue>(Op)) {
2512 C = nullptr;
2513 return true;
2514 }
2515 return false;
2516}
2517
2518/// Checks if the given intrinsic call, which evaluates to constant, is allowed
2519/// to be folded.
2520///
2521/// \param CI Constrained intrinsic call.
2522/// \param St Exception flags raised during constant evaluation.
2523static bool mayFoldConstrained(ConstrainedFPIntrinsic *CI,
2524 APFloat::opStatus St) {
2525 std::optional<RoundingMode> ORM = CI->getRoundingMode();
2526 std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2527
2528 // If the operation does not change exception status flags, it is safe
2529 // to fold.
2530 if (St == APFloat::opStatus::opOK)
2531 return true;
2532
2533 // If evaluation raised FP exception, the result can depend on rounding
2534 // mode. If the latter is unknown, folding is not possible.
2535 if (ORM == RoundingMode::Dynamic)
2536 return false;
2537
2538 // If FP exceptions are ignored, fold the call, even if such exception is
2539 // raised.
2540 if (EB && *EB != fp::ExceptionBehavior::ebStrict)
2541 return true;
2542
2543 // Leave the calculation for runtime so that exception flags be correctly set
2544 // in hardware.
2545 return false;
2546}
2547
2548/// Returns the rounding mode that should be used for constant evaluation.
2549static RoundingMode
2550getEvaluationRoundingMode(const ConstrainedFPIntrinsic *CI) {
2551 std::optional<RoundingMode> ORM = CI->getRoundingMode();
2552 if (!ORM || *ORM == RoundingMode::Dynamic)
2553 // Even if the rounding mode is unknown, try evaluating the operation.
2554 // If it does not raise inexact exception, rounding was not applied,
2555 // so the result is exact and does not depend on rounding mode. Whether
2556 // other FP exceptions are raised, it does not depend on rounding mode.
2558 return *ORM;
2559}
2560
2561/// Try to constant fold llvm.canonicalize for the given caller and value.
2562static Constant *constantFoldCanonicalize(const Type *Ty, const APFloat &Src,
2563 const Function *CtxF = nullptr) {
2564 // Zero, positive and negative, is always OK to fold.
2565 if (Src.isZero()) {
2566 // Get a fresh 0, since ppc_fp128 does have non-canonical zeros.
2567 return ConstantFP::get(
2568 Ty->getContext(),
2569 APFloat::getZero(Src.getSemantics(), Src.isNegative()));
2570 }
2571
2572 if (!Ty->isIEEELikeFPTy())
2573 return nullptr;
2574
2575 // Zero is always canonical and the sign must be preserved.
2576 //
2577 // Denorms and nans may have special encodings, but it should be OK to fold a
2578 // totally average number.
2579 if (Src.isNormal() || Src.isInfinity())
2580 return ConstantFP::get(Ty->getContext(), Src);
2581
2582 if (Src.isDenormal() && CtxF) {
2583 DenormalMode DenormMode = CtxF->getDenormalMode(Src.getSemantics());
2584
2585 if (DenormMode == DenormalMode::getIEEE())
2586 return ConstantFP::get(Ty->getContext(), Src);
2587
2588 if (DenormMode.Input == DenormalMode::Dynamic)
2589 return nullptr;
2590
2591 // If we know if either input or output is flushed, we can fold.
2592 if ((DenormMode.Input == DenormalMode::Dynamic &&
2593 DenormMode.Output == DenormalMode::IEEE) ||
2594 (DenormMode.Input == DenormalMode::IEEE &&
2595 DenormMode.Output == DenormalMode::Dynamic))
2596 return nullptr;
2597
2598 bool IsPositive =
2599 (!Src.isNegative() || DenormMode.Input == DenormalMode::PositiveZero ||
2600 (DenormMode.Output == DenormalMode::PositiveZero &&
2601 DenormMode.Input == DenormalMode::IEEE));
2602
2603 return ConstantFP::get(Ty->getContext(),
2604 APFloat::getZero(Src.getSemantics(), !IsPositive));
2605 }
2606
2607 return nullptr;
2608}
2609
2610static Constant *ConstantFoldScalarCall1(StringRef Name,
2611 Intrinsic::ID IntrinsicID, Type *Ty,
2613 const TargetLibraryInfo *TLI = nullptr,
2614 const CallBase *Call = nullptr) {
2615 assert(Operands.size() == 1 && "Wrong number of operands.");
2616
2617 if (IntrinsicID == Intrinsic::is_constant) {
2618 // We know we have a "Constant" argument. But we want to only
2619 // return true for manifest constants, not those that depend on
2620 // constants with unknowable values, e.g. GlobalValue or BlockAddress.
2621 if (Operands[0]->isManifestConstant())
2622 return ConstantInt::getTrue(Ty->getContext());
2623 return nullptr;
2624 }
2625
2626 if (isa<UndefValue>(Operands[0])) {
2627 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
2628 // ctpop() is between 0 and bitwidth, pick 0 for undef.
2629 // fptoui.sat and fptosi.sat can always fold to zero (for a zero input).
2630 if (IntrinsicID == Intrinsic::cos ||
2631 IntrinsicID == Intrinsic::ctpop ||
2632 IntrinsicID == Intrinsic::fptoui_sat ||
2633 IntrinsicID == Intrinsic::fptosi_sat ||
2634 IntrinsicID == Intrinsic::canonicalize)
2635 return Constant::getNullValue(Ty);
2636 if (IntrinsicID == Intrinsic::bswap ||
2637 IntrinsicID == Intrinsic::bitreverse ||
2638 IntrinsicID == Intrinsic::launder_invariant_group)
2639 return Operands[0];
2640 }
2641
2643 // launder(null) == null iff in addrspace 0
2644 if (IntrinsicID == Intrinsic::launder_invariant_group) {
2645 // If instruction is not yet put in a basic block (e.g. when cloning
2646 // a function during inlining), Call's caller may not be available.
2647 // So check Call's BB first before querying Call->getCaller.
2648 const Function *Caller =
2649 Call && Call->getParent() ? Call->getCaller() : nullptr;
2650 if (Caller &&
2652 Caller, Operands[0]->getType()->getPointerAddressSpace())) {
2653 return Operands[0];
2654 }
2655 return nullptr;
2656 }
2657 }
2658
2659 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
2660 APFloat U = Op->getValueAPF();
2661
2662 if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
2663 IntrinsicID == Intrinsic::wasm_trunc_unsigned) {
2664 bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed;
2665
2666 if (U.isNaN())
2667 return nullptr;
2668
2669 unsigned Width = Ty->getIntegerBitWidth();
2670 APSInt Int(Width, !Signed);
2671 bool IsExact = false;
2673 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2674
2676 return ConstantInt::get(Ty, Int);
2677
2678 return nullptr;
2679 }
2680
2681 if (IntrinsicID == Intrinsic::fptoui_sat ||
2682 IntrinsicID == Intrinsic::fptosi_sat) {
2683 // convertToInteger() already has the desired saturation semantics.
2684 APSInt Int(Ty->getIntegerBitWidth(),
2685 IntrinsicID == Intrinsic::fptoui_sat);
2686 bool IsExact;
2687 U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2688 return ConstantInt::get(Ty, Int);
2689 }
2690
2691 if (IntrinsicID == Intrinsic::canonicalize) {
2692 const Function *CtxF =
2693 Call && Call->getParent() ? Call->getFunction() : nullptr;
2694 return constantFoldCanonicalize(Ty, U, CtxF);
2695 }
2696
2697#if defined(HAS_IEE754_FLOAT128) && defined(HAS_LOGF128)
2698 if (Ty->isFP128Ty()) {
2699 if (IntrinsicID == Intrinsic::log) {
2700 float128 Result = logf128(Op->getValueAPF().convertToQuad());
2701 return GetConstantFoldFPValue128(Result, Ty);
2702 }
2703
2704 if (TLI && TLI->getLibFunc(Name) == LibFunc_logl &&
2705 TLI->has(LibFunc_logl))
2706 return ConstantFoldFP128(logf128, Op->getValueAPF(), Ty);
2707 }
2708#endif
2709
2710 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy() &&
2711 !Ty->isIntegerTy() && !Ty->isBFloatTy())
2712 return nullptr;
2713
2714 // Use internal versions of these intrinsics.
2715
2716 if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint ||
2717 IntrinsicID == Intrinsic::roundeven) {
2718 U.roundToIntegral(APFloat::rmNearestTiesToEven);
2719 return ConstantFP::get(Ty, U);
2720 }
2721
2722 if (IntrinsicID == Intrinsic::round) {
2723 U.roundToIntegral(APFloat::rmNearestTiesToAway);
2724 return ConstantFP::get(Ty, U);
2725 }
2726
2727 if (IntrinsicID == Intrinsic::roundeven) {
2728 U.roundToIntegral(APFloat::rmNearestTiesToEven);
2729 return ConstantFP::get(Ty, U);
2730 }
2731
2732 if (IntrinsicID == Intrinsic::ceil) {
2733 U.roundToIntegral(APFloat::rmTowardPositive);
2734 return ConstantFP::get(Ty, U);
2735 }
2736
2737 if (IntrinsicID == Intrinsic::floor) {
2738 U.roundToIntegral(APFloat::rmTowardNegative);
2739 return ConstantFP::get(Ty, U);
2740 }
2741
2742 if (IntrinsicID == Intrinsic::trunc) {
2743 U.roundToIntegral(APFloat::rmTowardZero);
2744 return ConstantFP::get(Ty, U);
2745 }
2746
2747 if (IntrinsicID == Intrinsic::fabs) {
2748 U.clearSign();
2749 return ConstantFP::get(Ty, U);
2750 }
2751
2752 if (IntrinsicID == Intrinsic::amdgcn_fract) {
2753 // The v_fract instruction behaves like the OpenCL spec, which defines
2754 // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
2755 // there to prevent fract(-small) from returning 1.0. It returns the
2756 // largest positive floating-point number less than 1.0."
2757 APFloat FloorU(U);
2758 FloorU.roundToIntegral(APFloat::rmTowardNegative);
2759 APFloat FractU(U - FloorU);
2760 APFloat AlmostOne(U.getSemantics(), 1);
2761 AlmostOne.next(/*nextDown*/ true);
2762 return ConstantFP::get(Ty, minimum(FractU, AlmostOne));
2763 }
2764
2765 // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
2766 // raise FP exceptions, unless the argument is signaling NaN.
2767
2769 std::optional<APFloat::roundingMode> RM;
2770 switch (IntrinsicID) {
2771 default:
2772 break;
2773 case Intrinsic::experimental_constrained_nearbyint:
2774 case Intrinsic::experimental_constrained_rint: {
2775 RM = CI->getRoundingMode();
2776 if (!RM || *RM == RoundingMode::Dynamic)
2777 return nullptr;
2778 break;
2779 }
2780 case Intrinsic::experimental_constrained_round:
2782 break;
2783 case Intrinsic::experimental_constrained_ceil:
2785 break;
2786 case Intrinsic::experimental_constrained_floor:
2788 break;
2789 case Intrinsic::experimental_constrained_trunc:
2791 break;
2792 }
2793 if (RM) {
2794 if (U.isFinite()) {
2795 APFloat::opStatus St = U.roundToIntegral(*RM);
2796 if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
2797 St == APFloat::opInexact) {
2798 std::optional<fp::ExceptionBehavior> EB =
2800 if (EB == fp::ebStrict)
2801 return nullptr;
2802 }
2803 } else if (U.isSignaling()) {
2804 std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2805 if (EB && *EB != fp::ebIgnore)
2806 return nullptr;
2807 U = APFloat::getQNaN(U.getSemantics());
2808 }
2809 return ConstantFP::get(Ty, U);
2810 }
2811 }
2812
2813 // NVVM float/double to signed/unsigned int32/int64 conversions:
2814 switch (IntrinsicID) {
2815 // f2i
2816 case Intrinsic::nvvm_f2i_rm:
2817 case Intrinsic::nvvm_f2i_rn:
2818 case Intrinsic::nvvm_f2i_rp:
2819 case Intrinsic::nvvm_f2i_rz:
2820 case Intrinsic::nvvm_f2i_rm_ftz:
2821 case Intrinsic::nvvm_f2i_rn_ftz:
2822 case Intrinsic::nvvm_f2i_rp_ftz:
2823 case Intrinsic::nvvm_f2i_rz_ftz:
2824 // f2ui
2825 case Intrinsic::nvvm_f2ui_rm:
2826 case Intrinsic::nvvm_f2ui_rn:
2827 case Intrinsic::nvvm_f2ui_rp:
2828 case Intrinsic::nvvm_f2ui_rz:
2829 case Intrinsic::nvvm_f2ui_rm_ftz:
2830 case Intrinsic::nvvm_f2ui_rn_ftz:
2831 case Intrinsic::nvvm_f2ui_rp_ftz:
2832 case Intrinsic::nvvm_f2ui_rz_ftz:
2833 // d2i
2834 case Intrinsic::nvvm_d2i_rm:
2835 case Intrinsic::nvvm_d2i_rn:
2836 case Intrinsic::nvvm_d2i_rp:
2837 case Intrinsic::nvvm_d2i_rz:
2838 // d2ui
2839 case Intrinsic::nvvm_d2ui_rm:
2840 case Intrinsic::nvvm_d2ui_rn:
2841 case Intrinsic::nvvm_d2ui_rp:
2842 case Intrinsic::nvvm_d2ui_rz:
2843 // f2ll
2844 case Intrinsic::nvvm_f2ll_rm:
2845 case Intrinsic::nvvm_f2ll_rn:
2846 case Intrinsic::nvvm_f2ll_rp:
2847 case Intrinsic::nvvm_f2ll_rz:
2848 case Intrinsic::nvvm_f2ll_rm_ftz:
2849 case Intrinsic::nvvm_f2ll_rn_ftz:
2850 case Intrinsic::nvvm_f2ll_rp_ftz:
2851 case Intrinsic::nvvm_f2ll_rz_ftz:
2852 // f2ull
2853 case Intrinsic::nvvm_f2ull_rm:
2854 case Intrinsic::nvvm_f2ull_rn:
2855 case Intrinsic::nvvm_f2ull_rp:
2856 case Intrinsic::nvvm_f2ull_rz:
2857 case Intrinsic::nvvm_f2ull_rm_ftz:
2858 case Intrinsic::nvvm_f2ull_rn_ftz:
2859 case Intrinsic::nvvm_f2ull_rp_ftz:
2860 case Intrinsic::nvvm_f2ull_rz_ftz:
2861 // d2ll
2862 case Intrinsic::nvvm_d2ll_rm:
2863 case Intrinsic::nvvm_d2ll_rn:
2864 case Intrinsic::nvvm_d2ll_rp:
2865 case Intrinsic::nvvm_d2ll_rz:
2866 // d2ull
2867 case Intrinsic::nvvm_d2ull_rm:
2868 case Intrinsic::nvvm_d2ull_rn:
2869 case Intrinsic::nvvm_d2ull_rp:
2870 case Intrinsic::nvvm_d2ull_rz: {
2871 // In float-to-integer conversion, NaN inputs are converted to 0.
2872 if (U.isNaN()) {
2873 // In float-to-integer conversion, NaN inputs are converted to 0
2874 // when the source and destination bitwidths are both less than 64.
2875 if (nvvm::FPToIntegerIntrinsicNaNZero(IntrinsicID))
2876 return ConstantInt::get(Ty, 0);
2877
2878 // Otherwise, the most significant bit is set.
2879 unsigned BitWidth = Ty->getIntegerBitWidth();
2880 uint64_t Val = 1ULL << (BitWidth - 1);
2881 return ConstantInt::get(Ty, APInt(BitWidth, Val, /*IsSigned=*/false));
2882 }
2883
2884 APFloat::roundingMode RMode =
2886 bool IsFTZ = nvvm::FPToIntegerIntrinsicShouldFTZ(IntrinsicID);
2887 bool IsSigned = nvvm::FPToIntegerIntrinsicResultIsSigned(IntrinsicID);
2888
2889 APSInt ResInt(Ty->getIntegerBitWidth(), !IsSigned);
2890 auto FloatToRound = IsFTZ ? FTZPreserveSign(U) : U;
2891
2892 // Return max/min value for integers if the result is +/-inf or
2893 // is too large to fit in the result's integer bitwidth.
2894 bool IsExact = false;
2895 FloatToRound.convertToInteger(ResInt, RMode, &IsExact);
2896 return ConstantInt::get(Ty, ResInt);
2897 }
2898 }
2899
2900 /// We only fold functions with finite arguments. Folding NaN and inf is
2901 /// likely to be aborted with an exception anyway, and some host libms
2902 /// have known errors raising exceptions.
2903 if (!U.isFinite())
2904 return nullptr;
2905
2906 /// Currently APFloat versions of these functions do not exist, so we use
2907 /// the host native double versions. Float versions are not called
2908 /// directly but for all these it is true (float)(f((double)arg)) ==
2909 /// f(arg). Long double not supported yet.
2910 const APFloat &APF = Op->getValueAPF();
2911
2912 switch (IntrinsicID) {
2913 default: break;
2914 case Intrinsic::log:
2915 if (U.isZero())
2916 return ConstantFP::getInfinity(Ty, true);
2917 if (U.isNegative())
2918 return ConstantFP::getNaN(Ty);
2919 if (U.isOne())
2920 return ConstantFP::getZero(Ty);
2921 return ConstantFoldFP(log, APF, Ty);
2922 case Intrinsic::log2:
2923 if (U.isZero())
2924 return ConstantFP::getInfinity(Ty, true);
2925 if (U.isNegative())
2926 return ConstantFP::getNaN(Ty);
2927 if (U.isOne())
2928 return ConstantFP::getZero(Ty);
2929 // TODO: What about hosts that lack a C99 library?
2930 return ConstantFoldFP(log2, APF, Ty);
2931 case Intrinsic::log10:
2932 if (U.isZero())
2933 return ConstantFP::getInfinity(Ty, true);
2934 if (U.isNegative())
2935 return ConstantFP::getNaN(Ty);
2936 if (U.isOne())
2937 return ConstantFP::getZero(Ty);
2938 // TODO: What about hosts that lack a C99 library?
2939 return ConstantFoldFP(log10, APF, Ty);
2940 case Intrinsic::exp:
2941 return ConstantFoldFP(exp, APF, Ty);
2942 case Intrinsic::exp2:
2943 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2944 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
2945 case Intrinsic::exp10:
2946 // Fold exp10(x) as pow(10, x), in case the host lacks a C99 library.
2947 return ConstantFoldBinaryFP(pow, APFloat(10.0), APF, Ty);
2948 case Intrinsic::sin:
2949 return ConstantFoldFP(sin, APF, Ty);
2950 case Intrinsic::cos:
2951 return ConstantFoldFP(cos, APF, Ty);
2952 case Intrinsic::sinh:
2953 return ConstantFoldFP(sinh, APF, Ty);
2954 case Intrinsic::cosh:
2955 return ConstantFoldFP(cosh, APF, Ty);
2956 case Intrinsic::atan:
2957 // Implement optional behavior from C's Annex F for +/-0.0.
2958 if (U.isZero())
2959 return ConstantFP::get(Ty, U);
2960 return ConstantFoldFP(atan, APF, Ty);
2961 case Intrinsic::sqrt:
2962 return ConstantFoldFP(sqrt, APF, Ty);
2963
2964 // NVVM Intrinsics:
2965 case Intrinsic::nvvm_ceil_ftz_f:
2966 case Intrinsic::nvvm_ceil_f:
2967 case Intrinsic::nvvm_ceil_d:
2968 return ConstantFoldFP(
2969 ceil, APF, Ty,
2971 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
2972
2973 case Intrinsic::nvvm_fabs_ftz:
2974 case Intrinsic::nvvm_fabs:
2975 return ConstantFoldFP(
2976 fabs, APF, Ty,
2978 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
2979
2980 case Intrinsic::nvvm_floor_ftz_f:
2981 case Intrinsic::nvvm_floor_f:
2982 case Intrinsic::nvvm_floor_d:
2983 return ConstantFoldFP(
2984 floor, APF, Ty,
2986 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
2987
2988 case Intrinsic::nvvm_rcp_rm_ftz_f:
2989 case Intrinsic::nvvm_rcp_rn_ftz_f:
2990 case Intrinsic::nvvm_rcp_rp_ftz_f:
2991 case Intrinsic::nvvm_rcp_rz_ftz_f:
2992 case Intrinsic::nvvm_rcp_rm_d:
2993 case Intrinsic::nvvm_rcp_rm_f:
2994 case Intrinsic::nvvm_rcp_rn_d:
2995 case Intrinsic::nvvm_rcp_rn_f:
2996 case Intrinsic::nvvm_rcp_rp_d:
2997 case Intrinsic::nvvm_rcp_rp_f:
2998 case Intrinsic::nvvm_rcp_rz_d:
2999 case Intrinsic::nvvm_rcp_rz_f: {
3000 APFloat::roundingMode RoundMode = nvvm::GetRCPRoundingMode(IntrinsicID);
3001 bool IsFTZ = nvvm::RCPShouldFTZ(IntrinsicID);
3002
3003 auto Denominator = IsFTZ ? FTZPreserveSign(APF) : APF;
3005 APFloat::opStatus Status = Res.divide(Denominator, RoundMode);
3006
3008 if (IsFTZ)
3009 Res = FTZPreserveSign(Res);
3010 return ConstantFP::get(Ty, Res);
3011 }
3012 return nullptr;
3013 }
3014
3015 case Intrinsic::nvvm_round_ftz_f:
3016 case Intrinsic::nvvm_round_f:
3017 case Intrinsic::nvvm_round_d: {
3018 // nvvm_round is lowered to PTX cvt.rni, which will round to nearest
3019 // integer, choosing even integer if source is equidistant between two
3020 // integers, so the semantics are closer to "rint" rather than "round".
3021 bool IsFTZ = nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID);
3022 auto V = IsFTZ ? FTZPreserveSign(APF) : APF;
3024 return ConstantFP::get(Ty, V);
3025 }
3026
3027 case Intrinsic::nvvm_saturate_ftz_f:
3028 case Intrinsic::nvvm_saturate_d:
3029 case Intrinsic::nvvm_saturate_f: {
3030 bool IsFTZ = nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID);
3031 auto V = IsFTZ ? FTZPreserveSign(APF) : APF;
3032 if (V.isNegative() || V.isZero() || V.isNaN())
3033 return ConstantFP::getZero(Ty);
3035 if (V > One)
3036 return ConstantFP::get(Ty, One);
3037 return ConstantFP::get(Ty, APF);
3038 }
3039
3040 case Intrinsic::nvvm_sqrt_rn_ftz_f:
3041 case Intrinsic::nvvm_sqrt_f:
3042 case Intrinsic::nvvm_sqrt_rn_d:
3043 case Intrinsic::nvvm_sqrt_rn_f:
3044 if (APF.isNegative())
3045 return nullptr;
3046 return ConstantFoldFP(
3047 sqrt, APF, Ty,
3049 nvvm::UnaryMathIntrinsicShouldFTZ(IntrinsicID)));
3050
3051 // AMDGCN Intrinsics:
3052 case Intrinsic::amdgcn_cos:
3053 case Intrinsic::amdgcn_sin: {
3054 double V = getValueAsDouble(Op);
3055 if (V < -256.0 || V > 256.0)
3056 // The gfx8 and gfx9 architectures handle arguments outside the range
3057 // [-256, 256] differently. This should be a rare case so bail out
3058 // rather than trying to handle the difference.
3059 return nullptr;
3060 bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
3061 double V4 = V * 4.0;
3062 if (V4 == floor(V4)) {
3063 // Force exact results for quarter-integer inputs.
3064 const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
3065 V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
3066 } else {
3067 if (IsCos)
3068 V = cos(V * 2.0 * numbers::pi);
3069 else
3070 V = sin(V * 2.0 * numbers::pi);
3071 }
3072 return GetConstantFoldFPValue(V, Ty);
3073 }
3074 }
3075
3076 if (!TLI)
3077 return nullptr;
3078
3079 LibFunc Func = TLI->getLibFunc(Name);
3080 if (Func == NotLibFunc)
3081 return nullptr;
3082
3083 switch (Func) {
3084 default:
3085 break;
3086 case LibFunc_acos:
3087 case LibFunc_acosf:
3088 case LibFunc_acos_finite:
3089 case LibFunc_acosf_finite:
3090 if (TLI->has(Func))
3091 return ConstantFoldFP(acos, APF, Ty);
3092 break;
3093 case LibFunc_asin:
3094 case LibFunc_asinf:
3095 case LibFunc_asin_finite:
3096 case LibFunc_asinf_finite:
3097 if (TLI->has(Func))
3098 return ConstantFoldFP(asin, APF, Ty);
3099 break;
3100 case LibFunc_atan:
3101 case LibFunc_atanf:
3102 // Implement optional behavior from C's Annex F for +/-0.0.
3103 if (U.isZero())
3104 return ConstantFP::get(Ty, U);
3105 if (TLI->has(Func))
3106 return ConstantFoldFP(atan, APF, Ty);
3107 break;
3108 case LibFunc_ceil:
3109 case LibFunc_ceilf:
3110 if (TLI->has(Func)) {
3111 U.roundToIntegral(APFloat::rmTowardPositive);
3112 return ConstantFP::get(Ty, U);
3113 }
3114 break;
3115 case LibFunc_cos:
3116 case LibFunc_cosf:
3117 if (TLI->has(Func))
3118 return ConstantFoldFP(cos, APF, Ty);
3119 break;
3120 case LibFunc_cosh:
3121 case LibFunc_coshf:
3122 case LibFunc_cosh_finite:
3123 case LibFunc_coshf_finite:
3124 if (TLI->has(Func))
3125 return ConstantFoldFP(cosh, APF, Ty);
3126 break;
3127 case LibFunc_exp:
3128 case LibFunc_expf:
3129 case LibFunc_exp_finite:
3130 case LibFunc_expf_finite:
3131 if (TLI->has(Func))
3132 return ConstantFoldFP(exp, APF, Ty);
3133 break;
3134 case LibFunc_exp2:
3135 case LibFunc_exp2f:
3136 case LibFunc_exp2_finite:
3137 case LibFunc_exp2f_finite:
3138 if (TLI->has(Func))
3139 // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
3140 return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
3141 break;
3142 case LibFunc_fabs:
3143 case LibFunc_fabsf:
3144 if (TLI->has(Func)) {
3145 U.clearSign();
3146 return ConstantFP::get(Ty, U);
3147 }
3148 break;
3149 case LibFunc_floor:
3150 case LibFunc_floorf:
3151 if (TLI->has(Func)) {
3152 U.roundToIntegral(APFloat::rmTowardNegative);
3153 return ConstantFP::get(Ty, U);
3154 }
3155 break;
3156 case LibFunc_log:
3157 case LibFunc_logf:
3158 case LibFunc_log_finite:
3159 case LibFunc_logf_finite:
3160 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
3161 return ConstantFoldFP(log, APF, Ty);
3162 break;
3163 case LibFunc_log2:
3164 case LibFunc_log2f:
3165 case LibFunc_log2_finite:
3166 case LibFunc_log2f_finite:
3167 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
3168 // TODO: What about hosts that lack a C99 library?
3169 return ConstantFoldFP(log2, APF, Ty);
3170 break;
3171 case LibFunc_log10:
3172 case LibFunc_log10f:
3173 case LibFunc_log10_finite:
3174 case LibFunc_log10f_finite:
3175 if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
3176 // TODO: What about hosts that lack a C99 library?
3177 return ConstantFoldFP(log10, APF, Ty);
3178 break;
3179 case LibFunc_ilogb:
3180 case LibFunc_ilogbf:
3181 if (!APF.isZero() && TLI->has(Func))
3182 return ConstantInt::get(Ty, ilogb(APF), true);
3183 break;
3184 case LibFunc_logb:
3185 case LibFunc_logbf:
3186 if (!APF.isZero() && TLI->has(Func))
3187 return ConstantFoldFP(logb, APF, Ty);
3188 break;
3189 case LibFunc_log1p:
3190 case LibFunc_log1pf:
3191 // Implement optional behavior from C's Annex F for +/-0.0.
3192 if (U.isZero())
3193 return ConstantFP::get(Ty, U);
3194 if (APF > APFloat::getOne(APF.getSemantics(), true) && TLI->has(Func))
3195 return ConstantFoldFP(log1p, APF, Ty);
3196 break;
3197 case LibFunc_logl:
3198 return nullptr;
3199 case LibFunc_erf:
3200 case LibFunc_erff:
3201 if (TLI->has(Func))
3202 return ConstantFoldFP(erf, APF, Ty);
3203 break;
3204 case LibFunc_nearbyint:
3205 case LibFunc_nearbyintf:
3206 case LibFunc_rint:
3207 case LibFunc_rintf:
3208 case LibFunc_roundeven:
3209 case LibFunc_roundevenf:
3210 if (TLI->has(Func)) {
3211 U.roundToIntegral(APFloat::rmNearestTiesToEven);
3212 return ConstantFP::get(Ty, U);
3213 }
3214 break;
3215 case LibFunc_round:
3216 case LibFunc_roundf:
3217 if (TLI->has(Func)) {
3218 U.roundToIntegral(APFloat::rmNearestTiesToAway);
3219 return ConstantFP::get(Ty, U);
3220 }
3221 break;
3222 case LibFunc_sin:
3223 case LibFunc_sinf:
3224 if (TLI->has(Func))
3225 return ConstantFoldFP(sin, APF, Ty);
3226 break;
3227 case LibFunc_sinh:
3228 case LibFunc_sinhf:
3229 case LibFunc_sinh_finite:
3230 case LibFunc_sinhf_finite:
3231 if (TLI->has(Func))
3232 return ConstantFoldFP(sinh, APF, Ty);
3233 break;
3234 case LibFunc_sqrt:
3235 case LibFunc_sqrtf:
3236 if (!APF.isNegative() && TLI->has(Func))
3237 return ConstantFoldFP(sqrt, APF, Ty);
3238 break;
3239 case LibFunc_tan:
3240 case LibFunc_tanf:
3241 if (TLI->has(Func))
3242 return ConstantFoldFP(tan, APF, Ty);
3243 break;
3244 case LibFunc_tanh:
3245 case LibFunc_tanhf:
3246 if (TLI->has(Func))
3247 return ConstantFoldFP(tanh, APF, Ty);
3248 break;
3249 case LibFunc_trunc:
3250 case LibFunc_truncf:
3251 if (TLI->has(Func)) {
3252 U.roundToIntegral(APFloat::rmTowardZero);
3253 return ConstantFP::get(Ty, U);
3254 }
3255 break;
3256 }
3257 return nullptr;
3258 }
3259
3260 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
3261 switch (IntrinsicID) {
3262 case Intrinsic::bswap:
3263 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
3264 case Intrinsic::ctpop:
3265 return ConstantInt::get(Ty, Op->getValue().popcount());
3266 case Intrinsic::bitreverse:
3267 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
3268 case Intrinsic::amdgcn_s_wqm: {
3269 uint64_t Val = Op->getZExtValue();
3270 Val |= (Val & 0x5555555555555555ULL) << 1 |
3271 ((Val >> 1) & 0x5555555555555555ULL);
3272 Val |= (Val & 0x3333333333333333ULL) << 2 |
3273 ((Val >> 2) & 0x3333333333333333ULL);
3274 return ConstantInt::get(Ty, Val);
3275 }
3276
3277 case Intrinsic::amdgcn_s_quadmask: {
3278 uint64_t Val = Op->getZExtValue();
3279 uint64_t QuadMask = 0;
3280 for (unsigned I = 0; I < Op->getBitWidth() / 4; ++I, Val >>= 4) {
3281 if (!(Val & 0xF))
3282 continue;
3283
3284 QuadMask |= (1ULL << I);
3285 }
3286 return ConstantInt::get(Ty, QuadMask);
3287 }
3288
3289 case Intrinsic::amdgcn_s_bitreplicate: {
3290 uint64_t Val = Op->getZExtValue();
3291 Val = (Val & 0x000000000000FFFFULL) | (Val & 0x00000000FFFF0000ULL) << 16;
3292 Val = (Val & 0x000000FF000000FFULL) | (Val & 0x0000FF000000FF00ULL) << 8;
3293 Val = (Val & 0x000F000F000F000FULL) | (Val & 0x00F000F000F000F0ULL) << 4;
3294 Val = (Val & 0x0303030303030303ULL) | (Val & 0x0C0C0C0C0C0C0C0CULL) << 2;
3295 Val = (Val & 0x1111111111111111ULL) | (Val & 0x2222222222222222ULL) << 1;
3296 Val = Val | Val << 1;
3297 return ConstantInt::get(Ty, Val);
3298 }
3299 }
3300 }
3301
3302 if (Operands[0]->getType()->isVectorTy()) {
3303 auto *Op = cast<Constant>(Operands[0]);
3304 switch (IntrinsicID) {
3305 default: break;
3306 case Intrinsic::vector_reduce_add:
3307 case Intrinsic::vector_reduce_mul:
3308 case Intrinsic::vector_reduce_and:
3309 case Intrinsic::vector_reduce_or:
3310 case Intrinsic::vector_reduce_xor:
3311 case Intrinsic::vector_reduce_smin:
3312 case Intrinsic::vector_reduce_smax:
3313 case Intrinsic::vector_reduce_umin:
3314 case Intrinsic::vector_reduce_umax:
3315 if (Constant *C = constantFoldVectorReduce(IntrinsicID, Operands[0]))
3316 return C;
3317 break;
3318 case Intrinsic::x86_sse_cvtss2si:
3319 case Intrinsic::x86_sse_cvtss2si64:
3320 case Intrinsic::x86_sse2_cvtsd2si:
3321 case Intrinsic::x86_sse2_cvtsd2si64:
3322 if (ConstantFP *FPOp =
3323 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
3324 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
3325 /*roundTowardZero=*/false, Ty,
3326 /*IsSigned*/true);
3327 break;
3328 case Intrinsic::x86_sse_cvttss2si:
3329 case Intrinsic::x86_sse_cvttss2si64:
3330 case Intrinsic::x86_sse2_cvttsd2si:
3331 case Intrinsic::x86_sse2_cvttsd2si64:
3332 if (ConstantFP *FPOp =
3333 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
3334 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
3335 /*roundTowardZero=*/true, Ty,
3336 /*IsSigned*/true);
3337 break;
3338
3339 case Intrinsic::wasm_anytrue:
3340 return Op->isNullValue() ? ConstantInt::get(Ty, 0)
3341 : ConstantInt::get(Ty, 1);
3342
3343 case Intrinsic::wasm_alltrue:
3344 // Check each element individually
3345 unsigned E = cast<FixedVectorType>(Op->getType())->getNumElements();
3346 for (unsigned I = 0; I != E; ++I) {
3347 Constant *Elt = Op->getAggregateElement(I);
3348 // Return false as soon as we find a non-true element.
3349 if (Elt && Elt->isNullValue())
3350 return ConstantInt::get(Ty, 0);
3351 // Bail as soon as we find an element we cannot prove to be true.
3352 if (!Elt || !isa<ConstantInt>(Elt))
3353 return nullptr;
3354 }
3355
3356 return ConstantInt::get(Ty, 1);
3357 }
3358 }
3359
3360 return nullptr;
3361}
3362
3363static Constant *evaluateCompare(const APFloat &Op1, const APFloat &Op2,
3367 FCmpInst::Predicate Cond = FCmp->getPredicate();
3368 if (FCmp->isSignaling()) {
3369 if (Op1.isNaN() || Op2.isNaN())
3371 } else {
3372 if (Op1.isSignaling() || Op2.isSignaling())
3374 }
3375 bool Result = FCmpInst::compare(Op1, Op2, Cond);
3376 if (mayFoldConstrained(const_cast<ConstrainedFPCmpIntrinsic *>(FCmp), St))
3377 return ConstantInt::get(Call->getType()->getScalarType(), Result);
3378 return nullptr;
3379}
3380
3381static Constant *ConstantFoldNextToward(const APFloat &Op0, const APFloat &Op1,
3382 const Type *RetTy) {
3383 assert(RetTy != nullptr);
3384 bool LosesInfo;
3385
3386 if (Op1.isSignaling())
3387 return nullptr;
3388 if (Op1.isNaN()) {
3389 APFloat Ret(Op1);
3390 Ret.convert(RetTy->getFltSemantics(), detail::rmNearestTiesToEven,
3391 &LosesInfo);
3392 return ConstantFP::get(RetTy->getContext(), Ret);
3393 }
3394
3395 // Recall that the second argument of nexttoward is always a long double,
3396 // so we may need to promote the first argument for comparisons to be valid.
3397 APFloat PromotedOp0(Op0);
3398 PromotedOp0.convert(Op1.getSemantics(), detail::rmNearestTiesToEven,
3399 &LosesInfo);
3400 assert(!LosesInfo && "Unexpected lossy promotion");
3401 const APFloat::cmpResult Result = PromotedOp0.compare(Op1);
3402
3403 // When equal, the standard says we must return the second argument.
3404 // This allows nice behavior such as nexttoward(0.0, -0.0) = -0.0 and
3405 // nexttoward(-0.0, 0.0) = 0.0
3406 if (Result == detail::cmpEqual) {
3407 APFloat Ret(Op1);
3408 Ret.convert(RetTy->getFltSemantics(), detail::rmNearestTiesToEven,
3409 &LosesInfo);
3410 return ConstantFP::get(RetTy->getContext(), Ret);
3411 }
3412
3413 APFloat Next(Op0);
3414 Next.next(/*nextDown=*/Result == APFloat::cmpGreaterThan);
3415 if (Next.isZero() || Next.isDenormal() || Next.isSignaling())
3416 return nullptr;
3417 return ConstantFP::get(RetTy->getContext(), Next);
3418}
3419
3420static Constant *ConstantFoldLibCall2(StringRef Name, Type *Ty,
3422 const TargetLibraryInfo *TLI = nullptr) {
3423 if (!TLI)
3424 return nullptr;
3425
3426 LibFunc Func = TLI->getLibFunc(Name);
3427 if (Func == NotLibFunc)
3428 return nullptr;
3429
3430 const auto *Op1 = dyn_cast<ConstantFP>(Operands[0]);
3431 if (!Op1)
3432 return nullptr;
3433
3434 const auto *Op2 = dyn_cast<ConstantFP>(Operands[1]);
3435 if (!Op2)
3436 return nullptr;
3437
3438 const APFloat &Op1V = Op1->getValueAPF();
3439 const APFloat &Op2V = Op2->getValueAPF();
3440
3441 switch (Func) {
3442 default:
3443 break;
3444 case LibFunc_pow:
3445 case LibFunc_powf:
3446 case LibFunc_pow_finite:
3447 case LibFunc_powf_finite:
3448 if (TLI->has(Func))
3449 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
3450 break;
3451 case LibFunc_fmod:
3452 case LibFunc_fmodf:
3453 if (TLI->has(Func)) {
3454 APFloat V = Op1->getValueAPF();
3455 if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
3456 return ConstantFP::get(Ty, V);
3457 }
3458 break;
3459 case LibFunc_remainder:
3460 case LibFunc_remainderf:
3461 if (TLI->has(Func)) {
3462 APFloat V = Op1->getValueAPF();
3463 if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
3464 return ConstantFP::get(Ty, V);
3465 }
3466 break;
3467 case LibFunc_atan2:
3468 case LibFunc_atan2f:
3469 // atan2(+/-0.0, +/-0.0) is known to raise an exception on some libm
3470 // (Solaris), so we do not assume a known result for that.
3471 if (Op1V.isZero() && Op2V.isZero())
3472 return nullptr;
3473 [[fallthrough]];
3474 case LibFunc_atan2_finite:
3475 case LibFunc_atan2f_finite:
3476 if (TLI->has(Func))
3477 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
3478 break;
3479 case LibFunc_nextafter:
3480 case LibFunc_nextafterf:
3481 case LibFunc_nexttoward:
3482 case LibFunc_nexttowardf:
3483 if (TLI->has(Func))
3484 return ConstantFoldNextToward(Op1V, Op2V, Ty);
3485 break;
3486 }
3487
3488 return nullptr;
3489}
3490
3491static Constant *ConstantFoldIntrinsicCall2(Intrinsic::ID IntrinsicID, Type *Ty,
3493 const CallBase *Call = nullptr) {
3494 assert(Operands.size() == 2 && "Wrong number of operands.");
3495
3496 if (Ty->isFloatingPointTy()) {
3497 // TODO: We should have undef handling for all of the FP intrinsics that
3498 // are attempted to be folded in this function.
3499 bool IsOp0Undef = isa<UndefValue>(Operands[0]);
3500 bool IsOp1Undef = isa<UndefValue>(Operands[1]);
3501 switch (IntrinsicID) {
3502 case Intrinsic::maxnum:
3503 case Intrinsic::minnum:
3504 case Intrinsic::maximum:
3505 case Intrinsic::minimum:
3506 case Intrinsic::maximumnum:
3507 case Intrinsic::minimumnum:
3508 case Intrinsic::nvvm_fmax_d:
3509 case Intrinsic::nvvm_fmin_d:
3510 // If one argument is undef, return the other argument.
3511 if (IsOp0Undef)
3512 return Operands[1];
3513 if (IsOp1Undef)
3514 return Operands[0];
3515 break;
3516
3517 case Intrinsic::nvvm_fmax_f:
3518 case Intrinsic::nvvm_fmax_ftz_f:
3519 case Intrinsic::nvvm_fmax_ftz_nan_f:
3520 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
3521 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
3522 case Intrinsic::nvvm_fmax_nan_f:
3523 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
3524 case Intrinsic::nvvm_fmax_xorsign_abs_f:
3525
3526 case Intrinsic::nvvm_fmin_f:
3527 case Intrinsic::nvvm_fmin_ftz_f:
3528 case Intrinsic::nvvm_fmin_ftz_nan_f:
3529 case Intrinsic::nvvm_fmin_ftz_nan_xorsign_abs_f:
3530 case Intrinsic::nvvm_fmin_ftz_xorsign_abs_f:
3531 case Intrinsic::nvvm_fmin_nan_f:
3532 case Intrinsic::nvvm_fmin_nan_xorsign_abs_f:
3533 case Intrinsic::nvvm_fmin_xorsign_abs_f:
3534 // If one arg is undef, the other arg can be returned only if it is
3535 // constant, as we may need to flush it to sign-preserving zero or
3536 // canonicalize the NaN.
3537 if (!IsOp0Undef && !IsOp1Undef)
3538 break;
3539 if (auto *Op = dyn_cast<ConstantFP>(Operands[IsOp0Undef ? 1 : 0])) {
3540 if (Op->isNaN()) {
3541 APInt NVCanonicalNaN(32, 0x7fffffff);
3542 return ConstantFP::get(
3543 Ty, APFloat(Ty->getFltSemantics(), NVCanonicalNaN));
3544 }
3545 if (nvvm::FMinFMaxShouldFTZ(IntrinsicID))
3546 return ConstantFP::get(Ty, FTZPreserveSign(Op->getValueAPF()));
3547 else
3548 return Op;
3549 }
3550 break;
3551 }
3552 }
3553
3554 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
3555 const APFloat &Op1V = Op1->getValueAPF();
3556
3557 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
3558 if (Op2->getType() != Op1->getType())
3559 return nullptr;
3560 const APFloat &Op2V = Op2->getValueAPF();
3561
3562 if (const auto *ConstrIntr =
3564 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
3565 APFloat Res = Op1V;
3567 switch (IntrinsicID) {
3568 default:
3569 return nullptr;
3570 case Intrinsic::experimental_constrained_fadd:
3571 St = Res.add(Op2V, RM);
3572 break;
3573 case Intrinsic::experimental_constrained_fsub:
3574 St = Res.subtract(Op2V, RM);
3575 break;
3576 case Intrinsic::experimental_constrained_fmul:
3577 St = Res.multiply(Op2V, RM);
3578 break;
3579 case Intrinsic::experimental_constrained_fdiv:
3580 St = Res.divide(Op2V, RM);
3581 break;
3582 case Intrinsic::experimental_constrained_frem:
3583 St = Res.mod(Op2V);
3584 break;
3585 case Intrinsic::experimental_constrained_fcmp:
3586 case Intrinsic::experimental_constrained_fcmps:
3587 return evaluateCompare(Op1V, Op2V, ConstrIntr);
3588 }
3589 if (mayFoldConstrained(const_cast<ConstrainedFPIntrinsic *>(ConstrIntr),
3590 St))
3591 return ConstantFP::get(Ty, Res);
3592 return nullptr;
3593 }
3594
3595 switch (IntrinsicID) {
3596 default:
3597 break;
3598 case Intrinsic::copysign:
3599 return ConstantFP::get(Ty, APFloat::copySign(Op1V, Op2V));
3600 case Intrinsic::minnum:
3601 return ConstantFP::get(Ty, minnum(Op1V, Op2V));
3602 case Intrinsic::maxnum:
3603 return ConstantFP::get(Ty, maxnum(Op1V, Op2V));
3604 case Intrinsic::minimum:
3605 return ConstantFP::get(Ty, minimum(Op1V, Op2V));
3606 case Intrinsic::maximum:
3607 return ConstantFP::get(Ty, maximum(Op1V, Op2V));
3608 case Intrinsic::minimumnum:
3609 return ConstantFP::get(Ty, minimumnum(Op1V, Op2V));
3610 case Intrinsic::maximumnum:
3611 return ConstantFP::get(Ty, maximumnum(Op1V, Op2V));
3612
3613 case Intrinsic::nvvm_fmax_d:
3614 case Intrinsic::nvvm_fmax_f:
3615 case Intrinsic::nvvm_fmax_ftz_f:
3616 case Intrinsic::nvvm_fmax_ftz_nan_f:
3617 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
3618 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
3619 case Intrinsic::nvvm_fmax_nan_f:
3620 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
3621 case Intrinsic::nvvm_fmax_xorsign_abs_f:
3622
3623 case Intrinsic::nvvm_fmin_d:
3624 case Intrinsic::nvvm_fmin_f:
3625 case Intrinsic::nvvm_fmin_ftz_f:
3626 case Intrinsic::nvvm_fmin_ftz_nan_f:
3627 case Intrinsic::nvvm_fmin_ftz_nan_xorsign_abs_f:
3628 case Intrinsic::nvvm_fmin_ftz_xorsign_abs_f:
3629 case Intrinsic::nvvm_fmin_nan_f:
3630 case Intrinsic::nvvm_fmin_nan_xorsign_abs_f:
3631 case Intrinsic::nvvm_fmin_xorsign_abs_f: {
3632
3633 bool ShouldCanonicalizeNaNs = !(IntrinsicID == Intrinsic::nvvm_fmax_d ||
3634 IntrinsicID == Intrinsic::nvvm_fmin_d);
3635 bool IsFTZ = nvvm::FMinFMaxShouldFTZ(IntrinsicID);
3636 bool IsNaNPropagating = nvvm::FMinFMaxPropagatesNaNs(IntrinsicID);
3637 bool IsXorSignAbs = nvvm::FMinFMaxIsXorSignAbs(IntrinsicID);
3638
3639 APFloat A = IsFTZ ? FTZPreserveSign(Op1V) : Op1V;
3640 APFloat B = IsFTZ ? FTZPreserveSign(Op2V) : Op2V;
3641
3642 bool XorSign = false;
3643 if (IsXorSignAbs) {
3644 XorSign = A.isNegative() ^ B.isNegative();
3645 A = abs(A);
3646 B = abs(B);
3647 }
3648
3649 bool IsFMax = false;
3650 switch (IntrinsicID) {
3651 case Intrinsic::nvvm_fmax_d:
3652 case Intrinsic::nvvm_fmax_f:
3653 case Intrinsic::nvvm_fmax_ftz_f:
3654 case Intrinsic::nvvm_fmax_ftz_nan_f:
3655 case Intrinsic::nvvm_fmax_ftz_nan_xorsign_abs_f:
3656 case Intrinsic::nvvm_fmax_ftz_xorsign_abs_f:
3657 case Intrinsic::nvvm_fmax_nan_f:
3658 case Intrinsic::nvvm_fmax_nan_xorsign_abs_f:
3659 case Intrinsic::nvvm_fmax_xorsign_abs_f:
3660 IsFMax = true;
3661 break;
3662 }
3663 APFloat Res =
3664 IsFMax ? (IsNaNPropagating ? maximum(A, B) : maximumnum(A, B))
3665 : (IsNaNPropagating ? minimum(A, B) : minimumnum(A, B));
3666
3667 if (ShouldCanonicalizeNaNs && Res.isNaN()) {
3668 APFloat NVCanonicalNaN(Res.getSemantics(), APInt(32, 0x7fffffff));
3669 return ConstantFP::get(Ty, NVCanonicalNaN);
3670 }
3671
3672 if (IsXorSignAbs && XorSign != Res.isNegative())
3673 Res.changeSign();
3674
3675 return ConstantFP::get(Ty, Res);
3676 }
3677
3678 case Intrinsic::nvvm_mul_rm_f:
3679 case Intrinsic::nvvm_mul_rn_f:
3680 case Intrinsic::nvvm_mul_rp_f:
3681 case Intrinsic::nvvm_mul_rz_f:
3682 case Intrinsic::nvvm_mul_rm_d:
3683 case Intrinsic::nvvm_mul_rn_d:
3684 case Intrinsic::nvvm_mul_rp_d:
3685 case Intrinsic::nvvm_mul_rz_d:
3686 case Intrinsic::nvvm_mul_rm_ftz_f:
3687 case Intrinsic::nvvm_mul_rn_ftz_f:
3688 case Intrinsic::nvvm_mul_rp_ftz_f:
3689 case Intrinsic::nvvm_mul_rz_ftz_f: {
3690
3691 bool IsFTZ = nvvm::FMulShouldFTZ(IntrinsicID);
3692 APFloat A = IsFTZ ? FTZPreserveSign(Op1V) : Op1V;
3693 APFloat B = IsFTZ ? FTZPreserveSign(Op2V) : Op2V;
3694
3695 APFloat::roundingMode RoundMode =
3696 nvvm::GetFMulRoundingMode(IntrinsicID);
3697
3698 APFloat Res = A;
3699 APFloat::opStatus Status = Res.multiply(B, RoundMode);
3700
3701 if (!Res.isNaN() &&
3703 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
3704 return ConstantFP::get(Ty, Res);
3705 }
3706 return nullptr;
3707 }
3708
3709 case Intrinsic::nvvm_div_rm_f:
3710 case Intrinsic::nvvm_div_rn_f:
3711 case Intrinsic::nvvm_div_rp_f:
3712 case Intrinsic::nvvm_div_rz_f:
3713 case Intrinsic::nvvm_div_rm_d:
3714 case Intrinsic::nvvm_div_rn_d:
3715 case Intrinsic::nvvm_div_rp_d:
3716 case Intrinsic::nvvm_div_rz_d:
3717 case Intrinsic::nvvm_div_rm_ftz_f:
3718 case Intrinsic::nvvm_div_rn_ftz_f:
3719 case Intrinsic::nvvm_div_rp_ftz_f:
3720 case Intrinsic::nvvm_div_rz_ftz_f: {
3721 bool IsFTZ = nvvm::FDivShouldFTZ(IntrinsicID);
3722 APFloat A = IsFTZ ? FTZPreserveSign(Op1V) : Op1V;
3723 APFloat B = IsFTZ ? FTZPreserveSign(Op2V) : Op2V;
3724 APFloat::roundingMode RoundMode =
3725 nvvm::GetFDivRoundingMode(IntrinsicID);
3726
3727 APFloat Res = A;
3728 APFloat::opStatus Status = Res.divide(B, RoundMode);
3729 if (!Res.isNaN() &&
3731 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
3732 return ConstantFP::get(Ty, Res);
3733 }
3734 return nullptr;
3735 }
3736 }
3737
3738 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
3739 return nullptr;
3740
3741 switch (IntrinsicID) {
3742 default:
3743 break;
3744 case Intrinsic::pow:
3745 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
3746 case Intrinsic::amdgcn_fmul_legacy:
3747 // The legacy behaviour is that multiplying +/- 0.0 by anything, even
3748 // NaN or infinity, gives +0.0.
3749 if (Op1V.isZero() || Op2V.isZero())
3750 return ConstantFP::getZero(Ty);
3751 return ConstantFP::get(Ty, Op1V * Op2V);
3752 }
3753
3754 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
3755 switch (IntrinsicID) {
3756 case Intrinsic::ldexp: {
3757 // APFloat::scalbn takes the exponent as `int`. Clamp wider integer
3758 // exponents into [INT_MIN, INT_MAX] so values still saturate the
3759 // result to +/-inf or +/-0.
3760 APInt Exp = Op2C->getValue();
3761 Exp = Exp.getBitWidth() < 32 ? Exp.sext(32) : Exp.truncSSat(32);
3762 return ConstantFP::get(
3763 Ty->getContext(),
3764 scalbn(Op1V, Exp.getSExtValue(), APFloat::rmNearestTiesToEven));
3765 }
3766 case Intrinsic::is_fpclass: {
3767 FPClassTest Mask = static_cast<FPClassTest>(Op2C->getZExtValue());
3768 bool Result =
3769 ((Mask & fcSNan) && Op1V.isNaN() && Op1V.isSignaling()) ||
3770 ((Mask & fcQNan) && Op1V.isNaN() && !Op1V.isSignaling()) ||
3771 ((Mask & fcNegInf) && Op1V.isNegInfinity()) ||
3772 ((Mask & fcNegNormal) && Op1V.isNormal() && Op1V.isNegative()) ||
3773 ((Mask & fcNegSubnormal) && Op1V.isDenormal() && Op1V.isNegative()) ||
3774 ((Mask & fcNegZero) && Op1V.isZero() && Op1V.isNegative()) ||
3775 ((Mask & fcPosZero) && Op1V.isZero() && !Op1V.isNegative()) ||
3776 ((Mask & fcPosSubnormal) && Op1V.isDenormal() && !Op1V.isNegative()) ||
3777 ((Mask & fcPosNormal) && Op1V.isNormal() && !Op1V.isNegative()) ||
3778 ((Mask & fcPosInf) && Op1V.isPosInfinity());
3779 return ConstantInt::get(Ty, Result);
3780 }
3781 case Intrinsic::powi: {
3782 // Square-and-multiply using the operand's own semantics, matching
3783 // the multiply sequence ExpandPowI builds in SelectionDAG.
3784 int Exp = static_cast<int>(Op2C->getSExtValue());
3785 unsigned UExp = static_cast<unsigned>(Exp);
3786 if (Exp < 0)
3787 UExp = -UExp;
3788 const fltSemantics &Semantics = Op1V.getSemantics();
3789 APFloat Res = APFloat::getOne(Semantics);
3790 APFloat CurSquare = Op1V;
3791 while (UExp) {
3792 if (UExp & 1)
3793 Res = Res * CurSquare;
3794 CurSquare = CurSquare * CurSquare;
3795 UExp >>= 1;
3796 }
3797 if (Exp < 0)
3798 Res = APFloat::getOne(Semantics) / Res;
3799 return ConstantFP::get(Ty, Res);
3800 }
3801 default:
3802 break;
3803 }
3804 }
3805 return nullptr;
3806 }
3807
3808 if (Operands[0]->getType()->isIntegerTy() &&
3809 Operands[1]->getType()->isIntegerTy()) {
3810 const APInt *C0, *C1;
3811 if (!getConstIntOrUndef(Operands[0], C0) ||
3812 !getConstIntOrUndef(Operands[1], C1))
3813 return nullptr;
3814
3815 switch (IntrinsicID) {
3816 default: break;
3817 case Intrinsic::smax:
3818 case Intrinsic::smin:
3819 case Intrinsic::umax:
3820 case Intrinsic::umin:
3821 if (!C0 || !C1)
3822 return MinMaxIntrinsic::getSaturationPoint(IntrinsicID, Ty);
3823 return ConstantInt::get(
3824 Ty, ICmpInst::compare(*C0, *C1,
3825 MinMaxIntrinsic::getPredicate(IntrinsicID))
3826 ? *C0
3827 : *C1);
3828
3829 case Intrinsic::scmp:
3830 case Intrinsic::ucmp:
3831 if (!C0 || !C1)
3832 return ConstantInt::get(Ty, 0);
3833
3834 int Res;
3835 if (IntrinsicID == Intrinsic::scmp)
3836 Res = C0->sgt(*C1) ? 1 : C0->slt(*C1) ? -1 : 0;
3837 else
3838 Res = C0->ugt(*C1) ? 1 : C0->ult(*C1) ? -1 : 0;
3839 return ConstantInt::get(Ty, Res, /*IsSigned=*/true);
3840
3841 case Intrinsic::usub_with_overflow:
3842 case Intrinsic::ssub_with_overflow:
3843 // X - undef -> { 0, false }
3844 // undef - X -> { 0, false }
3845 if (!C0 || !C1)
3846 return Constant::getNullValue(Ty);
3847 [[fallthrough]];
3848 case Intrinsic::uadd_with_overflow:
3849 case Intrinsic::sadd_with_overflow:
3850 // X + undef -> { -1, false }
3851 // undef + x -> { -1, false }
3852 if (!C0 || !C1) {
3853 return ConstantStruct::get(
3854 cast<StructType>(Ty),
3855 {Constant::getAllOnesValue(Ty->getStructElementType(0)),
3856 Constant::getNullValue(Ty->getStructElementType(1))});
3857 }
3858 [[fallthrough]];
3859 case Intrinsic::smul_with_overflow:
3860 case Intrinsic::umul_with_overflow: {
3861 // undef * X -> { 0, false }
3862 // X * undef -> { 0, false }
3863 if (!C0 || !C1)
3864 return Constant::getNullValue(Ty);
3865
3866 APInt Res;
3867 bool Overflow;
3868 switch (IntrinsicID) {
3869 default: llvm_unreachable("Invalid case");
3870 case Intrinsic::sadd_with_overflow:
3871 Res = C0->sadd_ov(*C1, Overflow);
3872 break;
3873 case Intrinsic::uadd_with_overflow:
3874 Res = C0->uadd_ov(*C1, Overflow);
3875 break;
3876 case Intrinsic::ssub_with_overflow:
3877 Res = C0->ssub_ov(*C1, Overflow);
3878 break;
3879 case Intrinsic::usub_with_overflow:
3880 Res = C0->usub_ov(*C1, Overflow);
3881 break;
3882 case Intrinsic::smul_with_overflow:
3883 Res = C0->smul_ov(*C1, Overflow);
3884 break;
3885 case Intrinsic::umul_with_overflow:
3886 Res = C0->umul_ov(*C1, Overflow);
3887 break;
3888 }
3889 Constant *Ops[] = {
3890 ConstantInt::get(Ty->getContext(), Res),
3891 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
3892 };
3894 }
3895 case Intrinsic::uadd_sat:
3896 case Intrinsic::sadd_sat:
3897 if (!C0 || !C1)
3898 return Constant::getAllOnesValue(Ty);
3899 if (IntrinsicID == Intrinsic::uadd_sat)
3900 return ConstantInt::get(Ty, C0->uadd_sat(*C1));
3901 else
3902 return ConstantInt::get(Ty, C0->sadd_sat(*C1));
3903 case Intrinsic::usub_sat:
3904 case Intrinsic::ssub_sat:
3905 if (!C0 || !C1)
3906 return Constant::getNullValue(Ty);
3907 if (IntrinsicID == Intrinsic::usub_sat)
3908 return ConstantInt::get(Ty, C0->usub_sat(*C1));
3909 else
3910 return ConstantInt::get(Ty, C0->ssub_sat(*C1));
3911 case Intrinsic::cttz:
3912 case Intrinsic::ctlz:
3913 assert(C1 && "Must be constant int");
3914
3915 // cttz(0, 1) and ctlz(0, 1) are poison.
3916 if (C1->isOne() && (!C0 || C0->isZero()))
3917 return PoisonValue::get(Ty);
3918 if (!C0)
3919 return Constant::getNullValue(Ty);
3920 if (IntrinsicID == Intrinsic::cttz)
3921 return ConstantInt::get(Ty, C0->countr_zero());
3922 else
3923 return ConstantInt::get(Ty, C0->countl_zero());
3924
3925 case Intrinsic::abs:
3926 assert(C1 && "Must be constant int");
3927 assert((C1->isOne() || C1->isZero()) && "Must be 0 or 1");
3928
3929 // Undef or minimum val operand with poison min --> poison
3930 if (C1->isOne() && (!C0 || C0->isMinSignedValue()))
3931 return PoisonValue::get(Ty);
3932
3933 // Undef operand with no poison min --> 0 (sign bit must be clear)
3934 if (!C0)
3935 return Constant::getNullValue(Ty);
3936
3937 return ConstantInt::get(Ty, C0->abs());
3938 case Intrinsic::clmul:
3939 if (!C0 || !C1)
3940 return Constant::getNullValue(Ty);
3941 return ConstantInt::get(Ty, APIntOps::clmul(*C0, *C1));
3942 case Intrinsic::pdep:
3943 if (!C0 || !C1)
3944 return Constant::getNullValue(Ty);
3945 return ConstantInt::get(Ty, APIntOps::pdep(*C0, *C1));
3946 case Intrinsic::pext:
3947 if (!C0 || !C1)
3948 return Constant::getNullValue(Ty);
3949 return ConstantInt::get(Ty, APIntOps::pext(*C0, *C1));
3950 case Intrinsic::smulh:
3951 if (!C0 || !C1)
3952 return Constant::getNullValue(Ty);
3953 return ConstantInt::get(Ty, APIntOps::mulhs(*C0, *C1));
3954 case Intrinsic::umulh:
3955 if (!C0 || !C1)
3956 return Constant::getNullValue(Ty);
3957 return ConstantInt::get(Ty, APIntOps::mulhu(*C0, *C1));
3958 case Intrinsic::amdgcn_wave_reduce_add:
3959 case Intrinsic::amdgcn_wave_reduce_sub:
3960 case Intrinsic::amdgcn_wave_reduce_xor: {
3961 if (C0 && C0->isZero())
3962 return Constant::getNullValue(Ty);
3963 return nullptr;
3964 }
3965 case Intrinsic::amdgcn_wave_reduce_umin:
3966 case Intrinsic::amdgcn_wave_reduce_umax:
3967 case Intrinsic::amdgcn_wave_reduce_max:
3968 case Intrinsic::amdgcn_wave_reduce_min:
3969 case Intrinsic::amdgcn_wave_reduce_and:
3970 case Intrinsic::amdgcn_wave_reduce_or:
3971 return Operands[0];
3972 }
3973
3974 return nullptr;
3975 }
3976
3977 // Support ConstantVector in case we have an Undef in the top.
3978 if ((isa<ConstantVector>(Operands[0]) ||
3980 // Check for default rounding mode.
3981 // FIXME: Support other rounding modes?
3983 cast<ConstantInt>(Operands[1])->getValue() == 4) {
3984 auto *Op = cast<Constant>(Operands[0]);
3985 switch (IntrinsicID) {
3986 default: break;
3987 case Intrinsic::x86_avx512_vcvtss2si32:
3988 case Intrinsic::x86_avx512_vcvtss2si64:
3989 case Intrinsic::x86_avx512_vcvtsd2si32:
3990 case Intrinsic::x86_avx512_vcvtsd2si64:
3991 if (ConstantFP *FPOp =
3992 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
3993 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
3994 /*roundTowardZero=*/false, Ty,
3995 /*IsSigned*/true);
3996 break;
3997 case Intrinsic::x86_avx512_vcvtss2usi32:
3998 case Intrinsic::x86_avx512_vcvtss2usi64:
3999 case Intrinsic::x86_avx512_vcvtsd2usi32:
4000 case Intrinsic::x86_avx512_vcvtsd2usi64:
4001 if (ConstantFP *FPOp =
4002 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4003 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4004 /*roundTowardZero=*/false, Ty,
4005 /*IsSigned*/false);
4006 break;
4007 case Intrinsic::x86_avx512_cvttss2si:
4008 case Intrinsic::x86_avx512_cvttss2si64:
4009 case Intrinsic::x86_avx512_cvttsd2si:
4010 case Intrinsic::x86_avx512_cvttsd2si64:
4011 if (ConstantFP *FPOp =
4012 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4013 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4014 /*roundTowardZero=*/true, Ty,
4015 /*IsSigned*/true);
4016 break;
4017 case Intrinsic::x86_avx512_cvttss2usi:
4018 case Intrinsic::x86_avx512_cvttss2usi64:
4019 case Intrinsic::x86_avx512_cvttsd2usi:
4020 case Intrinsic::x86_avx512_cvttsd2usi64:
4021 if (ConstantFP *FPOp =
4022 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
4023 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
4024 /*roundTowardZero=*/true, Ty,
4025 /*IsSigned*/false);
4026 break;
4027 }
4028 }
4029
4030 if (IntrinsicID == Intrinsic::experimental_cttz_elts) {
4031 auto *FVTy = dyn_cast<FixedVectorType>(Operands[0]->getType());
4032 bool ZeroIsPoison = cast<ConstantInt>(Operands[1])->isOne();
4033 if (!FVTy)
4034 return nullptr;
4035 unsigned Width = Ty->getIntegerBitWidth();
4036 if (APInt::getMaxValue(Width).ult(FVTy->getNumElements()) ||
4037 Operands[0]->containsPoisonElement())
4038 return PoisonValue::get(Ty);
4039 for (unsigned I = 0; I < FVTy->getNumElements(); ++I) {
4040 Constant *Elt = Operands[0]->getAggregateElement(I);
4041 if (!Elt)
4042 return nullptr;
4043 if (isa<UndefValue>(Elt) || Elt->isNullValue())
4044 continue;
4045 return ConstantInt::get(Ty, I);
4046 }
4047 if (ZeroIsPoison)
4048 return PoisonValue::get(Ty);
4049 return ConstantInt::get(Ty, FVTy->getNumElements());
4050 }
4051 return nullptr;
4052}
4053
4054static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
4055 const APFloat &S0,
4056 const APFloat &S1,
4057 const APFloat &S2) {
4058 unsigned ID;
4059 const fltSemantics &Sem = S0.getSemantics();
4060 APFloat MA(Sem), SC(Sem), TC(Sem);
4061 if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
4062 if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
4063 // S2 < 0
4064 ID = 5;
4065 SC = -S0;
4066 } else {
4067 ID = 4;
4068 SC = S0;
4069 }
4070 MA = S2;
4071 TC = -S1;
4072 } else if (abs(S1) >= abs(S0)) {
4073 if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
4074 // S1 < 0
4075 ID = 3;
4076 TC = -S2;
4077 } else {
4078 ID = 2;
4079 TC = S2;
4080 }
4081 MA = S1;
4082 SC = S0;
4083 } else {
4084 if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
4085 // S0 < 0
4086 ID = 1;
4087 SC = S2;
4088 } else {
4089 ID = 0;
4090 SC = -S2;
4091 }
4092 MA = S0;
4093 TC = -S1;
4094 }
4095 switch (IntrinsicID) {
4096 default:
4097 llvm_unreachable("unhandled amdgcn cube intrinsic");
4098 case Intrinsic::amdgcn_cubeid:
4099 return APFloat(Sem, ID);
4100 case Intrinsic::amdgcn_cubema:
4101 return MA + MA;
4102 case Intrinsic::amdgcn_cubesc:
4103 return SC;
4104 case Intrinsic::amdgcn_cubetc:
4105 return TC;
4106 }
4107}
4108
4109static Constant *ConstantFoldAMDGCNPermIntrinsic(ArrayRef<Constant *> Operands,
4110 Type *Ty) {
4111 const APInt *C0, *C1, *C2;
4112 if (!getConstIntOrUndef(Operands[0], C0) ||
4113 !getConstIntOrUndef(Operands[1], C1) ||
4114 !getConstIntOrUndef(Operands[2], C2))
4115 return nullptr;
4116
4117 if (!C2)
4118 return UndefValue::get(Ty);
4119
4120 APInt Val(32, 0);
4121 unsigned NumUndefBytes = 0;
4122 for (unsigned I = 0; I < 32; I += 8) {
4123 unsigned Sel = C2->extractBitsAsZExtValue(8, I);
4124 unsigned B = 0;
4125
4126 if (Sel >= 13)
4127 B = 0xff;
4128 else if (Sel == 12)
4129 B = 0x00;
4130 else {
4131 const APInt *Src = ((Sel & 10) == 10 || (Sel & 12) == 4) ? C0 : C1;
4132 if (!Src)
4133 ++NumUndefBytes;
4134 else if (Sel < 8)
4135 B = Src->extractBitsAsZExtValue(8, (Sel & 3) * 8);
4136 else
4137 B = Src->extractBitsAsZExtValue(1, (Sel & 1) ? 31 : 15) * 0xff;
4138 }
4139
4140 Val.insertBits(B, I, 8);
4141 }
4142
4143 if (NumUndefBytes == 4)
4144 return UndefValue::get(Ty);
4145
4146 return ConstantInt::get(Ty, Val);
4147}
4148
4149static Constant *ConstantFoldScalarCall3(StringRef Name,
4150 Intrinsic::ID IntrinsicID, Type *Ty,
4152 const TargetLibraryInfo *TLI = nullptr,
4153 const CallBase *Call = nullptr) {
4154 assert(Operands.size() == 3 && "Wrong number of operands.");
4155
4156 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
4157 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
4158 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
4159 const APFloat &C1 = Op1->getValueAPF();
4160 const APFloat &C2 = Op2->getValueAPF();
4161 const APFloat &C3 = Op3->getValueAPF();
4162
4163 if (const auto *ConstrIntr =
4165 RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
4166 APFloat Res = C1;
4168 switch (IntrinsicID) {
4169 default:
4170 return nullptr;
4171 case Intrinsic::experimental_constrained_fma:
4172 case Intrinsic::experimental_constrained_fmuladd:
4173 St = Res.fusedMultiplyAdd(C2, C3, RM);
4174 break;
4175 }
4176 if (mayFoldConstrained(
4177 const_cast<ConstrainedFPIntrinsic *>(ConstrIntr), St))
4178 return ConstantFP::get(Ty, Res);
4179 return nullptr;
4180 }
4181
4182 switch (IntrinsicID) {
4183 default: break;
4184 case Intrinsic::amdgcn_fma_legacy: {
4185 // The legacy behaviour is that multiplying +/- 0.0 by anything, even
4186 // NaN or infinity, gives +0.0.
4187 if (C1.isZero() || C2.isZero()) {
4188 // It's tempting to just return C3 here, but that would give the
4189 // wrong result if C3 was -0.0.
4190 return ConstantFP::get(Ty, APFloat(0.0f) + C3);
4191 }
4192 [[fallthrough]];
4193 }
4194 case Intrinsic::fma:
4195 case Intrinsic::fmuladd: {
4196 APFloat V = C1;
4198 return ConstantFP::get(Ty, V);
4199 }
4200
4201 case Intrinsic::nvvm_fma_rm_f:
4202 case Intrinsic::nvvm_fma_rn_f:
4203 case Intrinsic::nvvm_fma_rp_f:
4204 case Intrinsic::nvvm_fma_rz_f:
4205 case Intrinsic::nvvm_fma_rm_d:
4206 case Intrinsic::nvvm_fma_rn_d:
4207 case Intrinsic::nvvm_fma_rp_d:
4208 case Intrinsic::nvvm_fma_rz_d:
4209 case Intrinsic::nvvm_fma_rm_ftz_f:
4210 case Intrinsic::nvvm_fma_rn_ftz_f:
4211 case Intrinsic::nvvm_fma_rp_ftz_f:
4212 case Intrinsic::nvvm_fma_rz_ftz_f: {
4213 bool IsFTZ = nvvm::FMAShouldFTZ(IntrinsicID);
4214 APFloat A = IsFTZ ? FTZPreserveSign(C1) : C1;
4215 APFloat B = IsFTZ ? FTZPreserveSign(C2) : C2;
4216 APFloat C = IsFTZ ? FTZPreserveSign(C3) : C3;
4217
4218 APFloat::roundingMode RoundMode =
4219 nvvm::GetFMARoundingMode(IntrinsicID);
4220
4221 APFloat Res = A;
4222 APFloat::opStatus Status = Res.fusedMultiplyAdd(B, C, RoundMode);
4223
4224 if (!Res.isNaN() &&
4226 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
4227 return ConstantFP::get(Ty, Res);
4228 }
4229 return nullptr;
4230 }
4231
4232 case Intrinsic::amdgcn_cubeid:
4233 case Intrinsic::amdgcn_cubema:
4234 case Intrinsic::amdgcn_cubesc:
4235 case Intrinsic::amdgcn_cubetc: {
4236 APFloat V = ConstantFoldAMDGCNCubeIntrinsic(IntrinsicID, C1, C2, C3);
4237 return ConstantFP::get(Ty, V);
4238 }
4239 }
4240 }
4241
4242 // TODO: Add constant folding for the _sat variants.
4243 if (IntrinsicID == Intrinsic::nvvm_fadd ||
4244 IntrinsicID == Intrinsic::nvvm_fadd_ftz) {
4245 bool IsFTZ = IntrinsicID == Intrinsic::nvvm_fadd_ftz;
4246 APFloat A =
4247 IsFTZ ? FTZPreserveSign(Op1->getValueAPF()) : Op1->getValueAPF();
4248 APFloat B =
4249 IsFTZ ? FTZPreserveSign(Op2->getValueAPF()) : Op2->getValueAPF();
4250
4251 APFloat Res = A;
4254
4255 if (!Res.isNaN() &&
4257 Res = IsFTZ ? FTZPreserveSign(Res) : Res;
4258 return ConstantFP::get(Ty, Res);
4259 }
4260 return nullptr;
4261 }
4262 }
4263 }
4264
4265 if (IntrinsicID == Intrinsic::smul_fix ||
4266 IntrinsicID == Intrinsic::smul_fix_sat) {
4267 const APInt *C0, *C1;
4268 if (!getConstIntOrUndef(Operands[0], C0) ||
4269 !getConstIntOrUndef(Operands[1], C1))
4270 return nullptr;
4271
4272 // undef * C -> 0
4273 // C * undef -> 0
4274 if (!C0 || !C1)
4275 return Constant::getNullValue(Ty);
4276
4277 // This code performs rounding towards negative infinity in case the result
4278 // cannot be represented exactly for the given scale. Targets that do care
4279 // about rounding should use a target hook for specifying how rounding
4280 // should be done, and provide their own folding to be consistent with
4281 // rounding. This is the same approach as used by
4282 // DAGTypeLegalizer::ExpandIntRes_MULFIX.
4283 unsigned Scale = cast<ConstantInt>(Operands[2])->getZExtValue();
4284 unsigned Width = C0->getBitWidth();
4285 assert(Scale < Width && "Illegal scale.");
4286 unsigned ExtendedWidth = Width * 2;
4287 APInt Product =
4288 (C0->sext(ExtendedWidth) * C1->sext(ExtendedWidth)).ashr(Scale);
4289 if (IntrinsicID == Intrinsic::smul_fix_sat) {
4290 APInt Max = APInt::getSignedMaxValue(Width).sext(ExtendedWidth);
4291 APInt Min = APInt::getSignedMinValue(Width).sext(ExtendedWidth);
4292 Product = APIntOps::smin(Product, Max);
4293 Product = APIntOps::smax(Product, Min);
4294 }
4295 return ConstantInt::get(Ty->getContext(), Product.sextOrTrunc(Width));
4296 }
4297
4298 if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
4299 const APInt *C0, *C1, *C2;
4300 if (!getConstIntOrUndef(Operands[0], C0) ||
4301 !getConstIntOrUndef(Operands[1], C1) ||
4302 !getConstIntOrUndef(Operands[2], C2))
4303 return nullptr;
4304
4305 bool IsRight = IntrinsicID == Intrinsic::fshr;
4306 if (!C2)
4307 return Operands[IsRight ? 1 : 0];
4308 if (!C0 && !C1)
4309 return UndefValue::get(Ty);
4310
4311 // The shift amount is interpreted as modulo the bitwidth. If the shift
4312 // amount is effectively 0, avoid UB due to oversized inverse shift below.
4313 unsigned BitWidth = C2->getBitWidth();
4314 unsigned ShAmt = C2->urem(BitWidth);
4315 if (!ShAmt)
4316 return Operands[IsRight ? 1 : 0];
4317
4318 // (C0 << ShlAmt) | (C1 >> LshrAmt)
4319 unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
4320 unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
4321 if (!C0)
4322 return ConstantInt::get(Ty, C1->lshr(LshrAmt));
4323 if (!C1)
4324 return ConstantInt::get(Ty, C0->shl(ShlAmt));
4325 return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
4326 }
4327
4328 if (IntrinsicID == Intrinsic::amdgcn_perm)
4329 return ConstantFoldAMDGCNPermIntrinsic(Operands, Ty);
4330
4331 return nullptr;
4332}
4333
4334static Constant *ConstantFoldScalarCall(StringRef Name,
4335 Intrinsic::ID IntrinsicID, Type *Ty,
4337 const TargetLibraryInfo *TLI = nullptr,
4338 const CallBase *Call = nullptr) {
4339 if (IntrinsicID != Intrinsic::not_intrinsic &&
4341 intrinsicPropagatesPoison(IntrinsicID))
4342 return PoisonValue::get(Ty);
4343
4344 if (Operands.size() == 1)
4345 return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
4346
4347 if (Operands.size() == 2) {
4348 if (Constant *FoldedLibCall =
4349 ConstantFoldLibCall2(Name, Ty, Operands, TLI)) {
4350 return FoldedLibCall;
4351 }
4352 return ConstantFoldIntrinsicCall2(IntrinsicID, Ty, Operands, Call);
4353 }
4354
4355 if (Operands.size() == 3)
4356 return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
4357
4358 return nullptr;
4359}
4360
4361static Constant *ConstantFoldFixedVectorCall(
4362 StringRef Name, Intrinsic::ID IntrinsicID, FixedVectorType *FVTy,
4364 const TargetLibraryInfo *TLI = nullptr, const CallBase *Call = nullptr) {
4367 Type *Ty = FVTy->getElementType();
4368
4369 switch (IntrinsicID) {
4370 case Intrinsic::masked_load: {
4371 auto *SrcPtr = Operands[0];
4372 auto *Mask = Operands[1];
4373 auto *Passthru = Operands[2];
4374
4375 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
4376
4377 SmallVector<Constant *, 32> NewElements;
4378 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4379 auto *MaskElt = Mask->getAggregateElement(I);
4380 if (!MaskElt)
4381 break;
4382 auto *PassthruElt = Passthru->getAggregateElement(I);
4383 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
4384 if (isa<UndefValue>(MaskElt)) {
4385 if (PassthruElt)
4386 NewElements.push_back(PassthruElt);
4387 else if (VecElt)
4388 NewElements.push_back(VecElt);
4389 else
4390 return nullptr;
4391 }
4392 if (MaskElt->isNullValue()) {
4393 if (!PassthruElt)
4394 return nullptr;
4395 NewElements.push_back(PassthruElt);
4396 } else if (MaskElt->isOneValue()) {
4397 if (!VecElt)
4398 return nullptr;
4399 NewElements.push_back(VecElt);
4400 } else {
4401 return nullptr;
4402 }
4403 }
4404 if (NewElements.size() != FVTy->getNumElements())
4405 return nullptr;
4406 return ConstantVector::get(NewElements);
4407 }
4408 case Intrinsic::arm_mve_vctp8:
4409 case Intrinsic::arm_mve_vctp16:
4410 case Intrinsic::arm_mve_vctp32:
4411 case Intrinsic::arm_mve_vctp64: {
4412 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
4413 unsigned Lanes = FVTy->getNumElements();
4414 uint64_t Limit = Op->getZExtValue();
4415
4417 for (unsigned i = 0; i < Lanes; i++) {
4418 if (i < Limit)
4420 else
4422 }
4423 return ConstantVector::get(NCs);
4424 }
4425 return nullptr;
4426 }
4427 case Intrinsic::get_active_lane_mask: {
4428 auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
4429 auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
4430 if (Op0 && Op1) {
4431 unsigned Lanes = FVTy->getNumElements();
4432 APInt Base = Op0->getValue();
4433 APInt Limit = Op1->getValue();
4434
4436 for (unsigned I = 0; I < Lanes; I++) {
4437 bool Overflow;
4438 if (Base.uadd_ov(APInt(Base.getBitWidth(), I), Overflow).ult(Limit) &&
4439 !Overflow)
4441 else
4443 }
4444 return ConstantVector::get(NCs);
4445 }
4446 return nullptr;
4447 }
4448 case Intrinsic::vector_extract: {
4449 auto *Idx = dyn_cast<ConstantInt>(Operands[1]);
4450 Constant *Vec = Operands[0];
4451 if (!Idx || !isa<FixedVectorType>(Vec->getType()))
4452 return nullptr;
4453
4454 unsigned NumElements = FVTy->getNumElements();
4455 unsigned VecNumElements =
4456 cast<FixedVectorType>(Vec->getType())->getNumElements();
4457 unsigned StartingIndex = Idx->getZExtValue();
4458
4459 // Extracting entire vector is nop
4460 if (NumElements == VecNumElements && StartingIndex == 0)
4461 return Vec;
4462
4463 for (unsigned I = StartingIndex, E = StartingIndex + NumElements; I < E;
4464 ++I) {
4465 Constant *Elt = Vec->getAggregateElement(I);
4466 if (!Elt)
4467 return nullptr;
4468 Result[I - StartingIndex] = Elt;
4469 }
4470
4471 return ConstantVector::get(Result);
4472 }
4473 case Intrinsic::vector_insert: {
4474 Constant *Vec = Operands[0];
4475 Constant *SubVec = Operands[1];
4476 auto *Idx = dyn_cast<ConstantInt>(Operands[2]);
4477 if (!Idx || !isa<FixedVectorType>(Vec->getType()))
4478 return nullptr;
4479
4480 unsigned SubVecNumElements =
4481 cast<FixedVectorType>(SubVec->getType())->getNumElements();
4482 unsigned VecNumElements =
4483 cast<FixedVectorType>(Vec->getType())->getNumElements();
4484 unsigned IdxN = Idx->getZExtValue();
4485 // Replacing entire vector with a subvec is nop
4486 if (SubVecNumElements == VecNumElements && IdxN == 0)
4487 return SubVec;
4488
4489 for (unsigned I = 0; I < VecNumElements; ++I) {
4490 Constant *Elt;
4491 if (I < IdxN + SubVecNumElements)
4492 Elt = SubVec->getAggregateElement(I - IdxN);
4493 else
4494 Elt = Vec->getAggregateElement(I);
4495 if (!Elt)
4496 return nullptr;
4497 Result[I] = Elt;
4498 }
4499 return ConstantVector::get(Result);
4500 }
4501 case Intrinsic::vector_interleave2:
4502 case Intrinsic::vector_interleave3:
4503 case Intrinsic::vector_interleave4:
4504 case Intrinsic::vector_interleave5:
4505 case Intrinsic::vector_interleave6:
4506 case Intrinsic::vector_interleave7:
4507 case Intrinsic::vector_interleave8: {
4508 unsigned NumElements =
4509 cast<FixedVectorType>(Operands[0]->getType())->getNumElements();
4510 unsigned NumOperands = Operands.size();
4511 for (unsigned I = 0; I < NumElements; ++I) {
4512 for (unsigned J = 0; J < NumOperands; ++J) {
4513 Constant *Elt = Operands[J]->getAggregateElement(I);
4514 if (!Elt)
4515 return nullptr;
4516 Result[NumOperands * I + J] = Elt;
4517 }
4518 }
4519 return ConstantVector::get(Result);
4520 }
4521 case Intrinsic::vector_partial_reduce_add:
4522 return constantFoldVectorPartialReduceAdd(Operands[0], Operands[1], DL);
4523 case Intrinsic::wasm_dot: {
4524 unsigned NumElements =
4525 cast<FixedVectorType>(Operands[0]->getType())->getNumElements();
4526
4527 assert(NumElements == 8 && Result.size() == 4 &&
4528 "wasm dot takes i16x8 and produces i32x4");
4529 assert(Ty->isIntegerTy());
4530 int32_t MulVector[8];
4531
4532 for (unsigned I = 0; I < NumElements; ++I) {
4533 ConstantInt *Elt0 =
4534 dyn_cast<ConstantInt>(Operands[0]->getAggregateElement(I));
4535 ConstantInt *Elt1 =
4536 dyn_cast<ConstantInt>(Operands[1]->getAggregateElement(I));
4537
4538 if (!Elt0 || !Elt1)
4539 return nullptr;
4540
4541 MulVector[I] = Elt0->getSExtValue() * Elt1->getSExtValue();
4542 }
4543 for (unsigned I = 0; I < Result.size(); I++) {
4544 int64_t IAdd = (int64_t)MulVector[I * 2] + (int64_t)MulVector[I * 2 + 1];
4545 Result[I] = ConstantInt::getSigned(Ty, IAdd, /*ImplicitTrunc=*/true);
4546 }
4547
4548 return ConstantVector::get(Result);
4549 }
4550 case Intrinsic::nvvm_fadd:
4551 case Intrinsic::nvvm_fadd_ftz:
4552 // The rounding mode operand is a scalar, so the lane-wise folding below
4553 // does not apply.
4554 // TODO: Fold these by passing the rounding mode through to every lane.
4555 return nullptr;
4556 default:
4557 break;
4558 }
4559
4560 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4561 // Gather a column of constants.
4562 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
4563 // Some intrinsics use a scalar type for certain arguments.
4564 if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, J, /*TTI=*/nullptr)) {
4565 Lane[J] = Operands[J];
4566 continue;
4567 }
4568
4569 Constant *Agg = Operands[J]->getAggregateElement(I);
4570 if (!Agg)
4571 return nullptr;
4572
4573 Lane[J] = Agg;
4574 }
4575
4576 // Use the regular scalar folding to simplify this column.
4577 Constant *Folded =
4578 ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
4579 if (!Folded)
4580 return nullptr;
4581 Result[I] = Folded;
4582 }
4583
4584 return ConstantVector::get(Result);
4585}
4586
4587static Constant *ConstantFoldScalableVectorCall(
4588 StringRef Name, Intrinsic::ID IntrinsicID, ScalableVectorType *SVTy,
4590 const TargetLibraryInfo *TLI, const CallBase *Call) {
4591 switch (IntrinsicID) {
4592 case Intrinsic::aarch64_sve_convert_from_svbool: {
4593 Constant *Src = Operands[0];
4594 if (!Src->isNullValue())
4595 break;
4596
4597 return ConstantInt::getFalse(SVTy);
4598 }
4599 case Intrinsic::get_active_lane_mask: {
4600 auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
4601 auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
4602 if (Op0 && Op1 && Op0->getValue().uge(Op1->getValue()))
4603 return ConstantVector::getNullValue(SVTy);
4604 break;
4605 }
4606 case Intrinsic::vector_interleave2:
4607 case Intrinsic::vector_interleave3:
4608 case Intrinsic::vector_interleave4:
4609 case Intrinsic::vector_interleave5:
4610 case Intrinsic::vector_interleave6:
4611 case Intrinsic::vector_interleave7:
4612 case Intrinsic::vector_interleave8: {
4613 Constant *SplatVal = Operands[0]->getSplatValue();
4614 if (!SplatVal)
4615 return nullptr;
4616
4618 return nullptr;
4619
4620 return ConstantVector::getSplat(SVTy->getElementCount(), SplatVal);
4621 }
4622 default:
4623 break;
4624 }
4625
4626 // If trivially vectorizable, try folding it via the scalar call if all
4627 // operands are splats.
4628
4629 // TODO: ConstantFoldFixedVectorCall should probably check this too?
4630 if (!isTriviallyVectorizable(IntrinsicID))
4631 return nullptr;
4632
4634 for (auto [I, Op] : enumerate(Operands)) {
4635 if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, I, /*TTI=*/nullptr)) {
4636 SplatOps.push_back(Op);
4637 continue;
4638 }
4639 Constant *Splat = Op->getSplatValue();
4640 if (!Splat)
4641 return nullptr;
4642 SplatOps.push_back(Splat);
4643 }
4644 Constant *Folded = ConstantFoldScalarCall(
4645 Name, IntrinsicID, SVTy->getElementType(), SplatOps, TLI, Call);
4646 if (!Folded)
4647 return nullptr;
4648 return ConstantVector::getSplat(SVTy->getElementCount(), Folded);
4649}
4650
4651static std::pair<Constant *, Constant *>
4652ConstantFoldScalarFrexpCall(Constant *Op, Type *IntTy) {
4653 auto *ConstFP = dyn_cast<ConstantFP>(Op);
4654 if (!ConstFP)
4655 return {};
4656
4657 const APFloat &U = ConstFP->getValueAPF();
4658 int FrexpExp;
4659 APFloat FrexpMant = frexp(U, FrexpExp, APFloat::rmNearestTiesToEven);
4660 Constant *Result0 = ConstantFP::get(ConstFP->getType(), FrexpMant);
4661
4662 // The exponent is an "unspecified value" for inf/nan. We use zero to avoid
4663 // using undef.
4664 Constant *Result1 = FrexpMant.isFinite()
4665 ? ConstantInt::getSigned(IntTy, FrexpExp)
4666 : ConstantInt::getNullValue(IntTy);
4667 return {Result0, Result1};
4668}
4669
4670/// Handle intrinsics that return tuples, which may be tuples of vectors.
4671static Constant *
4672ConstantFoldStructCall(StringRef Name, Intrinsic::ID IntrinsicID,
4674 const DataLayout &DL, const TargetLibraryInfo *TLI,
4675 const CallBase *Call) {
4676
4677 switch (IntrinsicID) {
4678 case Intrinsic::frexp: {
4679 Type *Ty0 = StTy->getContainedType(0);
4680 Type *Ty1 = StTy->getContainedType(1)->getScalarType();
4681
4682 if (auto *FVTy0 = dyn_cast<FixedVectorType>(Ty0)) {
4683 SmallVector<Constant *, 4> Results0(FVTy0->getNumElements());
4684 SmallVector<Constant *, 4> Results1(FVTy0->getNumElements());
4685
4686 for (unsigned I = 0, E = FVTy0->getNumElements(); I != E; ++I) {
4687 Constant *Lane = Operands[0]->getAggregateElement(I);
4688 std::tie(Results0[I], Results1[I]) =
4689 ConstantFoldScalarFrexpCall(Lane, Ty1);
4690 if (!Results0[I])
4691 return nullptr;
4692 }
4693
4694 return ConstantStruct::get(StTy, ConstantVector::get(Results0),
4695 ConstantVector::get(Results1));
4696 }
4697
4698 auto [Result0, Result1] = ConstantFoldScalarFrexpCall(Operands[0], Ty1);
4699 if (!Result0)
4700 return nullptr;
4701 return ConstantStruct::get(StTy, Result0, Result1);
4702 }
4703 case Intrinsic::sincos: {
4704 Type *Ty = StTy->getContainedType(0);
4705 Type *TyScalar = Ty->getScalarType();
4706
4707 auto ConstantFoldScalarSincosCall =
4708 [&](Constant *Op) -> std::pair<Constant *, Constant *> {
4709 Constant *SinResult =
4710 ConstantFoldScalarCall(Name, Intrinsic::sin, TyScalar, Op, TLI, Call);
4711 Constant *CosResult =
4712 ConstantFoldScalarCall(Name, Intrinsic::cos, TyScalar, Op, TLI, Call);
4713 return std::make_pair(SinResult, CosResult);
4714 };
4715
4716 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4717 SmallVector<Constant *> SinResults(FVTy->getNumElements());
4718 SmallVector<Constant *> CosResults(FVTy->getNumElements());
4719
4720 for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
4721 Constant *Lane = Operands[0]->getAggregateElement(I);
4722 std::tie(SinResults[I], CosResults[I]) =
4723 ConstantFoldScalarSincosCall(Lane);
4724 if (!SinResults[I] || !CosResults[I])
4725 return nullptr;
4726 }
4727
4728 return ConstantStruct::get(StTy, ConstantVector::get(SinResults),
4729 ConstantVector::get(CosResults));
4730 }
4731
4732 if (!Ty->isFloatingPointTy())
4733 return nullptr;
4734
4735 auto [SinResult, CosResult] = ConstantFoldScalarSincosCall(Operands[0]);
4736 if (!SinResult || !CosResult)
4737 return nullptr;
4738 return ConstantStruct::get(StTy, SinResult, CosResult);
4739 }
4740 case Intrinsic::vector_deinterleave2:
4741 case Intrinsic::vector_deinterleave3:
4742 case Intrinsic::vector_deinterleave4:
4743 case Intrinsic::vector_deinterleave5:
4744 case Intrinsic::vector_deinterleave6:
4745 case Intrinsic::vector_deinterleave7:
4746 case Intrinsic::vector_deinterleave8: {
4747 unsigned NumResults = StTy->getNumElements();
4748 auto *Vec = Operands[0];
4749 auto *VecTy = cast<VectorType>(Vec->getType());
4750
4751 ElementCount ResultEC =
4752 VecTy->getElementCount().divideCoefficientBy(NumResults);
4753
4754 if (auto *EltC = Vec->getSplatValue()) {
4755 auto *ResultVec = ConstantVector::getSplat(ResultEC, EltC);
4756 SmallVector<Constant *, 8> Results(NumResults, ResultVec);
4757 return ConstantStruct::get(StTy, Results);
4758 }
4759
4760 if (!ResultEC.isFixed())
4761 return nullptr;
4762
4763 unsigned NumElements = ResultEC.getFixedValue();
4765 SmallVector<Constant *> Elements(NumElements);
4766 for (unsigned I = 0; I != NumResults; ++I) {
4767 for (unsigned J = 0; J != NumElements; ++J) {
4768 Constant *Elt = Vec->getAggregateElement(J * NumResults + I);
4769 if (!Elt)
4770 return nullptr;
4771 Elements[J] = Elt;
4772 }
4773 Results[I] = ConstantVector::get(Elements);
4774 }
4775 return ConstantStruct::get(StTy, Results);
4776 }
4777 default:
4778 // TODO: Constant folding of vector intrinsics that fall through here does
4779 // not work (e.g. overflow intrinsics)
4780 return ConstantFoldScalarCall(Name, IntrinsicID, StTy, Operands, TLI, Call);
4781 }
4782
4783 return nullptr;
4784}
4785
4786} // end anonymous namespace
4787
4790 const DataLayout &DL,
4791 const Function *CxtF) {
4792 // In the absence of CxtF, assume strictfp conservatively.
4793 if (!canConstantFoldIntrinsic(ID, CxtF ? CxtF->isStrictFP() : true) ||
4796 Ty, ArrayRef<Value *>((Value *const *)Ops.data(), Ops.size()))))
4797 return nullptr;
4798 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
4799 return ConstantFoldFixedVectorCall("", ID, FVTy, Ops, DL);
4800 return ConstantFoldScalarCall("", ID, Ty, Ops);
4801}
4802
4805 const TargetLibraryInfo *TLI,
4806 bool AllowNonDeterministic) {
4807 if (Call->isNoBuiltin())
4808 return nullptr;
4809 if (!F->hasName())
4810 return nullptr;
4811
4812 // If this is not an intrinsic and not recognized as a library call, bail out.
4813 Intrinsic::ID IID = F->getIntrinsicID();
4814 if (IID == Intrinsic::not_intrinsic) {
4815 if (!TLI)
4816 return nullptr;
4817 if (TLI->getLibFunc(*F) == NotLibFunc)
4818 return nullptr;
4819 }
4820
4821 // Conservatively assume that floating-point libcalls may be
4822 // non-deterministic.
4823 Type *Ty = F->getReturnType();
4824 if (!AllowNonDeterministic && Ty->isFPOrFPVectorTy())
4825 return nullptr;
4826
4827 StringRef Name = F->getName();
4828 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
4829 return ConstantFoldFixedVectorCall(
4830 Name, IID, FVTy, Operands, F->getDataLayout(), TLI, Call);
4831
4832 if (auto *SVTy = dyn_cast<ScalableVectorType>(Ty))
4833 return ConstantFoldScalableVectorCall(
4834 Name, IID, SVTy, Operands, F->getDataLayout(), TLI, Call);
4835
4836 if (auto *StTy = dyn_cast<StructType>(Ty))
4837 return ConstantFoldStructCall(Name, IID, StTy, Operands,
4838 F->getDataLayout(), TLI, Call);
4839
4840 // TODO: If this is a library function, we already discovered that above,
4841 // so we should pass the LibFunc, not the name (and it might be better
4842 // still to separate intrinsic handling from libcalls).
4843 return ConstantFoldScalarCall(Name, IID, Ty, Operands, TLI, Call);
4844}
4845
4847 const TargetLibraryInfo *TLI) {
4848 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
4849 // (and to some extent ConstantFoldScalarCall).
4850 if (Call->isNoBuiltin() || Call->isStrictFP())
4851 return false;
4852 Function *F = Call->getCalledFunction();
4853 if (!F)
4854 return false;
4855
4856 if (!TLI)
4857 return false;
4858
4859 LibFunc Func = TLI->getLibFunc(*F);
4860 if (Func == NotLibFunc)
4861 return false;
4862
4863 if (Call->arg_size() == 1) {
4864 if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
4865 const APFloat &Op = OpC->getValueAPF();
4866 switch (Func) {
4867 case LibFunc_logl:
4868 case LibFunc_log:
4869 case LibFunc_logf:
4870 case LibFunc_log2l:
4871 case LibFunc_log2:
4872 case LibFunc_log2f:
4873 case LibFunc_log10l:
4874 case LibFunc_log10:
4875 case LibFunc_log10f:
4876 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
4877
4878 case LibFunc_ilogb:
4879 return !Op.isNaN() && !Op.isZero() && !Op.isInfinity();
4880
4881 case LibFunc_expl:
4882 case LibFunc_exp:
4883 case LibFunc_expf:
4884 // FIXME: These boundaries are slightly conservative.
4885 if (OpC->getType()->isDoubleTy())
4886 return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
4887 if (OpC->getType()->isFloatTy())
4888 return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
4889 break;
4890
4891 case LibFunc_exp2l:
4892 case LibFunc_exp2:
4893 case LibFunc_exp2f:
4894 // FIXME: These boundaries are slightly conservative.
4895 if (OpC->getType()->isDoubleTy())
4896 return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
4897 if (OpC->getType()->isFloatTy())
4898 return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
4899 break;
4900
4901 case LibFunc_sinl:
4902 case LibFunc_sin:
4903 case LibFunc_sinf:
4904 case LibFunc_cosl:
4905 case LibFunc_cos:
4906 case LibFunc_cosf:
4907 return !Op.isInfinity();
4908
4909 case LibFunc_tanl:
4910 case LibFunc_tan:
4911 case LibFunc_tanf: {
4912 // FIXME: Stop using the host math library.
4913 // FIXME: The computation isn't done in the right precision.
4914 Type *Ty = OpC->getType();
4915 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy())
4916 return ConstantFoldFP(tan, OpC->getValueAPF(), Ty) != nullptr;
4917 break;
4918 }
4919
4920 case LibFunc_atan:
4921 case LibFunc_atanf:
4922 case LibFunc_atanl:
4923 // Per POSIX, this MAY fail if Op is denormal. We choose not failing.
4924 return true;
4925
4926 case LibFunc_asinl:
4927 case LibFunc_asin:
4928 case LibFunc_asinf:
4929 case LibFunc_acosl:
4930 case LibFunc_acos:
4931 case LibFunc_acosf:
4932 return !(Op < APFloat::getOne(Op.getSemantics(), true) ||
4933 Op > APFloat::getOne(Op.getSemantics()));
4934
4935 case LibFunc_sinh:
4936 case LibFunc_cosh:
4937 case LibFunc_sinhf:
4938 case LibFunc_coshf:
4939 case LibFunc_sinhl:
4940 case LibFunc_coshl:
4941 // FIXME: These boundaries are slightly conservative.
4942 if (OpC->getType()->isDoubleTy())
4943 return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
4944 if (OpC->getType()->isFloatTy())
4945 return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
4946 break;
4947
4948 case LibFunc_sqrtl:
4949 case LibFunc_sqrt:
4950 case LibFunc_sqrtf:
4951 return Op.isNaN() || Op.isZero() || !Op.isNegative();
4952
4953 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
4954 // maybe others?
4955 default:
4956 break;
4957 }
4958 }
4959 }
4960
4961 if (Call->arg_size() == 2) {
4962 ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
4963 ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
4964 if (Op0C && Op1C) {
4965 const APFloat &Op0 = Op0C->getValueAPF();
4966 const APFloat &Op1 = Op1C->getValueAPF();
4967
4968 switch (Func) {
4969 case LibFunc_powl:
4970 case LibFunc_pow:
4971 case LibFunc_powf: {
4972 // FIXME: Stop using the host math library.
4973 // FIXME: The computation isn't done in the right precision.
4974 Type *Ty = Op0C->getType();
4975 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
4976 if (Ty == Op1C->getType())
4977 return ConstantFoldBinaryFP(pow, Op0, Op1, Ty) != nullptr;
4978 }
4979 break;
4980 }
4981
4982 case LibFunc_fmodl:
4983 case LibFunc_fmod:
4984 case LibFunc_fmodf:
4985 case LibFunc_remainderl:
4986 case LibFunc_remainder:
4987 case LibFunc_remainderf:
4988 return Op0.isNaN() || Op1.isNaN() ||
4989 (!Op0.isInfinity() && !Op1.isZero());
4990
4991 case LibFunc_atan2:
4992 case LibFunc_atan2f:
4993 case LibFunc_atan2l:
4994 // Although IEEE-754 says atan2(+/-0.0, +/-0.0) are well-defined, and
4995 // GLIBC and MSVC do not appear to raise an error on those, we
4996 // cannot rely on that behavior. POSIX and C11 say that a domain error
4997 // may occur, so allow for that possibility.
4998 return !Op0.isZero() || !Op1.isZero();
4999
5000 case LibFunc_nextafter:
5001 case LibFunc_nextafterf:
5002 case LibFunc_nextafterl:
5003 case LibFunc_nexttoward:
5004 case LibFunc_nexttowardf:
5005 case LibFunc_nexttowardl: {
5006 return ConstantFoldNextToward(Op0, Op1, F->getReturnType()) != nullptr;
5007 }
5008 default:
5009 break;
5010 }
5011 }
5012 }
5013
5014 return false;
5015}
5016
5018 unsigned CastOp, const DataLayout &DL,
5019 PreservedCastFlags *Flags) {
5020 switch (CastOp) {
5021 case Instruction::BitCast:
5022 // Bitcast is always lossless.
5023 return ConstantFoldCastOperand(Instruction::BitCast, C, InvCastTo, DL);
5024 case Instruction::Trunc: {
5025 auto *ZExtC = ConstantFoldCastOperand(Instruction::ZExt, C, InvCastTo, DL);
5026 if (Flags) {
5027 // Truncation back on ZExt value is always NUW.
5028 Flags->NUW = true;
5029 // Test positivity of C.
5030 auto *SExtC =
5031 ConstantFoldCastOperand(Instruction::SExt, C, InvCastTo, DL);
5032 Flags->NSW = ZExtC == SExtC;
5033 }
5034 return ZExtC;
5035 }
5036 case Instruction::SExt:
5037 case Instruction::ZExt: {
5038 auto *InvC = ConstantExpr::getTrunc(C, InvCastTo);
5039 auto *CastInvC = ConstantFoldCastOperand(CastOp, InvC, C->getType(), DL);
5040 // Must satisfy CastOp(InvC) == C.
5041 if (!CastInvC || CastInvC != C)
5042 return nullptr;
5043 if (Flags && CastOp == Instruction::ZExt) {
5044 auto *SExtInvC =
5045 ConstantFoldCastOperand(Instruction::SExt, InvC, C->getType(), DL);
5046 // Test positivity of InvC.
5047 Flags->NNeg = CastInvC == SExtInvC;
5048 }
5049 return InvC;
5050 }
5051 case Instruction::FPExt: {
5052 Constant *InvC =
5053 ConstantFoldCastOperand(Instruction::FPTrunc, C, InvCastTo, DL);
5054 if (InvC) {
5055 Constant *CastInvC =
5056 ConstantFoldCastOperand(CastOp, InvC, C->getType(), DL);
5057 if (CastInvC == C)
5058 return InvC;
5059 }
5060 return nullptr;
5061 }
5062 default:
5063 return nullptr;
5064 }
5065}
5066
5068 const DataLayout &DL,
5069 PreservedCastFlags *Flags) {
5070 return getLosslessInvCast(C, DestTy, Instruction::ZExt, DL, Flags);
5071}
5072
5074 const DataLayout &DL,
5075 PreservedCastFlags *Flags) {
5076 return getLosslessInvCast(C, DestTy, Instruction::SExt, DL, Flags);
5077}
5078
5079void TargetFolder::anchor() {}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
constexpr LLT S1
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static Constant * FoldBitCast(Constant *V, Type *DestTy)
static ConstantFP * flushDenormalConstant(Type *Ty, const APFloat &APF, DenormalMode::DenormalModeKind Mode)
Constant * getConstantAtOffset(Constant *Base, APInt Offset, const DataLayout &DL)
If this Offset points exactly to the start of an aggregate element, return that element,...
static ConstantFP * flushDenormalConstantFP(ConstantFP *CFP, const Function *CxtF, bool IsOutput)
static cl::opt< bool > DisableFPCallFolding("disable-fp-call-folding", cl::desc("Disable constant-folding of FP intrinsics and libcalls."), cl::init(false), cl::Hidden)
static bool canConstantFoldIntrinsic(Intrinsic::ID ID, bool IsStrictFP)
Returns true if the intrinsic can be constant folded, given IsStrictFP.
static bool anyTypeContainsFP(Type *RetTy, ArrayRef< Value * > Ops)
Given a function's return type and its operands, determine if any of them of of floating-point type.
static DenormalMode getInstrDenormalMode(const Function *CtxF, Type *Ty)
Return the denormal mode that can be assumed when executing a floating point operation at CtxI.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
Hexagon Common GEP
amode Optimize addressing mode
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
This file contains the definitions of the enumerations and flags associated with NVVM Intrinsics,...
if(PassOpts->AAPipeline)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file implements the SmallBitVector class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
The Input class is used to parse a yaml document into in-memory structs and vectors.
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
llvm::RoundingMode roundingMode
IEEE-754R 4.3: Rounding-direction attributes.
Definition APFloat.h:359
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:364
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:363
static constexpr roundingMode rmNearestTiesToAway
Definition APFloat.h:366
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1224
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1312
void copySign(const APFloat &RHS)
Definition APFloat.h:1406
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6034
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1294
bool isNegative() const
Definition APFloat.h:1583
LLVM_ABI double convertToDouble() const
Converts this APFloat to host double value.
Definition APFloat.cpp:6093
bool isPosInfinity() const
Definition APFloat.h:1596
bool isNormal() const
Definition APFloat.h:1587
bool isDenormal() const
Definition APFloat.h:1584
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1285
const fltSemantics & getSemantics() const
Definition APFloat.h:1591
bool isNonZero() const
Definition APFloat.h:1592
bool isFinite() const
Definition APFloat.h:1588
bool isNaN() const
Definition APFloat.h:1581
static APFloat getOne(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative One.
Definition APFloat.h:1192
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1303
bool isSignaling() const
Definition APFloat.h:1585
opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, roundingMode RM)
Definition APFloat.h:1339
bool isZero() const
Definition APFloat.h:1579
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1330
bool isNegInfinity() const
Definition APFloat.h:1597
opStatus roundToIntegral(roundingMode RM)
Definition APFloat.h:1352
void changeSign()
Definition APFloat.h:1401
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1183
bool isInfinity() const
Definition APFloat.h:1580
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2093
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const
Definition APInt.cpp:517
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2064
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
LLVM_ABI APInt usub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1986
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
LLVM_ABI APInt sadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1966
LLVM_ABI APInt uadd_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1973
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2074
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1998
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
LLVM_ABI APInt ssub_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1979
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2083
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static LLVM_ABI Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
static LLVM_ABI unsigned isEliminableCastPair(Instruction::CastOps firstOpcode, Instruction::CastOps secondOpcode, Type *SrcTy, Type *MidTy, Type *DstTy, const DataLayout *DL)
Determine how a pair of casts can be eliminated, if they can be at all.
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
bool isSigned() const
Definition InstrTypes.h:993
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:878
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI bool isDesirableCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is desirable.
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static Constant * getPtrAdd(Constant *Ptr, Constant *Offset, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReduced=nullptr)
Create a getelementptr i8, ptr, offset constant expression.
Definition Constants.h:1513
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1614
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isDesirableBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is desirable.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1474
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Constrained floating point compare intrinsics.
This is the common base class for constrained floating point intrinsics.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI std::optional< RoundingMode > getRoundingMode() const
Wrapper for a function that represents a value that functionally represents the original function.
Definition Constants.h:1143
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:258
iterator end()
Definition DenseMap.h:176
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:319
static LLVM_ABI bool compare(const APFloat &LHS, const APFloat &RHS, FCmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
DenormalMode getDenormalMode(const fltSemantics &FPType) const
Returns the denormal handling type for the default rounding mode of the function.
Definition Function.cpp:806
bool isStrictFP() const
Determine if the function has strict floating point sematics.
Definition Function.h:637
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
GEPNoWrapFlags withoutNoUnsignedSignedWrap() const
static GEPNoWrapFlags noUnsignedWrap()
bool hasNoUnsignedSignedWrap() const
bool isInBounds() const
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
bool isCast() const
bool isBinaryOp() const
bool isUnaryOp() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
static APInt getSaturationPoint(Intrinsic::ID ID, unsigned numBits)
Min/max intrinsics are monotonic, they operate on a fixed-bitwidth values, so there is a certain thre...
static ICmpInst::Predicate getPredicate(Intrinsic::ID ID)
Returns the comparison predicate underlying the intrinsic.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Class to represent scalable SIMD vectors.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
SmallBitVector & set()
iterator_range< const_set_bits_iterator > set_bits() const
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const
Given a valid byte offset into the structure, returns the structure index that contains it.
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Provides information about what library functions are available for the current target.
bool has(LibFunc F) const
Tests whether a library function is available.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
Definition Type.h:243
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:298
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isX86_AMXTy() const
Return true if this is X86 AMX.
Definition Type.h:202
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition Type.h:392
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull, bool *CanBeFreed) const
Returns the number of bytes known to be dereferenceable for the pointer value.
Definition Value.cpp:918
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:171
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:237
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3165
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3245
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3157
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
LLVM_ABI APInt clmul(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, also known as XOR multiplication, and return low-bits.
Definition APInt.cpp:3225
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3255
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:454
static constexpr cmpResult cmpEqual
Definition APFloat.h:462
@ ebStrict
This corresponds to "fpexcept.strict".
Definition FPEnv.h:42
@ ebIgnore
This corresponds to "fpexcept.ignore".
Definition FPEnv.h:40
constexpr double pi
APFloat::roundingMode GetRoundingModeFromImmArg(const Value *ImmArgVal)
APFloat::roundingMode GetFMARoundingMode(Intrinsic::ID IntrinsicID)
DenormalMode GetNVVMDenormMode(bool ShouldFTZ)
bool FPToIntegerIntrinsicNaNZero(Intrinsic::ID IntrinsicID)
APFloat::roundingMode GetFDivRoundingMode(Intrinsic::ID IntrinsicID)
bool FPToIntegerIntrinsicResultIsSigned(Intrinsic::ID IntrinsicID)
APFloat::roundingMode GetFPToIntegerRoundingMode(Intrinsic::ID IntrinsicID)
bool RCPShouldFTZ(Intrinsic::ID IntrinsicID)
bool FPToIntegerIntrinsicShouldFTZ(Intrinsic::ID IntrinsicID)
bool FDivShouldFTZ(Intrinsic::ID IntrinsicID)
bool FMinFMaxIsXorSignAbs(Intrinsic::ID IntrinsicID)
APFloat::roundingMode GetFMulRoundingMode(Intrinsic::ID IntrinsicID)
bool UnaryMathIntrinsicShouldFTZ(Intrinsic::ID IntrinsicID)
bool FMinFMaxShouldFTZ(Intrinsic::ID IntrinsicID)
bool FMAShouldFTZ(Intrinsic::ID IntrinsicID)
bool FMulShouldFTZ(Intrinsic::ID IntrinsicID)
APFloat::roundingMode GetRCPRoundingMode(Intrinsic::ID IntrinsicID)
bool FMinFMaxPropagatesNaNs(Intrinsic::ID IntrinsicID)
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Constant * ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy, const DataLayout &DL)
ConstantFoldLoadThroughBitcast - try to cast constant to destination type returning null if unsuccess...
static double log2(double V)
LLVM_ABI Constant * ConstantFoldSelectInstruction(Constant *Cond, Constant *V1, Constant *V2)
Attempt to constant fold a select instruction with the specified operands.
LLVM_ABI Constant * ConstantFoldFPInstOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL, const Instruction *I, bool AllowNonDeterministic=true)
Attempt to constant fold a floating point binary operation with the specified operands,...
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
unsigned getPointerAddressSpace(const Type *T)
Definition SPIRVUtils.h:395
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Constant * ConstantFoldInstruction(const Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Definition APFloat.h:1721
LLVM_ABI Constant * ConstantFoldCompareInstruction(CmpInst::Predicate Predicate, Constant *C1, Constant *C2)
LLVM_ABI Constant * ConstantFoldUnaryInstruction(unsigned Opcode, Constant *V)
LLVM_ABI bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL, DSOLocalEquivalent **DSOEquiv=nullptr)
If this constant is a constant offset from a global, return the global and the constant.
LLVM_ABI bool isMathLibCallNoop(const CallBase *Call, const TargetLibraryInfo *TLI)
Check whether the given call has no side-effects.
LLVM_ABI Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1801
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F, const TargetLibraryInfo *TLI=nullptr)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1713
LLVM_ABI Constant * ConstantFoldExtractValueInstruction(Constant *Agg, ArrayRef< unsigned > Idxs)
Attempt to constant fold an extractvalue instruction with the specified operands and indices.
LLVM_ABI Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1756
LLVM_ABI Constant * ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty, const DataLayout &DL)
If C is a uniform value where all bits are the same (either all zero, all ones, all undef or all pois...
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI Constant * getLosslessUnsignedTrunc(Constant *C, Type *DestTy, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
LLVM_ABI Constant * ConstantFoldIntrinsic(Intrinsic::ID ID, ArrayRef< Constant * > Ops, Type *Ty, const DataLayout &DL, const Function *CxtF=nullptr)
LLVM_READONLY LLVM_ABI std::optional< APFloat > exp(const APFloat &X, RoundingMode RM=APFloat::rmNearestTiesToEven, APFloat::opStatus *Status=nullptr)
Implement IEEE 754-2019 exp functions.
Definition APFloat.cpp:6253
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1787
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM)
Returns: X * 2^Exp for integral exponents.
Definition APFloat.h:1701
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI Constant * getLosslessSignedTrunc(Constant *C, Type *DestTy, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 minNum semantics.
Definition APFloat.h:1737
@ Sub
Subtraction of integers.
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
RoundingMode
Rounding mode.
@ NearestTiesToEven
roundTiesToEven.
@ Dynamic
Denotes mode unknown at compile time.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
constexpr unsigned BitWidth
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI Constant * FlushFPConstant(Constant *Operand, const Function *CxtF, bool IsOutput)
Attempt to flush float point constant according to denormal mode set in the instruction's parent func...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
LLVM_ABI Constant * ConstantFoldInsertValueInstruction(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs)
Attempt to constant fold an insertvalue instruction with the specified operands and indices.
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition APFloat.h:1774
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1814
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CxtF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
Represent subnormal handling kind for floating point instruction inputs and outputs.
DenormalModeKind Input
Denormal treatment kind for floating point instruction inputs in the default floating-point environme...
DenormalModeKind
Represent handled modes for denormal (aka subnormal) modes in the floating point environment.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
DenormalModeKind Output
Denormal flushing mode for floating point instruction results in the default floating point environme...
static constexpr DenormalMode getDynamic()
static constexpr DenormalMode getIEEE()
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58