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