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