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