Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/llvm/lib/Analysis/ConstantFolding.cpp
Line
Count
Source (jump to first uncovered line)
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/SmallVector.h"
26
#include "llvm/ADT/StringRef.h"
27
#include "llvm/Analysis/TargetFolder.h"
28
#include "llvm/Analysis/TargetLibraryInfo.h"
29
#include "llvm/Analysis/ValueTracking.h"
30
#include "llvm/Analysis/VectorUtils.h"
31
#include "llvm/Config/config.h"
32
#include "llvm/IR/Constant.h"
33
#include "llvm/IR/ConstantFold.h"
34
#include "llvm/IR/Constants.h"
35
#include "llvm/IR/DataLayout.h"
36
#include "llvm/IR/DerivedTypes.h"
37
#include "llvm/IR/Function.h"
38
#include "llvm/IR/GlobalValue.h"
39
#include "llvm/IR/GlobalVariable.h"
40
#include "llvm/IR/InstrTypes.h"
41
#include "llvm/IR/Instruction.h"
42
#include "llvm/IR/Instructions.h"
43
#include "llvm/IR/IntrinsicInst.h"
44
#include "llvm/IR/Intrinsics.h"
45
#include "llvm/IR/IntrinsicsAArch64.h"
46
#include "llvm/IR/IntrinsicsAMDGPU.h"
47
#include "llvm/IR/IntrinsicsARM.h"
48
#include "llvm/IR/IntrinsicsWebAssembly.h"
49
#include "llvm/IR/IntrinsicsX86.h"
50
#include "llvm/IR/Operator.h"
51
#include "llvm/IR/Type.h"
52
#include "llvm/IR/Value.h"
53
#include "llvm/Support/Casting.h"
54
#include "llvm/Support/ErrorHandling.h"
55
#include "llvm/Support/KnownBits.h"
56
#include "llvm/Support/MathExtras.h"
57
#include <cassert>
58
#include <cerrno>
59
#include <cfenv>
60
#include <cmath>
61
#include <cstdint>
62
63
using namespace llvm;
64
65
namespace {
66
67
//===----------------------------------------------------------------------===//
68
// Constant Folding internal helper functions
69
//===----------------------------------------------------------------------===//
70
71
static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
72
                                        Constant *C, Type *SrcEltTy,
73
                                        unsigned NumSrcElts,
74
1.18k
                                        const DataLayout &DL) {
75
  // Now that we know that the input value is a vector of integers, just shift
76
  // and insert them into our result.
77
1.18k
  unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
78
11.9k
  for (unsigned i = 0; i != NumSrcElts; ++i) {
79
10.8k
    Constant *Element;
80
10.8k
    if (DL.isLittleEndian())
81
10.7k
      Element = C->getAggregateElement(NumSrcElts - i - 1);
82
30
    else
83
30
      Element = C->getAggregateElement(i);
84
85
10.8k
    if (Element && isa<UndefValue>(Element)) {
86
2.04k
      Result <<= BitShift;
87
2.04k
      continue;
88
2.04k
    }
89
90
8.76k
    auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
91
8.76k
    if (!ElementCI)
92
24
      return ConstantExpr::getBitCast(C, DestTy);
93
94
8.74k
    Result <<= BitShift;
95
8.74k
    Result |= ElementCI->getValue().zext(Result.getBitWidth());
96
8.74k
  }
97
98
1.16k
  return nullptr;
99
1.18k
}
100
101
/// Constant fold bitcast, symbolically evaluating it with DataLayout.
102
/// This always returns a non-null constant, but it may be a
103
/// ConstantExpr if unfoldable.
104
12.8k
Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
105
12.8k
  assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) &&
106
12.8k
         "Invalid constantexpr bitcast!");
107
108
  // Catch the obvious splat cases.
109
12.8k
  if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy))
110
2.76k
    return Res;
111
112
10.0k
  if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
113
    // Handle a vector->scalar integer/fp cast.
114
1.90k
    if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
115
1.18k
      unsigned NumSrcElts = cast<FixedVectorType>(VTy)->getNumElements();
116
1.18k
      Type *SrcEltTy = VTy->getElementType();
117
118
      // If the vector is a vector of floating point, convert it to vector of int
119
      // to simplify things.
120
1.18k
      if (SrcEltTy->isFloatingPointTy()) {
121
84
        unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
122
84
        auto *SrcIVTy = FixedVectorType::get(
123
84
            IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
124
        // Ask IR to do the conversion now that #elts line up.
125
84
        C = ConstantExpr::getBitCast(C, SrcIVTy);
126
84
      }
127
128
1.18k
      APInt Result(DL.getTypeSizeInBits(DestTy), 0);
129
1.18k
      if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
130
1.18k
                                                SrcEltTy, NumSrcElts, DL))
131
24
        return CE;
132
133
1.16k
      if (isa<IntegerType>(DestTy))
134
1.10k
        return ConstantInt::get(DestTy, Result);
135
136
57
      APFloat FP(DestTy->getFltSemantics(), Result);
137
57
      return ConstantFP::get(DestTy->getContext(), FP);
138
1.16k
    }
139
1.90k
  }
140
141
  // The code below only handles casts to vectors currently.
142
8.88k
  auto *DestVTy = dyn_cast<VectorType>(DestTy);
143
8.88k
  if (!DestVTy)
144
7.96k
    return ConstantExpr::getBitCast(C, DestTy);
145
146
  // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
147
  // vector so the code below can handle it uniformly.
148
920
  if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
149
95
    Constant *Ops = C; // don't take the address of C!
150
95
    return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
151
95
  }
152
153
  // If this is a bitcast from constant vector -> vector, fold it.
154
825
  if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
155
121
    return ConstantExpr::getBitCast(C, DestTy);
156
157
  // If the element types match, IR can fold it.
158
704
  unsigned NumDstElt = cast<FixedVectorType>(DestVTy)->getNumElements();
159
704
  unsigned NumSrcElt = cast<FixedVectorType>(C->getType())->getNumElements();
160
704
  if (NumDstElt == NumSrcElt)
161
44
    return ConstantExpr::getBitCast(C, DestTy);
162
163
660
  Type *SrcEltTy = cast<VectorType>(C->getType())->getElementType();
164
660
  Type *DstEltTy = DestVTy->getElementType();
165
166
  // Otherwise, we're changing the number of elements in a vector, which
167
  // requires endianness information to do the right thing.  For example,
168
  //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
169
  // folds to (little endian):
170
  //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
171
  // and to (big endian):
172
  //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
173
174
  // First thing is first.  We only want to think about integer here, so if
175
  // we have something in FP form, recast it as integer.
176
660
  if (DstEltTy->isFloatingPointTy()) {
177
    // Fold to an vector of integers with same size as our FP type.
178
26
    unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
179
26
    auto *DestIVTy = FixedVectorType::get(
180
26
        IntegerType::get(C->getContext(), FPWidth), NumDstElt);
181
    // Recursively handle this integer conversion, if possible.
182
26
    C = FoldBitCast(C, DestIVTy, DL);
183
184
    // Finally, IR can handle this now that #elts line up.
185
26
    return ConstantExpr::getBitCast(C, DestTy);
186
26
  }
187
188
  // Okay, we know the destination is integer, if the input is FP, convert
189
  // it to integer first.
190
634
  if (SrcEltTy->isFloatingPointTy()) {
191
16
    unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
192
16
    auto *SrcIVTy = FixedVectorType::get(
193
16
        IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
194
    // Ask IR to do the conversion now that #elts line up.
195
16
    C = ConstantExpr::getBitCast(C, SrcIVTy);
196
    // If IR wasn't able to fold it, bail out.
197
16
    if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
198
16
        !isa<ConstantDataVector>(C))
199
0
      return C;
200
16
  }
201
202
  // Now we know that the input and output vectors are both integer vectors
203
  // of the same size, and that their #elements is not the same.  Do the
204
  // conversion here, which depends on whether the input or output has
205
  // more elements.
206
634
  bool isLittleEndian = DL.isLittleEndian();
207
208
634
  SmallVector<Constant*, 32> Result;
209
634
  if (NumDstElt < NumSrcElt) {
210
    // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
211
306
    Constant *Zero = Constant::getNullValue(DstEltTy);
212
306
    unsigned Ratio = NumSrcElt/NumDstElt;
213
306
    unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
214
306
    unsigned SrcElt = 0;
215
1.69k
    for (unsigned i = 0; i != NumDstElt; ++i) {
216
      // Build each element of the result.
217
1.39k
      Constant *Elt = Zero;
218
1.39k
      unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
219
4.70k
      for (unsigned j = 0; j != Ratio; ++j) {
220
3.31k
        Constant *Src = C->getAggregateElement(SrcElt++);
221
3.31k
        if (Src && isa<UndefValue>(Src))
222
855
          Src = Constant::getNullValue(
223
855
              cast<VectorType>(C->getType())->getElementType());
224
2.45k
        else
225
2.45k
          Src = dyn_cast_or_null<ConstantInt>(Src);
226
3.31k
        if (!Src)  // Reject constantexpr elements.
227
0
          return ConstantExpr::getBitCast(C, DestTy);
228
229
        // Zero extend the element to the right size.
230
3.31k
        Src = ConstantFoldCastOperand(Instruction::ZExt, Src, Elt->getType(),
231
3.31k
                                      DL);
232
3.31k
        assert(Src && "Constant folding cannot fail on plain integers");
233
234
        // Shift it to the right place, depending on endianness.
235
0
        Src = ConstantFoldBinaryOpOperands(
236
3.31k
            Instruction::Shl, Src, ConstantInt::get(Src->getType(), ShiftAmt),
237
3.31k
            DL);
238
3.31k
        assert(Src && "Constant folding cannot fail on plain integers");
239
240
3.31k
        ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
241
242
        // Mix it in.
243
3.31k
        Elt = ConstantFoldBinaryOpOperands(Instruction::Or, Elt, Src, DL);
244
3.31k
        assert(Elt && "Constant folding cannot fail on plain integers");
245
3.31k
      }
246
1.39k
      Result.push_back(Elt);
247
1.39k
    }
248
306
    return ConstantVector::get(Result);
249
306
  }
250
251
  // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
252
328
  unsigned Ratio = NumDstElt/NumSrcElt;
253
328
  unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
254
255
  // Loop over each source value, expanding into multiple results.
256
1.05k
  for (unsigned i = 0; i != NumSrcElt; ++i) {
257
740
    auto *Element = C->getAggregateElement(i);
258
259
740
    if (!Element) // Reject constantexpr elements.
260
0
      return ConstantExpr::getBitCast(C, DestTy);
261
262
740
    if (isa<UndefValue>(Element)) {
263
      // Correctly Propagate undef values.
264
67
      Result.append(Ratio, UndefValue::get(DstEltTy));
265
67
      continue;
266
67
    }
267
268
673
    auto *Src = dyn_cast<ConstantInt>(Element);
269
673
    if (!Src)
270
16
      return ConstantExpr::getBitCast(C, DestTy);
271
272
657
    unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
273
2.85k
    for (unsigned j = 0; j != Ratio; ++j) {
274
      // Shift the piece of the value into the right place, depending on
275
      // endianness.
276
2.19k
      APInt Elt = Src->getValue().lshr(ShiftAmt);
277
2.19k
      ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
278
279
      // Truncate and remember this piece.
280
2.19k
      Result.push_back(ConstantInt::get(DstEltTy, Elt.trunc(DstBitSize)));
281
2.19k
    }
282
657
  }
283
284
312
  return ConstantVector::get(Result);
285
328
}
286
287
} // end anonymous namespace
288
289
/// If this constant is a constant offset from a global, return the global and
290
/// the constant. Because of constantexprs, this function is recursive.
291
bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
292
                                      APInt &Offset, const DataLayout &DL,
293
4.63k
                                      DSOLocalEquivalent **DSOEquiv) {
294
4.63k
  if (DSOEquiv)
295
0
    *DSOEquiv = nullptr;
296
297
  // Trivial case, constant is the global.
298
4.63k
  if ((GV = dyn_cast<GlobalValue>(C))) {
299
390
    unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
300
390
    Offset = APInt(BitWidth, 0);
301
390
    return true;
302
390
  }
303
304
4.24k
  if (auto *FoundDSOEquiv = dyn_cast<DSOLocalEquivalent>(C)) {
305
0
    if (DSOEquiv)
306
0
      *DSOEquiv = FoundDSOEquiv;
307
0
    GV = FoundDSOEquiv->getGlobalValue();
308
0
    unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
309
0
    Offset = APInt(BitWidth, 0);
310
0
    return true;
311
0
  }
312
313
  // Otherwise, if this isn't a constant expr, bail out.
314
4.24k
  auto *CE = dyn_cast<ConstantExpr>(C);
315
4.24k
  if (!CE) return false;
316
317
  // Look through ptr->int and ptr->ptr casts.
318
1.89k
  if (CE->getOpcode() == Instruction::PtrToInt ||
319
1.89k
      CE->getOpcode() == Instruction::BitCast)
320
469
    return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL,
321
469
                                      DSOEquiv);
322
323
  // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
324
1.42k
  auto *GEP = dyn_cast<GEPOperator>(CE);
325
1.42k
  if (!GEP)
326
930
    return false;
327
328
499
  unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
329
499
  APInt TmpOffset(BitWidth, 0);
330
331
  // If the base isn't a global+constant, we aren't either.
332
499
  if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL,
333
499
                                  DSOEquiv))
334
102
    return false;
335
336
  // Otherwise, add any offset that our operands provide.
337
397
  if (!GEP->accumulateConstantOffset(DL, TmpOffset))
338
63
    return false;
339
340
334
  Offset = TmpOffset;
341
334
  return true;
342
397
}
343
344
Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy,
345
10.3k
                                         const DataLayout &DL) {
346
11.9k
  do {
347
11.9k
    Type *SrcTy = C->getType();
348
11.9k
    if (SrcTy == DestTy)
349
8.06k
      return C;
350
351
3.92k
    TypeSize DestSize = DL.getTypeSizeInBits(DestTy);
352
3.92k
    TypeSize SrcSize = DL.getTypeSizeInBits(SrcTy);
353
3.92k
    if (!TypeSize::isKnownGE(SrcSize, DestSize))
354
1.08k
      return nullptr;
355
356
    // Catch the obvious splat cases (since all-zeros can coerce non-integral
357
    // pointers legally).
358
2.84k
    if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy))
359
663
      return Res;
360
361
    // If the type sizes are the same and a cast is legal, just directly
362
    // cast the constant.
363
    // But be careful not to coerce non-integral pointers illegally.
364
2.18k
    if (SrcSize == DestSize &&
365
2.18k
        DL.isNonIntegralPointerType(SrcTy->getScalarType()) ==
366
449
            DL.isNonIntegralPointerType(DestTy->getScalarType())) {
367
449
      Instruction::CastOps Cast = Instruction::BitCast;
368
      // If we are going from a pointer to int or vice versa, we spell the cast
369
      // differently.
370
449
      if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
371
18
        Cast = Instruction::IntToPtr;
372
431
      else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
373
30
        Cast = Instruction::PtrToInt;
374
375
449
      if (CastInst::castIsValid(Cast, C, DestTy))
376
87
        return ConstantFoldCastOperand(Cast, C, DestTy, DL);
377
449
    }
378
379
    // If this isn't an aggregate type, there is nothing we can do to drill down
380
    // and find a bitcastable constant.
381
2.09k
    if (!SrcTy->isAggregateType() && !SrcTy->isVectorTy())
382
485
      return nullptr;
383
384
    // We're simulating a load through a pointer that was bitcast to point to
385
    // a different type, so we can try to walk down through the initial
386
    // elements of an aggregate to see if some part of the aggregate is
387
    // castable to implement the "load" semantic model.
388
1.60k
    if (SrcTy->isStructTy()) {
389
      // Struct types might have leading zero-length elements like [0 x i32],
390
      // which are certainly not what we are looking for, so skip them.
391
218
      unsigned Elem = 0;
392
218
      Constant *ElemC;
393
218
      do {
394
218
        ElemC = C->getAggregateElement(Elem++);
395
218
      } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()).isZero());
396
218
      C = ElemC;
397
1.39k
    } else {
398
      // For non-byte-sized vector elements, the first element is not
399
      // necessarily located at the vector base address.
400
1.39k
      if (auto *VT = dyn_cast<VectorType>(SrcTy))
401
55
        if (!DL.typeSizeEqualsStoreSize(VT->getElementType()))
402
0
          return nullptr;
403
404
1.39k
      C = C->getAggregateElement(0u);
405
1.39k
    }
406
1.60k
  } while (C);
407
408
0
  return nullptr;
409
10.3k
}
410
411
namespace {
412
413
/// Recursive helper to read bits out of global. C is the constant being copied
414
/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
415
/// results into and BytesLeft is the number of bytes left in
416
/// the CurPtr buffer. DL is the DataLayout.
417
bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
418
9.98k
                        unsigned BytesLeft, const DataLayout &DL) {
419
9.98k
  assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
420
9.98k
         "Out of range access");
421
422
  // If this element is zero or undefined, we can just return since *CurPtr is
423
  // zero initialized.
424
9.98k
  if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
425
1.20k
    return true;
426
427
8.77k
  if (auto *CI = dyn_cast<ConstantInt>(C)) {
428
4.41k
    if ((CI->getBitWidth() & 7) != 0)
429
345
      return false;
430
4.07k
    const APInt &Val = CI->getValue();
431
4.07k
    unsigned IntBytes = unsigned(CI->getBitWidth()/8);
432
433
13.8k
    for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
434
9.82k
      unsigned n = ByteOffset;
435
9.82k
      if (!DL.isLittleEndian())
436
3.86k
        n = IntBytes - n - 1;
437
9.82k
      CurPtr[i] = Val.extractBits(8, n * 8).getZExtValue();
438
9.82k
      ++ByteOffset;
439
9.82k
    }
440
4.07k
    return true;
441
4.41k
  }
442
443
4.36k
  if (auto *CFP = dyn_cast<ConstantFP>(C)) {
444
1.48k
    if (CFP->getType()->isDoubleTy()) {
445
0
      C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
446
0
      return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
447
0
    }
448
1.48k
    if (CFP->getType()->isFloatTy()){
449
1.48k
      C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
450
1.48k
      return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
451
1.48k
    }
452
0
    if (CFP->getType()->isHalfTy()){
453
0
      C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
454
0
      return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
455
0
    }
456
0
    return false;
457
0
  }
458
459
2.87k
  if (auto *CS = dyn_cast<ConstantStruct>(C)) {
460
408
    const StructLayout *SL = DL.getStructLayout(CS->getType());
461
408
    unsigned Index = SL->getElementContainingOffset(ByteOffset);
462
408
    uint64_t CurEltOffset = SL->getElementOffset(Index);
463
408
    ByteOffset -= CurEltOffset;
464
465
584
    while (true) {
466
      // If the element access is to the element itself and not to tail padding,
467
      // read the bytes from the element.
468
584
      uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
469
470
584
      if (ByteOffset < EltSize &&
471
584
          !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
472
575
                              BytesLeft, DL))
473
52
        return false;
474
475
532
      ++Index;
476
477
      // Check to see if we read from the last struct element, if so we're done.
478
532
      if (Index == CS->getType()->getNumElements())
479
305
        return true;
480
481
      // If we read all of the bytes we needed from this element we're done.
482
227
      uint64_t NextEltOffset = SL->getElementOffset(Index);
483
484
227
      if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
485
51
        return true;
486
487
      // Move to the next element of the struct.
488
176
      CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
489
176
      BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
490
176
      ByteOffset = 0;
491
176
      CurEltOffset = NextEltOffset;
492
176
    }
493
    // not reached.
494
408
  }
495
496
2.46k
  if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
497
2.46k
      isa<ConstantDataSequential>(C)) {
498
2.41k
    uint64_t NumElts, EltSize;
499
2.41k
    Type *EltTy;
500
2.41k
    if (auto *AT = dyn_cast<ArrayType>(C->getType())) {
501
2.39k
      NumElts = AT->getNumElements();
502
2.39k
      EltTy = AT->getElementType();
503
2.39k
      EltSize = DL.getTypeAllocSize(EltTy);
504
2.39k
    } else {
505
24
      NumElts = cast<FixedVectorType>(C->getType())->getNumElements();
506
24
      EltTy = cast<FixedVectorType>(C->getType())->getElementType();
507
      // TODO: For non-byte-sized vectors, current implementation assumes there is
508
      // padding to the next byte boundary between elements.
509
24
      if (!DL.typeSizeEqualsStoreSize(EltTy))
510
0
        return false;
511
512
24
      EltSize = DL.getTypeStoreSize(EltTy);
513
24
    }
514
2.41k
    uint64_t Index = ByteOffset / EltSize;
515
2.41k
    uint64_t Offset = ByteOffset - Index * EltSize;
516
517
5.50k
    for (; Index != NumElts; ++Index) {
518
5.36k
      if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
519
5.36k
                              BytesLeft, DL))
520
387
        return false;
521
522
4.98k
      uint64_t BytesWritten = EltSize - Offset;
523
4.98k
      assert(BytesWritten <= EltSize && "Not indexing into this element?");
524
4.98k
      if (BytesWritten >= BytesLeft)
525
1.89k
        return true;
526
527
3.08k
      Offset = 0;
528
3.08k
      BytesLeft -= BytesWritten;
529
3.08k
      CurPtr += BytesWritten;
530
3.08k
    }
531
135
    return true;
532
2.41k
  }
533
534
49
  if (auto *CE = dyn_cast<ConstantExpr>(C)) {
535
20
    if (CE->getOpcode() == Instruction::IntToPtr &&
536
20
        CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
537
0
      return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
538
0
                                BytesLeft, DL);
539
0
    }
540
20
  }
541
542
  // Otherwise, unknown initializer type.
543
49
  return false;
544
49
}
545
546
Constant *FoldReinterpretLoadFromConst(Constant *C, Type *LoadTy,
547
3.62k
                                       int64_t Offset, const DataLayout &DL) {
548
  // Bail out early. Not expect to load from scalable global variable.
549
3.62k
  if (isa<ScalableVectorType>(LoadTy))
550
0
    return nullptr;
551
552
3.62k
  auto *IntType = dyn_cast<IntegerType>(LoadTy);
553
554
  // If this isn't an integer load we can't fold it directly.
555
3.62k
  if (!IntType) {
556
    // If this is a non-integer load, we can try folding it as an int load and
557
    // then bitcast the result.  This can be useful for union cases.  Note
558
    // that address spaces don't matter here since we're not going to result in
559
    // an actual new load.
560
725
    if (!LoadTy->isFloatingPointTy() && !LoadTy->isPointerTy() &&
561
725
        !LoadTy->isVectorTy())
562
3
      return nullptr;
563
564
722
    Type *MapTy = Type::getIntNTy(C->getContext(),
565
722
                                  DL.getTypeSizeInBits(LoadTy).getFixedValue());
566
722
    if (Constant *Res = FoldReinterpretLoadFromConst(C, MapTy, Offset, DL)) {
567
620
      if (Res->isNullValue() && !LoadTy->isX86_MMXTy() &&
568
620
          !LoadTy->isX86_AMXTy())
569
        // Materializing a zero can be done trivially without a bitcast
570
412
        return Constant::getNullValue(LoadTy);
571
208
      Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy;
572
208
      Res = FoldBitCast(Res, CastTy, DL);
573
208
      if (LoadTy->isPtrOrPtrVectorTy()) {
574
        // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr
575
6
        if (Res->isNullValue() && !LoadTy->isX86_MMXTy() &&
576
6
            !LoadTy->isX86_AMXTy())
577
0
          return Constant::getNullValue(LoadTy);
578
6
        if (DL.isNonIntegralPointerType(LoadTy->getScalarType()))
579
          // Be careful not to replace a load of an addrspace value with an inttoptr here
580
0
          return nullptr;
581
6
        Res = ConstantExpr::getIntToPtr(Res, LoadTy);
582
6
      }
583
208
      return Res;
584
208
    }
585
102
    return nullptr;
586
722
  }
587
588
2.90k
  unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
589
2.90k
  if (BytesLoaded > 32 || BytesLoaded == 0)
590
0
    return nullptr;
591
592
  // If we're not accessing anything in this constant, the result is undefined.
593
2.90k
  if (Offset <= -1 * static_cast<int64_t>(BytesLoaded))
594
523
    return PoisonValue::get(IntType);
595
596
  // TODO: We should be able to support scalable types.
597
2.38k
  TypeSize InitializerSize = DL.getTypeAllocSize(C->getType());
598
2.38k
  if (InitializerSize.isScalable())
599
0
    return nullptr;
600
601
  // If we're not accessing anything in this constant, the result is undefined.
602
2.38k
  if (Offset >= (int64_t)InitializerSize.getFixedValue())
603
0
    return PoisonValue::get(IntType);
604
605
2.38k
  unsigned char RawBytes[32] = {0};
606
2.38k
  unsigned char *CurPtr = RawBytes;
607
2.38k
  unsigned BytesLeft = BytesLoaded;
608
609
  // If we're loading off the beginning of the global, some bytes may be valid.
610
2.38k
  if (Offset < 0) {
611
58
    CurPtr += -Offset;
612
58
    BytesLeft += Offset;
613
58
    Offset = 0;
614
58
  }
615
616
2.38k
  if (!ReadDataFromGlobal(C, Offset, CurPtr, BytesLeft, DL))
617
394
    return nullptr;
618
619
1.98k
  APInt ResultVal = APInt(IntType->getBitWidth(), 0);
620
1.98k
  if (DL.isLittleEndian()) {
621
1.98k
    ResultVal = RawBytes[BytesLoaded - 1];
622
9.92k
    for (unsigned i = 1; i != BytesLoaded; ++i) {
623
7.93k
      ResultVal <<= 8;
624
7.93k
      ResultVal |= RawBytes[BytesLoaded - 1 - i];
625
7.93k
    }
626
1.98k
  } else {
627
1
    ResultVal = RawBytes[0];
628
8
    for (unsigned i = 1; i != BytesLoaded; ++i) {
629
7
      ResultVal <<= 8;
630
7
      ResultVal |= RawBytes[i];
631
7
    }
632
1
  }
633
634
1.98k
  return ConstantInt::get(IntType->getContext(), ResultVal);
635
2.38k
}
636
637
} // anonymous namespace
638
639
// If GV is a constant with an initializer read its representation starting
640
// at Offset and return it as a constant array of unsigned char.  Otherwise
641
// return null.
642
Constant *llvm::ReadByteArrayFromGlobal(const GlobalVariable *GV,
643
170
                                        uint64_t Offset) {
644
170
  if (!GV->isConstant() || !GV->hasDefinitiveInitializer())
645
0
    return nullptr;
646
647
170
  const DataLayout &DL = GV->getParent()->getDataLayout();
648
170
  Constant *Init = const_cast<Constant *>(GV->getInitializer());
649
170
  TypeSize InitSize = DL.getTypeAllocSize(Init->getType());
650
170
  if (InitSize < Offset)
651
0
    return nullptr;
652
653
170
  uint64_t NBytes = InitSize - Offset;
654
170
  if (NBytes > UINT16_MAX)
655
    // Bail for large initializers in excess of 64K to avoid allocating
656
    // too much memory.
657
    // Offset is assumed to be less than or equal than InitSize (this
658
    // is enforced in ReadDataFromGlobal).
659
0
    return nullptr;
660
661
170
  SmallVector<unsigned char, 256> RawBytes(static_cast<size_t>(NBytes));
662
170
  unsigned char *CurPtr = RawBytes.data();
663
664
170
  if (!ReadDataFromGlobal(Init, Offset, CurPtr, NBytes, DL))
665
0
    return nullptr;
666
667
170
  return ConstantDataArray::get(GV->getContext(), RawBytes);
668
170
}
669
670
/// If this Offset points exactly to the start of an aggregate element, return
671
/// that element, otherwise return nullptr.
672
Constant *getConstantAtOffset(Constant *Base, APInt Offset,
673
12.4k
                              const DataLayout &DL) {
674
12.4k
  if (Offset.isZero())
675
1.74k
    return Base;
676
677
10.6k
  if (!isa<ConstantAggregate>(Base) && !isa<ConstantDataSequential>(Base))
678
49
    return nullptr;
679
680
10.6k
  Type *ElemTy = Base->getType();
681
10.6k
  SmallVector<APInt> Indices = DL.getGEPIndicesForOffset(ElemTy, Offset);
682
10.6k
  if (!Offset.isZero() || !Indices[0].isZero())
683
1.98k
    return nullptr;
684
685
8.64k
  Constant *C = Base;
686
15.7k
  for (const APInt &Index : drop_begin(Indices)) {
687
15.7k
    if (Index.isNegative() || Index.getActiveBits() >= 32)
688
0
      return nullptr;
689
690
15.7k
    C = C->getAggregateElement(Index.getZExtValue());
691
15.7k
    if (!C)
692
0
      return nullptr;
693
15.7k
  }
694
695
8.64k
  return C;
696
8.64k
}
697
698
Constant *llvm::ConstantFoldLoadFromConst(Constant *C, Type *Ty,
699
                                          const APInt &Offset,
700
12.4k
                                          const DataLayout &DL) {
701
12.4k
  if (Constant *AtOffset = getConstantAtOffset(C, Offset, DL))
702
10.3k
    if (Constant *Result = ConstantFoldLoadThroughBitcast(AtOffset, Ty, DL))
703
8.81k
      return Result;
704
705
  // Explicitly check for out-of-bounds access, so we return poison even if the
706
  // constant is a uniform value.
707
3.60k
  TypeSize Size = DL.getTypeAllocSize(C->getType());
708
3.60k
  if (!Size.isScalable() && Offset.sge(Size.getFixedValue()))
709
667
    return PoisonValue::get(Ty);
710
711
  // Try an offset-independent fold of a uniform value.
712
2.94k
  if (Constant *Result = ConstantFoldLoadFromUniformValue(C, Ty))
713
34
    return Result;
714
715
  // Try hard to fold loads from bitcasted strange and non-type-safe things.
716
2.90k
  if (Offset.getSignificantBits() <= 64)
717
2.90k
    if (Constant *Result =
718
2.90k
            FoldReinterpretLoadFromConst(C, Ty, Offset.getSExtValue(), DL))
719
2.50k
      return Result;
720
721
397
  return nullptr;
722
2.90k
}
723
724
Constant *llvm::ConstantFoldLoadFromConst(Constant *C, Type *Ty,
725
16
                                          const DataLayout &DL) {
726
16
  return ConstantFoldLoadFromConst(C, Ty, APInt(64, 0), DL);
727
16
}
728
729
Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
730
                                             APInt Offset,
731
159k
                                             const DataLayout &DL) {
732
  // We can only fold loads from constant globals with a definitive initializer.
733
  // Check this upfront, to skip expensive offset calculations.
734
159k
  auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C));
735
159k
  if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
736
146k
    return nullptr;
737
738
12.6k
  C = cast<Constant>(C->stripAndAccumulateConstantOffsets(
739
12.6k
          DL, Offset, /* AllowNonInbounds */ true));
740
741
12.6k
  if (C == GV)
742
12.4k
    if (Constant *Result = ConstantFoldLoadFromConst(GV->getInitializer(), Ty,
743
12.4k
                                                     Offset, DL))
744
12.0k
      return Result;
745
746
  // If this load comes from anywhere in a uniform constant global, the value
747
  // is always the same, regardless of the loaded offset.
748
648
  return ConstantFoldLoadFromUniformValue(GV->getInitializer(), Ty);
749
12.6k
}
750
751
Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
752
159k
                                             const DataLayout &DL) {
753
159k
  APInt Offset(DL.getIndexTypeSizeInBits(C->getType()), 0);
754
159k
  return ConstantFoldLoadFromConstPtr(C, Ty, Offset, DL);
755
159k
}
756
757
20.1k
Constant *llvm::ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty) {
758
20.1k
  if (isa<PoisonValue>(C))
759
245
    return PoisonValue::get(Ty);
760
19.9k
  if (isa<UndefValue>(C))
761
663
    return UndefValue::get(Ty);
762
19.2k
  if (C->isNullValue() && !Ty->isX86_MMXTy() && !Ty->isX86_AMXTy())
763
2.28k
    return Constant::getNullValue(Ty);
764
16.9k
  if (C->isAllOnesValue() &&
765
16.9k
      (Ty->isIntOrIntVectorTy() || Ty->isFPOrFPVectorTy()))
766
278
    return Constant::getAllOnesValue(Ty);
767
16.6k
  return nullptr;
768
16.9k
}
769
770
namespace {
771
772
/// One of Op0/Op1 is a constant expression.
773
/// Attempt to symbolically evaluate the result of a binary operator merging
774
/// these together.  If target data info is available, it is provided as DL,
775
/// otherwise DL is null.
776
Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
777
26.0k
                                    const DataLayout &DL) {
778
  // SROA
779
780
  // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
781
  // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
782
  // bits.
783
784
26.0k
  if (Opc == Instruction::And) {
785
4.11k
    KnownBits Known0 = computeKnownBits(Op0, DL);
786
4.11k
    KnownBits Known1 = computeKnownBits(Op1, DL);
787
4.11k
    if ((Known1.One | Known0.Zero).isAllOnes()) {
788
      // All the bits of Op0 that the 'and' could be masking are already zero.
789
1.04k
      return Op0;
790
1.04k
    }
791
3.07k
    if ((Known0.One | Known1.Zero).isAllOnes()) {
792
      // All the bits of Op1 that the 'and' could be masking are already zero.
793
822
      return Op1;
794
822
    }
795
796
2.25k
    Known0 &= Known1;
797
2.25k
    if (Known0.isConstant())
798
537
      return ConstantInt::get(Op0->getType(), Known0.getConstant());
799
2.25k
  }
800
801
  // If the constant expr is something like &A[123] - &A[4].f, fold this into a
802
  // constant.  This happens frequently when iterating over a global array.
803
23.6k
  if (Opc == Instruction::Sub) {
804
3.34k
    GlobalValue *GV1, *GV2;
805
3.34k
    APInt Offs1, Offs2;
806
807
3.34k
    if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
808
321
      if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
809
2
        unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
810
811
        // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
812
        // PtrToInt may change the bitwidth so we have convert to the right size
813
        // first.
814
2
        return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
815
2
                                                Offs2.zextOrTrunc(OpSize));
816
2
      }
817
3.34k
  }
818
819
23.6k
  return nullptr;
820
23.6k
}
821
822
/// If array indices are not pointer-sized integers, explicitly cast them so
823
/// that they aren't implicitly casted by the getelementptr.
824
Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
825
                         Type *ResultTy, bool InBounds,
826
                         std::optional<unsigned> InRangeIndex,
827
159k
                         const DataLayout &DL, const TargetLibraryInfo *TLI) {
828
159k
  Type *IntIdxTy = DL.getIndexType(ResultTy);
829
159k
  Type *IntIdxScalarTy = IntIdxTy->getScalarType();
830
831
159k
  bool Any = false;
832
159k
  SmallVector<Constant*, 32> NewIdxs;
833
413k
  for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
834
262k
    if ((i == 1 ||
835
262k
         !isa<StructType>(GetElementPtrInst::getIndexedType(
836
102k
             SrcElemTy, Ops.slice(1, i - 1)))) &&
837
262k
        Ops[i]->getType()->getScalarType() != IntIdxScalarTy) {
838
40.2k
      Any = true;
839
40.2k
      Type *NewType =
840
40.2k
          Ops[i]->getType()->isVectorTy() ? IntIdxTy : IntIdxScalarTy;
841
40.2k
      Constant *NewIdx = ConstantFoldCastOperand(
842
40.2k
          CastInst::getCastOpcode(Ops[i], true, NewType, true), Ops[i], NewType,
843
40.2k
          DL);
844
40.2k
      if (!NewIdx)
845
9.15k
        return nullptr;
846
31.1k
      NewIdxs.push_back(NewIdx);
847
31.1k
    } else
848
222k
      NewIdxs.push_back(Ops[i]);
849
262k
  }
850
851
150k
  if (!Any)
852
121k
    return nullptr;
853
854
29.1k
  Constant *C = ConstantExpr::getGetElementPtr(
855
29.1k
      SrcElemTy, Ops[0], NewIdxs, InBounds, InRangeIndex);
856
29.1k
  return ConstantFoldConstant(C, DL, TLI);
857
150k
}
858
859
/// If we can symbolically evaluate the GEP constant expression, do so.
860
Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
861
                                  ArrayRef<Constant *> Ops,
862
                                  const DataLayout &DL,
863
159k
                                  const TargetLibraryInfo *TLI) {
864
159k
  const GEPOperator *InnermostGEP = GEP;
865
159k
  bool InBounds = GEP->isInBounds();
866
867
159k
  Type *SrcElemTy = GEP->getSourceElementType();
868
159k
  Type *ResElemTy = GEP->getResultElementType();
869
159k
  Type *ResTy = GEP->getType();
870
159k
  if (!SrcElemTy->isSized() || isa<ScalableVectorType>(SrcElemTy))
871
0
    return nullptr;
872
873
159k
  if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
874
159k
                                   GEP->isInBounds(), GEP->getInRangeIndex(),
875
159k
                                   DL, TLI))
876
29.1k
    return C;
877
878
130k
  Constant *Ptr = Ops[0];
879
130k
  if (!Ptr->getType()->isPointerTy())
880
4
    return nullptr;
881
882
130k
  Type *IntIdxTy = DL.getIndexType(Ptr->getType());
883
884
346k
  for (unsigned i = 1, e = Ops.size(); i != e; ++i)
885
229k
    if (!isa<ConstantInt>(Ops[i]))
886
13.6k
      return nullptr;
887
888
117k
  unsigned BitWidth = DL.getTypeSizeInBits(IntIdxTy);
889
117k
  APInt Offset = APInt(
890
117k
      BitWidth,
891
117k
      DL.getIndexedOffsetInType(
892
117k
          SrcElemTy, ArrayRef((Value *const *)Ops.data() + 1, Ops.size() - 1)));
893
894
  // If this is a GEP of a GEP, fold it all into a single GEP.
895
134k
  while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
896
18.5k
    InnermostGEP = GEP;
897
18.5k
    InBounds &= GEP->isInBounds();
898
899
18.5k
    SmallVector<Value *, 4> NestedOps(llvm::drop_begin(GEP->operands()));
900
901
    // Do not try the incorporate the sub-GEP if some index is not a number.
902
18.5k
    bool AllConstantInt = true;
903
18.5k
    for (Value *NestedOp : NestedOps)
904
38.8k
      if (!isa<ConstantInt>(NestedOp)) {
905
1.47k
        AllConstantInt = false;
906
1.47k
        break;
907
1.47k
      }
908
18.5k
    if (!AllConstantInt)
909
1.47k
      break;
910
911
17.0k
    Ptr = cast<Constant>(GEP->getOperand(0));
912
17.0k
    SrcElemTy = GEP->getSourceElementType();
913
17.0k
    Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
914
17.0k
  }
915
916
  // If the base value for this address is a literal integer value, fold the
917
  // getelementptr to the resulting integer value casted to the pointer type.
918
117k
  APInt BasePtr(BitWidth, 0);
919
117k
  if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
920
11.1k
    if (CE->getOpcode() == Instruction::IntToPtr) {
921
9.63k
      if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
922
9.63k
        BasePtr = Base->getValue().zextOrTrunc(BitWidth);
923
9.63k
    }
924
11.1k
  }
925
926
117k
  auto *PTy = cast<PointerType>(Ptr->getType());
927
117k
  if ((Ptr->isNullValue() || BasePtr != 0) &&
928
117k
      !DL.isNonIntegralPointerType(PTy)) {
929
20.9k
    Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
930
20.9k
    return ConstantExpr::getIntToPtr(C, ResTy);
931
20.9k
  }
932
933
  // Otherwise form a regular getelementptr. Recompute the indices so that
934
  // we eliminate over-indexing of the notional static type array bounds.
935
  // This makes it easy to determine if the getelementptr is "inbounds".
936
937
  // For GEPs of GlobalValues, use the value type, otherwise use an i8 GEP.
938
96.1k
  if (auto *GV = dyn_cast<GlobalValue>(Ptr))
939
93.9k
    SrcElemTy = GV->getValueType();
940
2.18k
  else
941
2.18k
    SrcElemTy = Type::getInt8Ty(Ptr->getContext());
942
943
96.1k
  if (!SrcElemTy->isSized())
944
137
    return nullptr;
945
946
96.0k
  Type *ElemTy = SrcElemTy;
947
96.0k
  SmallVector<APInt> Indices = DL.getGEPIndicesForOffset(ElemTy, Offset);
948
96.0k
  if (Offset != 0)
949
3.43k
    return nullptr;
950
951
  // Try to add additional zero indices to reach the desired result element
952
  // type.
953
  // TODO: Should we avoid extra zero indices if ResElemTy can't be reached and
954
  // we'll have to insert a bitcast anyway?
955
97.4k
  while (ElemTy != ResElemTy) {
956
9.56k
    Type *NextTy = GetElementPtrInst::getTypeAtIndex(ElemTy, (uint64_t)0);
957
9.56k
    if (!NextTy)
958
4.74k
      break;
959
960
4.81k
    Indices.push_back(APInt::getZero(isa<StructType>(ElemTy) ? 32 : BitWidth));
961
4.81k
    ElemTy = NextTy;
962
4.81k
  }
963
964
92.6k
  SmallVector<Constant *, 32> NewIdxs;
965
92.6k
  for (const APInt &Index : Indices)
966
197k
    NewIdxs.push_back(ConstantInt::get(
967
197k
        Type::getIntNTy(Ptr->getContext(), Index.getBitWidth()), Index));
968
969
  // Preserve the inrange index from the innermost GEP if possible. We must
970
  // have calculated the same indices up to and including the inrange index.
971
92.6k
  std::optional<unsigned> InRangeIndex;
972
92.6k
  if (std::optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
973
4
    if (SrcElemTy == InnermostGEP->getSourceElementType() &&
974
4
        NewIdxs.size() > *LastIRIndex) {
975
4
      InRangeIndex = LastIRIndex;
976
4
      for (unsigned I = 0; I <= *LastIRIndex; ++I)
977
4
        if (NewIdxs[I] != InnermostGEP->getOperand(I + 1))
978
4
          return nullptr;
979
4
    }
980
981
  // Create a GEP.
982
92.5k
  return ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs, InBounds,
983
92.5k
                                        InRangeIndex);
984
92.6k
}
985
986
/// Attempt to constant fold an instruction with the
987
/// specified opcode and operands.  If successful, the constant result is
988
/// returned, if not, null is returned.  Note that this function can fail when
989
/// attempting to fold instructions like loads and stores, which have no
990
/// constant expression form.
991
Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
992
                                       ArrayRef<Constant *> Ops,
993
                                       const DataLayout &DL,
994
1.66M
                                       const TargetLibraryInfo *TLI) {
995
1.66M
  Type *DestTy = InstOrCE->getType();
996
997
1.66M
  if (Instruction::isUnaryOp(Opcode))
998
37
    return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL);
999
1000
1.66M
  if (Instruction::isBinaryOp(Opcode)) {
1001
845k
    switch (Opcode) {
1002
704k
    default:
1003
704k
      break;
1004
704k
    case Instruction::FAdd:
1005
65.3k
    case Instruction::FSub:
1006
92.5k
    case Instruction::FMul:
1007
117k
    case Instruction::FDiv:
1008
140k
    case Instruction::FRem:
1009
      // Handle floating point instructions separately to account for denormals
1010
      // TODO: If a constant expression is being folded rather than an
1011
      // instruction, denormals will not be flushed/treated as zero
1012
140k
      if (const auto *I = dyn_cast<Instruction>(InstOrCE)) {
1013
140k
        return ConstantFoldFPInstOperands(Opcode, Ops[0], Ops[1], DL, I);
1014
140k
      }
1015
845k
    }
1016
704k
    return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1017
845k
  }
1018
1019
823k
  if (Instruction::isCast(Opcode))
1020
81.8k
    return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1021
1022
742k
  if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
1023
159k
    Type *SrcElemTy = GEP->getSourceElementType();
1024
159k
    if (!ConstantExpr::isSupportedGetElementPtr(SrcElemTy))
1025
0
      return nullptr;
1026
1027
159k
    if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1028
142k
      return C;
1029
1030
17.1k
    return ConstantExpr::getGetElementPtr(SrcElemTy, Ops[0], Ops.slice(1),
1031
17.1k
                                          GEP->isInBounds(),
1032
17.1k
                                          GEP->getInRangeIndex());
1033
159k
  }
1034
1035
582k
  if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE)) {
1036
6.53k
    if (CE->isCompare())
1037
3.17k
      return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1038
3.17k
                                             DL, TLI);
1039
3.35k
    return CE->getWithOperands(Ops);
1040
6.53k
  }
1041
1042
575k
  switch (Opcode) {
1043
241k
  default: return nullptr;
1044
215k
  case Instruction::ICmp:
1045
278k
  case Instruction::FCmp: {
1046
278k
    auto *C = cast<CmpInst>(InstOrCE);
1047
278k
    return ConstantFoldCompareInstOperands(C->getPredicate(), Ops[0], Ops[1],
1048
278k
                                           DL, TLI, C);
1049
215k
  }
1050
385
  case Instruction::Freeze:
1051
385
    return isGuaranteedNotToBeUndefOrPoison(Ops[0]) ? Ops[0] : nullptr;
1052
19.3k
  case Instruction::Call:
1053
19.3k
    if (auto *F = dyn_cast<Function>(Ops.back())) {
1054
19.3k
      const auto *Call = cast<CallBase>(InstOrCE);
1055
19.3k
      if (canConstantFoldCallTo(Call, F))
1056
12.2k
        return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI);
1057
19.3k
    }
1058
7.13k
    return nullptr;
1059
3.68k
  case Instruction::Select:
1060
3.68k
    return ConstantFoldSelectInstruction(Ops[0], Ops[1], Ops[2]);
1061
407
  case Instruction::ExtractElement:
1062
407
    return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1063
559
  case Instruction::ExtractValue:
1064
559
    return ConstantFoldExtractValueInstruction(
1065
559
        Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices());
1066
1.03k
  case Instruction::InsertElement:
1067
1.03k
    return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1068
477
  case Instruction::InsertValue:
1069
477
    return ConstantFoldInsertValueInstruction(
1070
477
        Ops[0], Ops[1], cast<InsertValueInst>(InstOrCE)->getIndices());
1071
452
  case Instruction::ShuffleVector:
1072
452
    return ConstantExpr::getShuffleVector(
1073
452
        Ops[0], Ops[1], cast<ShuffleVectorInst>(InstOrCE)->getShuffleMask());
1074
29.2k
  case Instruction::Load: {
1075
29.2k
    const auto *LI = dyn_cast<LoadInst>(InstOrCE);
1076
29.2k
    if (LI->isVolatile())
1077
10
      return nullptr;
1078
29.1k
    return ConstantFoldLoadFromConstPtr(Ops[0], LI->getType(), DL);
1079
29.2k
  }
1080
575k
  }
1081
575k
}
1082
1083
} // end anonymous namespace
1084
1085
//===----------------------------------------------------------------------===//
1086
// Constant Folding public APIs
1087
//===----------------------------------------------------------------------===//
1088
1089
namespace {
1090
1091
Constant *
1092
ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1093
                         const TargetLibraryInfo *TLI,
1094
329k
                         SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1095
329k
  if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1096
179k
    return const_cast<Constant *>(C);
1097
1098
149k
  SmallVector<Constant *, 8> Ops;
1099
420k
  for (const Use &OldU : C->operands()) {
1100
420k
    Constant *OldC = cast<Constant>(&OldU);
1101
420k
    Constant *NewC = OldC;
1102
    // Recursively fold the ConstantExpr's operands. If we have already folded
1103
    // a ConstantExpr, we don't have to process it again.
1104
420k
    if (isa<ConstantVector>(OldC) || isa<ConstantExpr>(OldC)) {
1105
49.0k
      auto It = FoldedOps.find(OldC);
1106
49.0k
      if (It == FoldedOps.end()) {
1107
38.4k
        NewC = ConstantFoldConstantImpl(OldC, DL, TLI, FoldedOps);
1108
38.4k
        FoldedOps.insert({OldC, NewC});
1109
38.4k
      } else {
1110
10.6k
        NewC = It->second;
1111
10.6k
      }
1112
49.0k
    }
1113
420k
    Ops.push_back(NewC);
1114
420k
  }
1115
1116
149k
  if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1117
137k
    if (Constant *Res =
1118
137k
            ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI))
1119
137k
      return Res;
1120
0
    return const_cast<Constant *>(C);
1121
137k
  }
1122
1123
11.6k
  assert(isa<ConstantVector>(C));
1124
0
  return ConstantVector::get(Ops);
1125
149k
}
1126
1127
} // end anonymous namespace
1128
1129
Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
1130
147k
                                        const TargetLibraryInfo *TLI) {
1131
  // Handle PHI nodes quickly here...
1132
147k
  if (auto *PN = dyn_cast<PHINode>(I)) {
1133
1.63k
    Constant *CommonValue = nullptr;
1134
1135
1.63k
    SmallDenseMap<Constant *, Constant *> FoldedOps;
1136
3.40k
    for (Value *Incoming : PN->incoming_values()) {
1137
      // If the incoming value is undef then skip it.  Note that while we could
1138
      // skip the value if it is equal to the phi node itself we choose not to
1139
      // because that would break the rule that constant folding only applies if
1140
      // all operands are constants.
1141
3.40k
      if (isa<UndefValue>(Incoming))
1142
750
        continue;
1143
      // If the incoming value is not a constant, then give up.
1144
2.65k
      auto *C = dyn_cast<Constant>(Incoming);
1145
2.65k
      if (!C)
1146
1.17k
        return nullptr;
1147
      // Fold the PHI's operands.
1148
1.47k
      C = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1149
      // If the incoming value is a different constant to
1150
      // the one we saw previously, then give up.
1151
1.47k
      if (CommonValue && C != CommonValue)
1152
318
        return nullptr;
1153
1.15k
      CommonValue = C;
1154
1.15k
    }
1155
1156
    // If we reach here, all incoming values are the same constant or undef.
1157
139
    return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1158
1.63k
  }
1159
1160
  // Scan the operand list, checking to see if they are all constants, if so,
1161
  // hand off to ConstantFoldInstOperandsImpl.
1162
248k
  if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1163
35.6k
    return nullptr;
1164
1165
110k
  SmallDenseMap<Constant *, Constant *> FoldedOps;
1166
110k
  SmallVector<Constant *, 8> Ops;
1167
176k
  for (const Use &OpU : I->operands()) {
1168
176k
    auto *Op = cast<Constant>(&OpU);
1169
    // Fold the Instruction's operands.
1170
176k
    Op = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps);
1171
176k
    Ops.push_back(Op);
1172
176k
  }
1173
1174
110k
  return ConstantFoldInstOperands(I, Ops, DL, TLI);
1175
146k
}
1176
1177
Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1178
112k
                                     const TargetLibraryInfo *TLI) {
1179
112k
  SmallDenseMap<Constant *, Constant *> FoldedOps;
1180
112k
  return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1181
112k
}
1182
1183
Constant *llvm::ConstantFoldInstOperands(Instruction *I,
1184
                                         ArrayRef<Constant *> Ops,
1185
                                         const DataLayout &DL,
1186
1.53M
                                         const TargetLibraryInfo *TLI) {
1187
1.53M
  return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
1188
1.53M
}
1189
1190
Constant *llvm::ConstantFoldCompareInstOperands(
1191
    unsigned IntPredicate, Constant *Ops0, Constant *Ops1, const DataLayout &DL,
1192
370k
    const TargetLibraryInfo *TLI, const Instruction *I) {
1193
370k
  CmpInst::Predicate Predicate = (CmpInst::Predicate)IntPredicate;
1194
  // fold: icmp (inttoptr x), null         -> icmp x, 0
1195
  // fold: icmp null, (inttoptr x)         -> icmp 0, x
1196
  // fold: icmp (ptrtoint x), 0            -> icmp x, null
1197
  // fold: icmp 0, (ptrtoint x)            -> icmp null, x
1198
  // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1199
  // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1200
  //
1201
  // FIXME: The following comment is out of data and the DataLayout is here now.
1202
  // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1203
  // around to know if bit truncation is happening.
1204
370k
  if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1205
19.8k
    if (Ops1->isNullValue()) {
1206
2.38k
      if (CE0->getOpcode() == Instruction::IntToPtr) {
1207
119
        Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1208
        // Convert the integer value to the right size to ensure we get the
1209
        // proper extension or truncation.
1210
119
        if (Constant *C = ConstantFoldIntegerCast(CE0->getOperand(0), IntPtrTy,
1211
119
                                                  /*IsSigned*/ false, DL)) {
1212
116
          Constant *Null = Constant::getNullValue(C->getType());
1213
116
          return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1214
116
        }
1215
119
      }
1216
1217
      // Only do this transformation if the int is intptrty in size, otherwise
1218
      // there is a truncation or extension that we aren't modeling.
1219
2.26k
      if (CE0->getOpcode() == Instruction::PtrToInt) {
1220
460
        Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1221
460
        if (CE0->getType() == IntPtrTy) {
1222
39
          Constant *C = CE0->getOperand(0);
1223
39
          Constant *Null = Constant::getNullValue(C->getType());
1224
39
          return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1225
39
        }
1226
460
      }
1227
2.26k
    }
1228
1229
19.6k
    if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1230
13.2k
      if (CE0->getOpcode() == CE1->getOpcode()) {
1231
11.5k
        if (CE0->getOpcode() == Instruction::IntToPtr) {
1232
2.67k
          Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1233
1234
          // Convert the integer value to the right size to ensure we get the
1235
          // proper extension or truncation.
1236
2.67k
          Constant *C0 = ConstantFoldIntegerCast(CE0->getOperand(0), IntPtrTy,
1237
2.67k
                                                 /*IsSigned*/ false, DL);
1238
2.67k
          Constant *C1 = ConstantFoldIntegerCast(CE1->getOperand(0), IntPtrTy,
1239
2.67k
                                                 /*IsSigned*/ false, DL);
1240
2.67k
          if (C0 && C1)
1241
2.67k
            return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1242
2.67k
        }
1243
1244
        // Only do this transformation if the int is intptrty in size, otherwise
1245
        // there is a truncation or extension that we aren't modeling.
1246
8.83k
        if (CE0->getOpcode() == Instruction::PtrToInt) {
1247
419
          Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1248
419
          if (CE0->getType() == IntPtrTy &&
1249
419
              CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1250
67
            return ConstantFoldCompareInstOperands(
1251
67
                Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1252
67
          }
1253
419
        }
1254
8.83k
      }
1255
13.2k
    }
1256
1257
    // Convert pointer comparison (base+offset1) pred (base+offset2) into
1258
    // offset1 pred offset2, for the case where the offset is inbounds. This
1259
    // only works for equality and unsigned comparison, as inbounds permits
1260
    // crossing the sign boundary. However, the offset comparison itself is
1261
    // signed.
1262
16.9k
    if (Ops0->getType()->isPointerTy() && !ICmpInst::isSigned(Predicate)) {
1263
6.01k
      unsigned IndexWidth = DL.getIndexTypeSizeInBits(Ops0->getType());
1264
6.01k
      APInt Offset0(IndexWidth, 0);
1265
6.01k
      Value *Stripped0 =
1266
6.01k
          Ops0->stripAndAccumulateInBoundsConstantOffsets(DL, Offset0);
1267
6.01k
      APInt Offset1(IndexWidth, 0);
1268
6.01k
      Value *Stripped1 =
1269
6.01k
          Ops1->stripAndAccumulateInBoundsConstantOffsets(DL, Offset1);
1270
6.01k
      if (Stripped0 == Stripped1)
1271
223
        return ConstantExpr::getCompare(
1272
223
            ICmpInst::getSignedPredicate(Predicate),
1273
223
            ConstantInt::get(CE0->getContext(), Offset0),
1274
223
            ConstantInt::get(CE0->getContext(), Offset1));
1275
6.01k
    }
1276
351k
  } else if (isa<ConstantExpr>(Ops1)) {
1277
    // If RHS is a constant expression, but the left side isn't, swap the
1278
    // operands and try again.
1279
2.33k
    Predicate = ICmpInst::getSwappedPredicate(Predicate);
1280
2.33k
    return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
1281
2.33k
  }
1282
1283
  // Flush any denormal constant float input according to denormal handling
1284
  // mode.
1285
365k
  Ops0 = FlushFPConstant(Ops0, I, /* IsOutput */ false);
1286
365k
  if (!Ops0)
1287
0
    return nullptr;
1288
365k
  Ops1 = FlushFPConstant(Ops1, I, /* IsOutput */ false);
1289
365k
  if (!Ops1)
1290
0
    return nullptr;
1291
1292
365k
  return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1293
365k
}
1294
1295
Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op,
1296
748
                                           const DataLayout &DL) {
1297
748
  assert(Instruction::isUnaryOp(Opcode));
1298
1299
0
  return ConstantFoldUnaryInstruction(Opcode, Op);
1300
748
}
1301
1302
Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1303
                                             Constant *RHS,
1304
1.38M
                                             const DataLayout &DL) {
1305
1.38M
  assert(Instruction::isBinaryOp(Opcode));
1306
1.38M
  if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1307
26.0k
    if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1308
2.40k
      return C;
1309
1310
1.38M
  if (ConstantExpr::isDesirableBinOp(Opcode))
1311
974k
    return ConstantExpr::get(Opcode, LHS, RHS);
1312
405k
  return ConstantFoldBinaryInstruction(Opcode, LHS, RHS);
1313
1.38M
}
1314
1315
Constant *llvm::FlushFPConstant(Constant *Operand, const Instruction *I,
1316
1.19M
                                bool IsOutput) {
1317
1.19M
  if (!I || !I->getParent() || !I->getFunction())
1318
145k
    return Operand;
1319
1320
1.05M
  ConstantFP *CFP = dyn_cast<ConstantFP>(Operand);
1321
1.05M
  if (!CFP)
1322
429k
    return Operand;
1323
1324
621k
  const APFloat &APF = CFP->getValueAPF();
1325
  // TODO: Should this canonicalize nans?
1326
621k
  if (!APF.isDenormal())
1327
390k
    return Operand;
1328
1329
230k
  Type *Ty = CFP->getType();
1330
230k
  DenormalMode DenormMode =
1331
230k
      I->getFunction()->getDenormalMode(Ty->getFltSemantics());
1332
230k
  DenormalMode::DenormalModeKind Mode =
1333
230k
      IsOutput ? DenormMode.Output : DenormMode.Input;
1334
230k
  switch (Mode) {
1335
0
  default:
1336
0
    llvm_unreachable("unknown denormal mode");
1337
0
  case DenormalMode::Dynamic:
1338
0
    return nullptr;
1339
230k
  case DenormalMode::IEEE:
1340
230k
    return Operand;
1341
0
  case DenormalMode::PreserveSign:
1342
0
    if (APF.isDenormal()) {
1343
0
      return ConstantFP::get(
1344
0
          Ty->getContext(),
1345
0
          APFloat::getZero(Ty->getFltSemantics(), APF.isNegative()));
1346
0
    }
1347
0
    return Operand;
1348
0
  case DenormalMode::PositiveZero:
1349
0
    if (APF.isDenormal()) {
1350
0
      return ConstantFP::get(Ty->getContext(),
1351
0
                             APFloat::getZero(Ty->getFltSemantics(), false));
1352
0
    }
1353
0
    return Operand;
1354
230k
  }
1355
0
  return Operand;
1356
230k
}
1357
1358
Constant *llvm::ConstantFoldFPInstOperands(unsigned Opcode, Constant *LHS,
1359
                                           Constant *RHS, const DataLayout &DL,
1360
155k
                                           const Instruction *I) {
1361
155k
  if (Instruction::isBinaryOp(Opcode)) {
1362
    // Flush denormal inputs if needed.
1363
155k
    Constant *Op0 = FlushFPConstant(LHS, I, /* IsOutput */ false);
1364
155k
    if (!Op0)
1365
0
      return nullptr;
1366
155k
    Constant *Op1 = FlushFPConstant(RHS, I, /* IsOutput */ false);
1367
155k
    if (!Op1)
1368
0
      return nullptr;
1369
1370
    // Calculate constant result.
1371
155k
    Constant *C = ConstantFoldBinaryOpOperands(Opcode, Op0, Op1, DL);
1372
155k
    if (!C)
1373
381
      return nullptr;
1374
1375
    // Flush denormal output if needed.
1376
155k
    return FlushFPConstant(C, I, /* IsOutput */ true);
1377
155k
  }
1378
  // If instruction lacks a parent/function and the denormal mode cannot be
1379
  // determined, use the default (IEEE).
1380
0
  return ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
1381
155k
}
1382
1383
Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1384
191k
                                        Type *DestTy, const DataLayout &DL) {
1385
191k
  assert(Instruction::isCast(Opcode));
1386
0
  switch (Opcode) {
1387
0
  default:
1388
0
    llvm_unreachable("Missing case");
1389
10.1k
  case Instruction::PtrToInt:
1390
10.1k
    if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1391
3.77k
      Constant *FoldedValue = nullptr;
1392
      // If the input is a inttoptr, eliminate the pair.  This requires knowing
1393
      // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1394
3.77k
      if (CE->getOpcode() == Instruction::IntToPtr) {
1395
        // zext/trunc the inttoptr to pointer size.
1396
253
        FoldedValue = ConstantFoldIntegerCast(CE->getOperand(0),
1397
253
                                              DL.getIntPtrType(CE->getType()),
1398
253
                                              /*IsSigned=*/false, DL);
1399
3.52k
      } else if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
1400
        // If we have GEP, we can perform the following folds:
1401
        // (ptrtoint (gep null, x)) -> x
1402
        // (ptrtoint (gep (gep null, x), y) -> x + y, etc.
1403
3.52k
        unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
1404
3.52k
        APInt BaseOffset(BitWidth, 0);
1405
3.52k
        auto *Base = cast<Constant>(GEP->stripAndAccumulateConstantOffsets(
1406
3.52k
            DL, BaseOffset, /*AllowNonInbounds=*/true));
1407
3.52k
        if (Base->isNullValue()) {
1408
0
          FoldedValue = ConstantInt::get(CE->getContext(), BaseOffset);
1409
3.52k
        } else {
1410
          // ptrtoint (gep i8, Ptr, (sub 0, V)) -> sub (ptrtoint Ptr), V
1411
3.52k
          if (GEP->getNumIndices() == 1 &&
1412
3.52k
              GEP->getSourceElementType()->isIntegerTy(8)) {
1413
723
            auto *Ptr = cast<Constant>(GEP->getPointerOperand());
1414
723
            auto *Sub = dyn_cast<ConstantExpr>(GEP->getOperand(1));
1415
723
            Type *IntIdxTy = DL.getIndexType(Ptr->getType());
1416
723
            if (Sub && Sub->getType() == IntIdxTy &&
1417
723
                Sub->getOpcode() == Instruction::Sub &&
1418
723
                Sub->getOperand(0)->isNullValue())
1419
4
              FoldedValue = ConstantExpr::getSub(
1420
4
                  ConstantExpr::getPtrToInt(Ptr, IntIdxTy), Sub->getOperand(1));
1421
723
          }
1422
3.52k
        }
1423
3.52k
      }
1424
3.77k
      if (FoldedValue) {
1425
        // Do a zext or trunc to get to the ptrtoint dest size.
1426
257
        return ConstantFoldIntegerCast(FoldedValue, DestTy, /*IsSigned=*/false,
1427
257
                                       DL);
1428
257
      }
1429
3.77k
    }
1430
9.87k
    break;
1431
9.87k
  case Instruction::IntToPtr:
1432
    // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1433
    // the int size is >= the ptr size and the address spaces are the same.
1434
    // This requires knowing the width of a pointer, so it can't be done in
1435
    // ConstantExpr::getCast.
1436
9.50k
    if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1437
85
      if (CE->getOpcode() == Instruction::PtrToInt) {
1438
57
        Constant *SrcPtr = CE->getOperand(0);
1439
57
        unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1440
57
        unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1441
1442
57
        if (MidIntSize >= SrcPtrSize) {
1443
14
          unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1444
14
          if (SrcAS == DestTy->getPointerAddressSpace())
1445
14
            return FoldBitCast(CE->getOperand(0), DestTy, DL);
1446
14
        }
1447
57
      }
1448
85
    }
1449
9.49k
    break;
1450
46.4k
  case Instruction::Trunc:
1451
66.6k
  case Instruction::ZExt:
1452
138k
  case Instruction::SExt:
1453
141k
  case Instruction::FPTrunc:
1454
141k
  case Instruction::FPExt:
1455
142k
  case Instruction::UIToFP:
1456
159k
  case Instruction::SIToFP:
1457
159k
  case Instruction::FPToUI:
1458
160k
  case Instruction::FPToSI:
1459
160k
  case Instruction::AddrSpaceCast:
1460
160k
    break;
1461
11.0k
  case Instruction::BitCast:
1462
11.0k
    return FoldBitCast(C, DestTy, DL);
1463
191k
  }
1464
1465
179k
  if (ConstantExpr::isDesirableCastOp(Opcode))
1466
66.1k
    return ConstantExpr::getCast(Opcode, C, DestTy);
1467
113k
  return ConstantFoldCastInstruction(Opcode, C, DestTy);
1468
179k
}
1469
1470
Constant *llvm::ConstantFoldIntegerCast(Constant *C, Type *DestTy,
1471
6.95k
                                        bool IsSigned, const DataLayout &DL) {
1472
6.95k
  Type *SrcTy = C->getType();
1473
6.95k
  if (SrcTy == DestTy)
1474
5.68k
    return C;
1475
1.27k
  if (SrcTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1476
376
    return ConstantFoldCastOperand(Instruction::Trunc, C, DestTy, DL);
1477
898
  if (IsSigned)
1478
43
    return ConstantFoldCastOperand(Instruction::SExt, C, DestTy, DL);
1479
855
  return ConstantFoldCastOperand(Instruction::ZExt, C, DestTy, DL);
1480
898
}
1481
1482
//===----------------------------------------------------------------------===//
1483
//  Constant Folding for Calls
1484
//
1485
1486
159k
bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) {
1487
159k
  if (Call->isNoBuiltin())
1488
222
    return false;
1489
159k
  if (Call->getFunctionType() != F->getFunctionType())
1490
280
    return false;
1491
158k
  switch (F->getIntrinsicID()) {
1492
  // Operations that do not operate floating-point numbers and do not depend on
1493
  // FP environment can be folded even in strictfp functions.
1494
2.51k
  case Intrinsic::bswap:
1495
5.64k
  case Intrinsic::ctpop:
1496
12.1k
  case Intrinsic::ctlz:
1497
14.4k
  case Intrinsic::cttz:
1498
15.6k
  case Intrinsic::fshl:
1499
16.0k
  case Intrinsic::fshr:
1500
16.2k
  case Intrinsic::launder_invariant_group:
1501
16.3k
  case Intrinsic::strip_invariant_group:
1502
17.0k
  case Intrinsic::masked_load:
1503
17.0k
  case Intrinsic::get_active_lane_mask:
1504
18.3k
  case Intrinsic::abs:
1505
21.8k
  case Intrinsic::smax:
1506
25.6k
  case Intrinsic::smin:
1507
28.6k
  case Intrinsic::umax:
1508
31.7k
  case Intrinsic::umin:
1509
32.8k
  case Intrinsic::sadd_with_overflow:
1510
33.4k
  case Intrinsic::uadd_with_overflow:
1511
34.4k
  case Intrinsic::ssub_with_overflow:
1512
34.6k
  case Intrinsic::usub_with_overflow:
1513
34.8k
  case Intrinsic::smul_with_overflow:
1514
35.3k
  case Intrinsic::umul_with_overflow:
1515
37.3k
  case Intrinsic::sadd_sat:
1516
38.7k
  case Intrinsic::uadd_sat:
1517
40.4k
  case Intrinsic::ssub_sat:
1518
41.4k
  case Intrinsic::usub_sat:
1519
41.5k
  case Intrinsic::smul_fix:
1520
41.6k
  case Intrinsic::smul_fix_sat:
1521
42.4k
  case Intrinsic::bitreverse:
1522
42.4k
  case Intrinsic::is_constant:
1523
42.8k
  case Intrinsic::vector_reduce_add:
1524
42.8k
  case Intrinsic::vector_reduce_mul:
1525
42.9k
  case Intrinsic::vector_reduce_and:
1526
43.1k
  case Intrinsic::vector_reduce_or:
1527
43.2k
  case Intrinsic::vector_reduce_xor:
1528
43.4k
  case Intrinsic::vector_reduce_smin:
1529
43.5k
  case Intrinsic::vector_reduce_smax:
1530
43.7k
  case Intrinsic::vector_reduce_umin:
1531
43.8k
  case Intrinsic::vector_reduce_umax:
1532
  // Target intrinsics
1533
43.8k
  case Intrinsic::amdgcn_perm:
1534
43.8k
  case Intrinsic::amdgcn_wave_reduce_umin:
1535
43.8k
  case Intrinsic::amdgcn_wave_reduce_umax:
1536
43.8k
  case Intrinsic::amdgcn_s_wqm:
1537
43.8k
  case Intrinsic::amdgcn_s_quadmask:
1538
43.8k
  case Intrinsic::amdgcn_s_bitreplicate:
1539
43.8k
  case Intrinsic::arm_mve_vctp8:
1540
43.8k
  case Intrinsic::arm_mve_vctp16:
1541
43.8k
  case Intrinsic::arm_mve_vctp32:
1542
43.8k
  case Intrinsic::arm_mve_vctp64:
1543
43.8k
  case Intrinsic::aarch64_sve_convert_from_svbool:
1544
  // WebAssembly float semantics are always known
1545
43.8k
  case Intrinsic::wasm_trunc_signed:
1546
43.8k
  case Intrinsic::wasm_trunc_unsigned:
1547
43.8k
    return true;
1548
1549
  // Floating point operations cannot be folded in strictfp functions in
1550
  // general case. They can be folded if FP environment is known to compiler.
1551
244
  case Intrinsic::minnum:
1552
1.19k
  case Intrinsic::maxnum:
1553
1.55k
  case Intrinsic::minimum:
1554
2.12k
  case Intrinsic::maximum:
1555
2.44k
  case Intrinsic::log:
1556
2.64k
  case Intrinsic::log2:
1557
2.80k
  case Intrinsic::log10:
1558
8.10k
  case Intrinsic::exp:
1559
9.56k
  case Intrinsic::exp2:
1560
9.56k
  case Intrinsic::exp10:
1561
13.6k
  case Intrinsic::sqrt:
1562
17.1k
  case Intrinsic::sin:
1563
17.7k
  case Intrinsic::cos:
1564
19.2k
  case Intrinsic::pow:
1565
19.9k
  case Intrinsic::powi:
1566
20.0k
  case Intrinsic::ldexp:
1567
22.3k
  case Intrinsic::fma:
1568
22.5k
  case Intrinsic::fmuladd:
1569
22.5k
  case Intrinsic::frexp:
1570
22.5k
  case Intrinsic::fptoui_sat:
1571
22.5k
  case Intrinsic::fptosi_sat:
1572
22.5k
  case Intrinsic::convert_from_fp16:
1573
22.5k
  case Intrinsic::convert_to_fp16:
1574
22.5k
  case Intrinsic::amdgcn_cos:
1575
22.5k
  case Intrinsic::amdgcn_cubeid:
1576
22.5k
  case Intrinsic::amdgcn_cubema:
1577
22.5k
  case Intrinsic::amdgcn_cubesc:
1578
22.5k
  case Intrinsic::amdgcn_cubetc:
1579
22.5k
  case Intrinsic::amdgcn_fmul_legacy:
1580
22.5k
  case Intrinsic::amdgcn_fma_legacy:
1581
22.5k
  case Intrinsic::amdgcn_fract:
1582
22.5k
  case Intrinsic::amdgcn_sin:
1583
  // The intrinsics below depend on rounding mode in MXCSR.
1584
22.5k
  case Intrinsic::x86_sse_cvtss2si:
1585
22.6k
  case Intrinsic::x86_sse_cvtss2si64:
1586
22.6k
  case Intrinsic::x86_sse_cvttss2si:
1587
22.6k
  case Intrinsic::x86_sse_cvttss2si64:
1588
22.7k
  case Intrinsic::x86_sse2_cvtsd2si:
1589
22.7k
  case Intrinsic::x86_sse2_cvtsd2si64:
1590
22.7k
  case Intrinsic::x86_sse2_cvttsd2si:
1591
22.7k
  case Intrinsic::x86_sse2_cvttsd2si64:
1592
22.7k
  case Intrinsic::x86_avx512_vcvtss2si32:
1593
22.8k
  case Intrinsic::x86_avx512_vcvtss2si64:
1594
22.8k
  case Intrinsic::x86_avx512_cvttss2si:
1595
22.9k
  case Intrinsic::x86_avx512_cvttss2si64:
1596
22.9k
  case Intrinsic::x86_avx512_vcvtsd2si32:
1597
22.9k
  case Intrinsic::x86_avx512_vcvtsd2si64:
1598
23.0k
  case Intrinsic::x86_avx512_cvttsd2si:
1599
23.0k
  case Intrinsic::x86_avx512_cvttsd2si64:
1600
23.1k
  case Intrinsic::x86_avx512_vcvtss2usi32:
1601
23.1k
  case Intrinsic::x86_avx512_vcvtss2usi64:
1602
23.1k
  case Intrinsic::x86_avx512_cvttss2usi:
1603
23.2k
  case Intrinsic::x86_avx512_cvttss2usi64:
1604
23.2k
  case Intrinsic::x86_avx512_vcvtsd2usi32:
1605
23.2k
  case Intrinsic::x86_avx512_vcvtsd2usi64:
1606
23.2k
  case Intrinsic::x86_avx512_cvttsd2usi:
1607
23.3k
  case Intrinsic::x86_avx512_cvttsd2usi64:
1608
23.3k
    return !Call->isStrictFP();
1609
1610
  // Sign operations are actually bitwise operations, they do not raise
1611
  // exceptions even for SNANs.
1612
1.99k
  case Intrinsic::fabs:
1613
2.76k
  case Intrinsic::copysign:
1614
2.76k
  case Intrinsic::is_fpclass:
1615
  // Non-constrained variants of rounding operations means default FP
1616
  // environment, they can be folded in any case.
1617
3.21k
  case Intrinsic::ceil:
1618
3.47k
  case Intrinsic::floor:
1619
3.62k
  case Intrinsic::round:
1620
3.66k
  case Intrinsic::roundeven:
1621
3.94k
  case Intrinsic::trunc:
1622
4.30k
  case Intrinsic::nearbyint:
1623
4.50k
  case Intrinsic::rint:
1624
4.51k
  case Intrinsic::canonicalize:
1625
  // Constrained intrinsics can be folded if FP environment is known
1626
  // to compiler.
1627
4.51k
  case Intrinsic::experimental_constrained_fma:
1628
4.51k
  case Intrinsic::experimental_constrained_fmuladd:
1629
4.52k
  case Intrinsic::experimental_constrained_fadd:
1630
4.53k
  case Intrinsic::experimental_constrained_fsub:
1631
4.54k
  case Intrinsic::experimental_constrained_fmul:
1632
4.56k
  case Intrinsic::experimental_constrained_fdiv:
1633
4.57k
  case Intrinsic::experimental_constrained_frem:
1634
4.57k
  case Intrinsic::experimental_constrained_ceil:
1635
4.57k
  case Intrinsic::experimental_constrained_floor:
1636
4.57k
  case Intrinsic::experimental_constrained_round:
1637
4.57k
  case Intrinsic::experimental_constrained_roundeven:
1638
4.57k
  case Intrinsic::experimental_constrained_trunc:
1639
4.57k
  case Intrinsic::experimental_constrained_nearbyint:
1640
4.57k
  case Intrinsic::experimental_constrained_rint:
1641
4.58k
  case Intrinsic::experimental_constrained_fcmp:
1642
4.59k
  case Intrinsic::experimental_constrained_fcmps:
1643
4.59k
    return true;
1644
43.9k
  default:
1645
43.9k
    return false;
1646
43.2k
  case Intrinsic::not_intrinsic: break;
1647
158k
  }
1648
1649
43.2k
  if (!F->hasName() || Call->isStrictFP())
1650
121
    return false;
1651
1652
  // In these cases, the check of the length is required.  We don't want to
1653
  // return true for a name like "cos\0blah" which strcmp would return equal to
1654
  // "cos", but has length 8.
1655
43.1k
  StringRef Name = F->getName();
1656
43.1k
  switch (Name[0]) {
1657
11.3k
  default:
1658
11.3k
    return false;
1659
1.31k
  case 'a':
1660
1.31k
    return Name == "acos" || Name == "acosf" ||
1661
1.31k
           Name == "asin" || Name == "asinf" ||
1662
1.31k
           Name == "atan" || Name == "atanf" ||
1663
1.31k
           Name == "atan2" || Name == "atan2f";
1664
5.97k
  case 'c':
1665
5.97k
    return Name == "ceil" || Name == "ceilf" ||
1666
5.97k
           Name == "cos" || Name == "cosf" ||
1667
5.97k
           Name == "cosh" || Name == "coshf";
1668
3.04k
  case 'e':
1669
3.04k
    return Name == "exp" || Name == "expf" ||
1670
3.04k
           Name == "exp2" || Name == "exp2f";
1671
4.82k
  case 'f':
1672
4.82k
    return Name == "fabs" || Name == "fabsf" ||
1673
4.82k
           Name == "floor" || Name == "floorf" ||
1674
4.82k
           Name == "fmod" || Name == "fmodf";
1675
2.81k
  case 'l':
1676
2.81k
    return Name == "log" || Name == "logf" ||
1677
2.81k
           Name == "log2" || Name == "log2f" ||
1678
2.81k
           Name == "log10" || Name == "log10f";
1679
258
  case 'n':
1680
258
    return Name == "nearbyint" || Name == "nearbyintf";
1681
2.02k
  case 'p':
1682
2.02k
    return Name == "pow" || Name == "powf";
1683
220
  case 'r':
1684
220
    return Name == "remainder" || Name == "remainderf" ||
1685
220
           Name == "rint" || Name == "rintf" ||
1686
220
           Name == "round" || Name == "roundf";
1687
7.24k
  case 's':
1688
7.24k
    return Name == "sin" || Name == "sinf" ||
1689
7.24k
           Name == "sinh" || Name == "sinhf" ||
1690
7.24k
           Name == "sqrt" || Name == "sqrtf";
1691
1.16k
  case 't':
1692
1.16k
    return Name == "tan" || Name == "tanf" ||
1693
1.16k
           Name == "tanh" || Name == "tanhf" ||
1694
1.16k
           Name == "trunc" || Name == "truncf";
1695
2.97k
  case '_':
1696
    // Check for various function names that get used for the math functions
1697
    // when the header files are preprocessed with the macro
1698
    // __FINITE_MATH_ONLY__ enabled.
1699
    // The '12' here is the length of the shortest name that can match.
1700
    // We need to check the size before looking at Name[1] and Name[2]
1701
    // so we may as well check a limit that will eliminate mismatches.
1702
2.97k
    if (Name.size() < 12 || Name[1] != '_')
1703
2.19k
      return false;
1704
784
    switch (Name[2]) {
1705
331
    default:
1706
331
      return false;
1707
11
    case 'a':
1708
11
      return Name == "__acos_finite" || Name == "__acosf_finite" ||
1709
11
             Name == "__asin_finite" || Name == "__asinf_finite" ||
1710
11
             Name == "__atan2_finite" || Name == "__atan2f_finite";
1711
27
    case 'c':
1712
27
      return Name == "__cosh_finite" || Name == "__coshf_finite";
1713
77
    case 'e':
1714
77
      return Name == "__exp_finite" || Name == "__expf_finite" ||
1715
77
             Name == "__exp2_finite" || Name == "__exp2f_finite";
1716
82
    case 'l':
1717
82
      return Name == "__log_finite" || Name == "__logf_finite" ||
1718
82
             Name == "__log10_finite" || Name == "__log10f_finite";
1719
52
    case 'p':
1720
52
      return Name == "__pow_finite" || Name == "__powf_finite";
1721
204
    case 's':
1722
204
      return Name == "__sinh_finite" || Name == "__sinhf_finite";
1723
784
    }
1724
43.1k
  }
1725
43.1k
}
1726
1727
namespace {
1728
1729
11.4k
Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1730
11.4k
  if (Ty->isHalfTy() || Ty->isFloatTy()) {
1731
7.31k
    APFloat APF(V);
1732
7.31k
    bool unused;
1733
7.31k
    APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
1734
7.31k
    return ConstantFP::get(Ty->getContext(), APF);
1735
7.31k
  }
1736
4.08k
  if (Ty->isDoubleTy())
1737
4.08k
    return ConstantFP::get(Ty->getContext(), APFloat(V));
1738
0
  llvm_unreachable("Can only constant fold half/float/double");
1739
0
}
1740
1741
/// Clear the floating-point exception state.
1742
12.1k
inline void llvm_fenv_clearexcept() {
1743
12.1k
#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1744
12.1k
  feclearexcept(FE_ALL_EXCEPT);
1745
12.1k
#endif
1746
12.1k
  errno = 0;
1747
12.1k
}
1748
1749
/// Test if a floating-point exception was raised.
1750
11.7k
inline bool llvm_fenv_testexcept() {
1751
11.7k
  int errno_val = errno;
1752
11.7k
  if (errno_val == ERANGE || errno_val == EDOM)
1753
260
    return true;
1754
11.5k
#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1755
11.5k
  if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1756
134
    return true;
1757
11.3k
#endif
1758
11.3k
  return false;
1759
11.5k
}
1760
1761
Constant *ConstantFoldFP(double (*NativeFP)(double), const APFloat &V,
1762
10.3k
                         Type *Ty) {
1763
10.3k
  llvm_fenv_clearexcept();
1764
10.3k
  double Result = NativeFP(V.convertToDouble());
1765
10.3k
  if (llvm_fenv_testexcept()) {
1766
367
    llvm_fenv_clearexcept();
1767
367
    return nullptr;
1768
367
  }
1769
1770
10.0k
  return GetConstantFoldFPValue(Result, Ty);
1771
10.3k
}
1772
1773
Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1774
1.40k
                               const APFloat &V, const APFloat &W, Type *Ty) {
1775
1.40k
  llvm_fenv_clearexcept();
1776
1.40k
  double Result = NativeFP(V.convertToDouble(), W.convertToDouble());
1777
1.40k
  if (llvm_fenv_testexcept()) {
1778
27
    llvm_fenv_clearexcept();
1779
27
    return nullptr;
1780
27
  }
1781
1782
1.38k
  return GetConstantFoldFPValue(Result, Ty);
1783
1.40k
}
1784
1785
103
Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
1786
103
  FixedVectorType *VT = dyn_cast<FixedVectorType>(Op->getType());
1787
103
  if (!VT)
1788
0
    return nullptr;
1789
1790
  // This isn't strictly necessary, but handle the special/common case of zero:
1791
  // all integer reductions of a zero input produce zero.
1792
103
  if (isa<ConstantAggregateZero>(Op))
1793
42
    return ConstantInt::get(VT->getElementType(), 0);
1794
1795
  // This is the same as the underlying binops - poison propagates.
1796
61
  if (isa<PoisonValue>(Op) || Op->containsPoisonElement())
1797
6
    return PoisonValue::get(VT->getElementType());
1798
1799
  // TODO: Handle undef.
1800
55
  if (!isa<ConstantVector>(Op) && !isa<ConstantDataVector>(Op))
1801
51
    return nullptr;
1802
1803
4
  auto *EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(0U));
1804
4
  if (!EltC)
1805
0
    return nullptr;
1806
1807
4
  APInt Acc = EltC->getValue();
1808
140
  for (unsigned I = 1, E = VT->getNumElements(); I != E; I++) {
1809
136
    if (!(EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(I))))
1810
0
      return nullptr;
1811
136
    const APInt &X = EltC->getValue();
1812
136
    switch (IID) {
1813
130
    case Intrinsic::vector_reduce_add:
1814
130
      Acc = Acc + X;
1815
130
      break;
1816
0
    case Intrinsic::vector_reduce_mul:
1817
0
      Acc = Acc * X;
1818
0
      break;
1819
0
    case Intrinsic::vector_reduce_and:
1820
0
      Acc = Acc & X;
1821
0
      break;
1822
3
    case Intrinsic::vector_reduce_or:
1823
3
      Acc = Acc | X;
1824
3
      break;
1825
0
    case Intrinsic::vector_reduce_xor:
1826
0
      Acc = Acc ^ X;
1827
0
      break;
1828
0
    case Intrinsic::vector_reduce_smin:
1829
0
      Acc = APIntOps::smin(Acc, X);
1830
0
      break;
1831
0
    case Intrinsic::vector_reduce_smax:
1832
0
      Acc = APIntOps::smax(Acc, X);
1833
0
      break;
1834
0
    case Intrinsic::vector_reduce_umin:
1835
0
      Acc = APIntOps::umin(Acc, X);
1836
0
      break;
1837
3
    case Intrinsic::vector_reduce_umax:
1838
3
      Acc = APIntOps::umax(Acc, X);
1839
3
      break;
1840
136
    }
1841
136
  }
1842
1843
4
  return ConstantInt::get(Op->getContext(), Acc);
1844
4
}
1845
1846
/// Attempt to fold an SSE floating point to integer conversion of a constant
1847
/// floating point. If roundTowardZero is false, the default IEEE rounding is
1848
/// used (toward nearest, ties to even). This matches the behavior of the
1849
/// non-truncating SSE instructions in the default rounding mode. The desired
1850
/// integer type Ty is used to select how many bits are available for the
1851
/// result. Returns null if the conversion cannot be performed, otherwise
1852
/// returns the Constant value resulting from the conversion.
1853
Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1854
20
                                      Type *Ty, bool IsSigned) {
1855
  // All of these conversion intrinsics form an integer of at most 64bits.
1856
20
  unsigned ResultWidth = Ty->getIntegerBitWidth();
1857
20
  assert(ResultWidth <= 64 &&
1858
20
         "Can only constant fold conversions to 64 and 32 bit ints");
1859
1860
0
  uint64_t UIntVal;
1861
20
  bool isExact = false;
1862
20
  APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1863
20
                                              : APFloat::rmNearestTiesToEven;
1864
20
  APFloat::opStatus status =
1865
20
      Val.convertToInteger(MutableArrayRef(UIntVal), ResultWidth,
1866
20
                           IsSigned, mode, &isExact);
1867
20
  if (status != APFloat::opOK &&
1868
20
      (!roundTowardZero || status != APFloat::opInexact))
1869
16
    return nullptr;
1870
4
  return ConstantInt::get(Ty, UIntVal, IsSigned);
1871
20
}
1872
1873
8
double getValueAsDouble(ConstantFP *Op) {
1874
8
  Type *Ty = Op->getType();
1875
1876
8
  if (Ty->isBFloatTy() || Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())
1877
8
    return Op->getValueAPF().convertToDouble();
1878
1879
0
  bool unused;
1880
0
  APFloat APF = Op->getValueAPF();
1881
0
  APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
1882
0
  return APF.convertToDouble();
1883
8
}
1884
1885
48.6k
static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1886
48.6k
  if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1887
46.7k
    C = &CI->getValue();
1888
46.7k
    return true;
1889
46.7k
  }
1890
1.85k
  if (isa<UndefValue>(Op)) {
1891
1.85k
    C = nullptr;
1892
1.85k
    return true;
1893
1.85k
  }
1894
0
  return false;
1895
1.85k
}
1896
1897
/// Checks if the given intrinsic call, which evaluates to constant, is allowed
1898
/// to be folded.
1899
///
1900
/// \param CI Constrained intrinsic call.
1901
/// \param St Exception flags raised during constant evaluation.
1902
static bool mayFoldConstrained(ConstrainedFPIntrinsic *CI,
1903
0
                               APFloat::opStatus St) {
1904
0
  std::optional<RoundingMode> ORM = CI->getRoundingMode();
1905
0
  std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
1906
1907
  // If the operation does not change exception status flags, it is safe
1908
  // to fold.
1909
0
  if (St == APFloat::opStatus::opOK)
1910
0
    return true;
1911
1912
  // If evaluation raised FP exception, the result can depend on rounding
1913
  // mode. If the latter is unknown, folding is not possible.
1914
0
  if (ORM && *ORM == RoundingMode::Dynamic)
1915
0
    return false;
1916
1917
  // If FP exceptions are ignored, fold the call, even if such exception is
1918
  // raised.
1919
0
  if (EB && *EB != fp::ExceptionBehavior::ebStrict)
1920
0
    return true;
1921
1922
  // Leave the calculation for runtime so that exception flags be correctly set
1923
  // in hardware.
1924
0
  return false;
1925
0
}
1926
1927
/// Returns the rounding mode that should be used for constant evaluation.
1928
static RoundingMode
1929
0
getEvaluationRoundingMode(const ConstrainedFPIntrinsic *CI) {
1930
0
  std::optional<RoundingMode> ORM = CI->getRoundingMode();
1931
0
  if (!ORM || *ORM == RoundingMode::Dynamic)
1932
    // Even if the rounding mode is unknown, try evaluating the operation.
1933
    // If it does not raise inexact exception, rounding was not applied,
1934
    // so the result is exact and does not depend on rounding mode. Whether
1935
    // other FP exceptions are raised, it does not depend on rounding mode.
1936
0
    return RoundingMode::NearestTiesToEven;
1937
0
  return *ORM;
1938
0
}
1939
1940
/// Try to constant fold llvm.canonicalize for the given caller and value.
1941
static Constant *constantFoldCanonicalize(const Type *Ty, const CallBase *CI,
1942
0
                                          const APFloat &Src) {
1943
  // Zero, positive and negative, is always OK to fold.
1944
0
  if (Src.isZero()) {
1945
    // Get a fresh 0, since ppc_fp128 does have non-canonical zeros.
1946
0
    return ConstantFP::get(
1947
0
        CI->getContext(),
1948
0
        APFloat::getZero(Src.getSemantics(), Src.isNegative()));
1949
0
  }
1950
1951
0
  if (!Ty->isIEEELikeFPTy())
1952
0
    return nullptr;
1953
1954
  // Zero is always canonical and the sign must be preserved.
1955
  //
1956
  // Denorms and nans may have special encodings, but it should be OK to fold a
1957
  // totally average number.
1958
0
  if (Src.isNormal() || Src.isInfinity())
1959
0
    return ConstantFP::get(CI->getContext(), Src);
1960
1961
0
  if (Src.isDenormal() && CI->getParent() && CI->getFunction()) {
1962
0
    DenormalMode DenormMode =
1963
0
        CI->getFunction()->getDenormalMode(Src.getSemantics());
1964
1965
0
    if (DenormMode == DenormalMode::getIEEE())
1966
0
      return ConstantFP::get(CI->getContext(), Src);
1967
1968
0
    if (DenormMode.Input == DenormalMode::Dynamic)
1969
0
      return nullptr;
1970
1971
    // If we know if either input or output is flushed, we can fold.
1972
0
    if ((DenormMode.Input == DenormalMode::Dynamic &&
1973
0
         DenormMode.Output == DenormalMode::IEEE) ||
1974
0
        (DenormMode.Input == DenormalMode::IEEE &&
1975
0
         DenormMode.Output == DenormalMode::Dynamic))
1976
0
      return nullptr;
1977
1978
0
    bool IsPositive =
1979
0
        (!Src.isNegative() || DenormMode.Input == DenormalMode::PositiveZero ||
1980
0
         (DenormMode.Output == DenormalMode::PositiveZero &&
1981
0
          DenormMode.Input == DenormalMode::IEEE));
1982
1983
0
    return ConstantFP::get(CI->getContext(),
1984
0
                           APFloat::getZero(Src.getSemantics(), !IsPositive));
1985
0
  }
1986
1987
0
  return nullptr;
1988
0
}
1989
1990
static Constant *ConstantFoldScalarCall1(StringRef Name,
1991
                                         Intrinsic::ID IntrinsicID,
1992
                                         Type *Ty,
1993
                                         ArrayRef<Constant *> Operands,
1994
                                         const TargetLibraryInfo *TLI,
1995
14.6k
                                         const CallBase *Call) {
1996
14.6k
  assert(Operands.size() == 1 && "Wrong number of operands.");
1997
1998
14.6k
  if (IntrinsicID == Intrinsic::is_constant) {
1999
    // We know we have a "Constant" argument. But we want to only
2000
    // return true for manifest constants, not those that depend on
2001
    // constants with unknowable values, e.g. GlobalValue or BlockAddress.
2002
0
    if (Operands[0]->isManifestConstant())
2003
0
      return ConstantInt::getTrue(Ty->getContext());
2004
0
    return nullptr;
2005
0
  }
2006
2007
14.6k
  if (isa<PoisonValue>(Operands[0])) {
2008
    // TODO: All of these operations should probably propagate poison.
2009
105
    if (IntrinsicID == Intrinsic::canonicalize)
2010
0
      return PoisonValue::get(Ty);
2011
105
  }
2012
2013
14.6k
  if (isa<UndefValue>(Operands[0])) {
2014
    // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
2015
    // ctpop() is between 0 and bitwidth, pick 0 for undef.
2016
    // fptoui.sat and fptosi.sat can always fold to zero (for a zero input).
2017
257
    if (IntrinsicID == Intrinsic::cos ||
2018
257
        IntrinsicID == Intrinsic::ctpop ||
2019
257
        IntrinsicID == Intrinsic::fptoui_sat ||
2020
257
        IntrinsicID == Intrinsic::fptosi_sat ||
2021
257
        IntrinsicID == Intrinsic::canonicalize)
2022
47
      return Constant::getNullValue(Ty);
2023
210
    if (IntrinsicID == Intrinsic::bswap ||
2024
210
        IntrinsicID == Intrinsic::bitreverse ||
2025
210
        IntrinsicID == Intrinsic::launder_invariant_group ||
2026
210
        IntrinsicID == Intrinsic::strip_invariant_group)
2027
84
      return Operands[0];
2028
210
  }
2029
2030
14.5k
  if (isa<ConstantPointerNull>(Operands[0])) {
2031
    // launder(null) == null == strip(null) iff in addrspace 0
2032
68
    if (IntrinsicID == Intrinsic::launder_invariant_group ||
2033
68
        IntrinsicID == Intrinsic::strip_invariant_group) {
2034
      // If instruction is not yet put in a basic block (e.g. when cloning
2035
      // a function during inlining), Call's caller may not be available.
2036
      // So check Call's BB first before querying Call->getCaller.
2037
68
      const Function *Caller =
2038
68
          Call->getParent() ? Call->getCaller() : nullptr;
2039
68
      if (Caller &&
2040
68
          !NullPointerIsDefined(
2041
68
              Caller, Operands[0]->getType()->getPointerAddressSpace())) {
2042
17
        return Operands[0];
2043
17
      }
2044
51
      return nullptr;
2045
68
    }
2046
68
  }
2047
2048
14.4k
  if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
2049
13.9k
    if (IntrinsicID == Intrinsic::convert_to_fp16) {
2050
0
      APFloat Val(Op->getValueAPF());
2051
2052
0
      bool lost = false;
2053
0
      Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
2054
2055
0
      return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
2056
0
    }
2057
2058
13.9k
    APFloat U = Op->getValueAPF();
2059
2060
13.9k
    if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
2061
13.9k
        IntrinsicID == Intrinsic::wasm_trunc_unsigned) {
2062
0
      bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed;
2063
2064
0
      if (U.isNaN())
2065
0
        return nullptr;
2066
2067
0
      unsigned Width = Ty->getIntegerBitWidth();
2068
0
      APSInt Int(Width, !Signed);
2069
0
      bool IsExact = false;
2070
0
      APFloat::opStatus Status =
2071
0
          U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2072
2073
0
      if (Status == APFloat::opOK || Status == APFloat::opInexact)
2074
0
        return ConstantInt::get(Ty, Int);
2075
2076
0
      return nullptr;
2077
0
    }
2078
2079
13.9k
    if (IntrinsicID == Intrinsic::fptoui_sat ||
2080
13.9k
        IntrinsicID == Intrinsic::fptosi_sat) {
2081
      // convertToInteger() already has the desired saturation semantics.
2082
0
      APSInt Int(Ty->getIntegerBitWidth(),
2083
0
                 IntrinsicID == Intrinsic::fptoui_sat);
2084
0
      bool IsExact;
2085
0
      U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
2086
0
      return ConstantInt::get(Ty, Int);
2087
0
    }
2088
2089
13.9k
    if (IntrinsicID == Intrinsic::canonicalize)
2090
0
      return constantFoldCanonicalize(Ty, Call, U);
2091
2092
13.9k
    if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2093
0
      return nullptr;
2094
2095
    // Use internal versions of these intrinsics.
2096
2097
13.9k
    if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) {
2098
339
      U.roundToIntegral(APFloat::rmNearestTiesToEven);
2099
339
      return ConstantFP::get(Ty->getContext(), U);
2100
339
    }
2101
2102
13.5k
    if (IntrinsicID == Intrinsic::round) {
2103
18
      U.roundToIntegral(APFloat::rmNearestTiesToAway);
2104
18
      return ConstantFP::get(Ty->getContext(), U);
2105
18
    }
2106
2107
13.5k
    if (IntrinsicID == Intrinsic::roundeven) {
2108
2
      U.roundToIntegral(APFloat::rmNearestTiesToEven);
2109
2
      return ConstantFP::get(Ty->getContext(), U);
2110
2
    }
2111
2112
13.5k
    if (IntrinsicID == Intrinsic::ceil) {
2113
302
      U.roundToIntegral(APFloat::rmTowardPositive);
2114
302
      return ConstantFP::get(Ty->getContext(), U);
2115
302
    }
2116
2117
13.2k
    if (IntrinsicID == Intrinsic::floor) {
2118
73
      U.roundToIntegral(APFloat::rmTowardNegative);
2119
73
      return ConstantFP::get(Ty->getContext(), U);
2120
73
    }
2121
2122
13.1k
    if (IntrinsicID == Intrinsic::trunc) {
2123
138
      U.roundToIntegral(APFloat::rmTowardZero);
2124
138
      return ConstantFP::get(Ty->getContext(), U);
2125
138
    }
2126
2127
13.0k
    if (IntrinsicID == Intrinsic::fabs) {
2128
88
      U.clearSign();
2129
88
      return ConstantFP::get(Ty->getContext(), U);
2130
88
    }
2131
2132
12.9k
    if (IntrinsicID == Intrinsic::amdgcn_fract) {
2133
      // The v_fract instruction behaves like the OpenCL spec, which defines
2134
      // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
2135
      //   there to prevent fract(-small) from returning 1.0. It returns the
2136
      //   largest positive floating-point number less than 1.0."
2137
0
      APFloat FloorU(U);
2138
0
      FloorU.roundToIntegral(APFloat::rmTowardNegative);
2139
0
      APFloat FractU(U - FloorU);
2140
0
      APFloat AlmostOne(U.getSemantics(), 1);
2141
0
      AlmostOne.next(/*nextDown*/ true);
2142
0
      return ConstantFP::get(Ty->getContext(), minimum(FractU, AlmostOne));
2143
0
    }
2144
2145
    // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
2146
    // raise FP exceptions, unless the argument is signaling NaN.
2147
2148
12.9k
    std::optional<APFloat::roundingMode> RM;
2149
12.9k
    switch (IntrinsicID) {
2150
12.9k
    default:
2151
12.9k
      break;
2152
12.9k
    case Intrinsic::experimental_constrained_nearbyint:
2153
0
    case Intrinsic::experimental_constrained_rint: {
2154
0
      auto CI = cast<ConstrainedFPIntrinsic>(Call);
2155
0
      RM = CI->getRoundingMode();
2156
0
      if (!RM || *RM == RoundingMode::Dynamic)
2157
0
        return nullptr;
2158
0
      break;
2159
0
    }
2160
0
    case Intrinsic::experimental_constrained_round:
2161
0
      RM = APFloat::rmNearestTiesToAway;
2162
0
      break;
2163
0
    case Intrinsic::experimental_constrained_ceil:
2164
0
      RM = APFloat::rmTowardPositive;
2165
0
      break;
2166
0
    case Intrinsic::experimental_constrained_floor:
2167
0
      RM = APFloat::rmTowardNegative;
2168
0
      break;
2169
0
    case Intrinsic::experimental_constrained_trunc:
2170
0
      RM = APFloat::rmTowardZero;
2171
0
      break;
2172
12.9k
    }
2173
12.9k
    if (RM) {
2174
0
      auto CI = cast<ConstrainedFPIntrinsic>(Call);
2175
0
      if (U.isFinite()) {
2176
0
        APFloat::opStatus St = U.roundToIntegral(*RM);
2177
0
        if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
2178
0
            St == APFloat::opInexact) {
2179
0
          std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2180
0
          if (EB && *EB == fp::ebStrict)
2181
0
            return nullptr;
2182
0
        }
2183
0
      } else if (U.isSignaling()) {
2184
0
        std::optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2185
0
        if (EB && *EB != fp::ebIgnore)
2186
0
          return nullptr;
2187
0
        U = APFloat::getQNaN(U.getSemantics());
2188
0
      }
2189
0
      return ConstantFP::get(Ty->getContext(), U);
2190
0
    }
2191
2192
    /// We only fold functions with finite arguments. Folding NaN and inf is
2193
    /// likely to be aborted with an exception anyway, and some host libms
2194
    /// have known errors raising exceptions.
2195
12.9k
    if (!U.isFinite())
2196
86
      return nullptr;
2197
2198
    /// Currently APFloat versions of these functions do not exist, so we use
2199
    /// the host native double versions.  Float versions are not called
2200
    /// directly but for all these it is true (float)(f((double)arg)) ==
2201
    /// f(arg).  Long double not supported yet.
2202
12.8k
    const APFloat &APF = Op->getValueAPF();
2203
2204
12.8k
    switch (IntrinsicID) {
2205
6.52k
      default: break;
2206
6.52k
      case Intrinsic::log:
2207
103
        return ConstantFoldFP(log, APF, Ty);
2208
51
      case Intrinsic::log2:
2209
        // TODO: What about hosts that lack a C99 library?
2210
51
        return ConstantFoldFP(log2, APF, Ty);
2211
67
      case Intrinsic::log10:
2212
        // TODO: What about hosts that lack a C99 library?
2213
67
        return ConstantFoldFP(log10, APF, Ty);
2214
2.54k
      case Intrinsic::exp:
2215
2.54k
        return ConstantFoldFP(exp, APF, Ty);
2216
550
      case Intrinsic::exp2:
2217
        // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2218
550
        return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
2219
0
      case Intrinsic::exp10:
2220
        // Fold exp10(x) as pow(10, x), in case the host lacks a C99 library.
2221
0
        return ConstantFoldBinaryFP(pow, APFloat(10.0), APF, Ty);
2222
1.59k
      case Intrinsic::sin:
2223
1.59k
        return ConstantFoldFP(sin, APF, Ty);
2224
193
      case Intrinsic::cos:
2225
193
        return ConstantFoldFP(cos, APF, Ty);
2226
1.21k
      case Intrinsic::sqrt:
2227
1.21k
        return ConstantFoldFP(sqrt, APF, Ty);
2228
8
      case Intrinsic::amdgcn_cos:
2229
8
      case Intrinsic::amdgcn_sin: {
2230
8
        double V = getValueAsDouble(Op);
2231
8
        if (V < -256.0 || V > 256.0)
2232
          // The gfx8 and gfx9 architectures handle arguments outside the range
2233
          // [-256, 256] differently. This should be a rare case so bail out
2234
          // rather than trying to handle the difference.
2235
0
          return nullptr;
2236
8
        bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
2237
8
        double V4 = V * 4.0;
2238
8
        if (V4 == floor(V4)) {
2239
          // Force exact results for quarter-integer inputs.
2240
7
          const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
2241
7
          V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
2242
7
        } else {
2243
1
          if (IsCos)
2244
1
            V = cos(V * 2.0 * numbers::pi);
2245
0
          else
2246
0
            V = sin(V * 2.0 * numbers::pi);
2247
1
        }
2248
8
        return GetConstantFoldFPValue(V, Ty);
2249
8
      }
2250
12.8k
    }
2251
2252
6.52k
    if (!TLI)
2253
0
      return nullptr;
2254
2255
6.52k
    LibFunc Func = NotLibFunc;
2256
6.52k
    if (!TLI->getLibFunc(Name, Func))
2257
0
      return nullptr;
2258
2259
6.52k
    switch (Func) {
2260
0
    default:
2261
0
      break;
2262
54
    case LibFunc_acos:
2263
91
    case LibFunc_acosf:
2264
91
    case LibFunc_acos_finite:
2265
91
    case LibFunc_acosf_finite:
2266
91
      if (TLI->has(Func))
2267
91
        return ConstantFoldFP(acos, APF, Ty);
2268
0
      break;
2269
57
    case LibFunc_asin:
2270
72
    case LibFunc_asinf:
2271
72
    case LibFunc_asin_finite:
2272
72
    case LibFunc_asinf_finite:
2273
72
      if (TLI->has(Func))
2274
72
        return ConstantFoldFP(asin, APF, Ty);
2275
0
      break;
2276
37
    case LibFunc_atan:
2277
40
    case LibFunc_atanf:
2278
40
      if (TLI->has(Func))
2279
40
        return ConstantFoldFP(atan, APF, Ty);
2280
0
      break;
2281
582
    case LibFunc_ceil:
2282
587
    case LibFunc_ceilf:
2283
587
      if (TLI->has(Func)) {
2284
587
        U.roundToIntegral(APFloat::rmTowardPositive);
2285
587
        return ConstantFP::get(Ty->getContext(), U);
2286
587
      }
2287
0
      break;
2288
571
    case LibFunc_cos:
2289
1.72k
    case LibFunc_cosf:
2290
1.72k
      if (TLI->has(Func))
2291
1.72k
        return ConstantFoldFP(cos, APF, Ty);
2292
0
      break;
2293
22
    case LibFunc_cosh:
2294
31
    case LibFunc_coshf:
2295
31
    case LibFunc_cosh_finite:
2296
31
    case LibFunc_coshf_finite:
2297
31
      if (TLI->has(Func))
2298
31
        return ConstantFoldFP(cosh, APF, Ty);
2299
0
      break;
2300
215
    case LibFunc_exp:
2301
355
    case LibFunc_expf:
2302
375
    case LibFunc_exp_finite:
2303
380
    case LibFunc_expf_finite:
2304
380
      if (TLI->has(Func))
2305
355
        return ConstantFoldFP(exp, APF, Ty);
2306
25
      break;
2307
67
    case LibFunc_exp2:
2308
508
    case LibFunc_exp2f:
2309
508
    case LibFunc_exp2_finite:
2310
508
    case LibFunc_exp2f_finite:
2311
508
      if (TLI->has(Func))
2312
        // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2313
508
        return ConstantFoldBinaryFP(pow, APFloat(2.0), APF, Ty);
2314
0
      break;
2315
25
    case LibFunc_fabs:
2316
470
    case LibFunc_fabsf:
2317
470
      if (TLI->has(Func)) {
2318
470
        U.clearSign();
2319
470
        return ConstantFP::get(Ty->getContext(), U);
2320
470
      }
2321
0
      break;
2322
7
    case LibFunc_floor:
2323
7
    case LibFunc_floorf:
2324
7
      if (TLI->has(Func)) {
2325
7
        U.roundToIntegral(APFloat::rmTowardNegative);
2326
7
        return ConstantFP::get(Ty->getContext(), U);
2327
7
      }
2328
0
      break;
2329
107
    case LibFunc_log:
2330
190
    case LibFunc_logf:
2331
206
    case LibFunc_log_finite:
2332
237
    case LibFunc_logf_finite:
2333
237
      if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2334
96
        return ConstantFoldFP(log, APF, Ty);
2335
141
      break;
2336
141
    case LibFunc_log2:
2337
110
    case LibFunc_log2f:
2338
110
    case LibFunc_log2_finite:
2339
110
    case LibFunc_log2f_finite:
2340
110
      if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2341
        // TODO: What about hosts that lack a C99 library?
2342
24
        return ConstantFoldFP(log2, APF, Ty);
2343
86
      break;
2344
86
    case LibFunc_log10:
2345
90
    case LibFunc_log10f:
2346
90
    case LibFunc_log10_finite:
2347
90
    case LibFunc_log10f_finite:
2348
90
      if (!APF.isNegative() && !APF.isZero() && TLI->has(Func))
2349
        // TODO: What about hosts that lack a C99 library?
2350
46
        return ConstantFoldFP(log10, APF, Ty);
2351
44
      break;
2352
44
    case LibFunc_nearbyint:
2353
4
    case LibFunc_nearbyintf:
2354
4
    case LibFunc_rint:
2355
4
    case LibFunc_rintf:
2356
4
      if (TLI->has(Func)) {
2357
4
        U.roundToIntegral(APFloat::rmNearestTiesToEven);
2358
4
        return ConstantFP::get(Ty->getContext(), U);
2359
4
      }
2360
0
      break;
2361
19
    case LibFunc_round:
2362
19
    case LibFunc_roundf:
2363
19
      if (TLI->has(Func)) {
2364
19
        U.roundToIntegral(APFloat::rmNearestTiesToAway);
2365
19
        return ConstantFP::get(Ty->getContext(), U);
2366
19
      }
2367
0
      break;
2368
313
    case LibFunc_sin:
2369
1.39k
    case LibFunc_sinf:
2370
1.39k
      if (TLI->has(Func))
2371
1.39k
        return ConstantFoldFP(sin, APF, Ty);
2372
0
      break;
2373
20
    case LibFunc_sinh:
2374
32
    case LibFunc_sinhf:
2375
32
    case LibFunc_sinh_finite:
2376
32
    case LibFunc_sinhf_finite:
2377
32
      if (TLI->has(Func))
2378
32
        return ConstantFoldFP(sinh, APF, Ty);
2379
0
      break;
2380
534
    case LibFunc_sqrt:
2381
570
    case LibFunc_sqrtf:
2382
570
      if (!APF.isNegative() && TLI->has(Func))
2383
555
        return ConstantFoldFP(sqrt, APF, Ty);
2384
15
      break;
2385
42
    case LibFunc_tan:
2386
59
    case LibFunc_tanf:
2387
59
      if (TLI->has(Func))
2388
59
        return ConstantFoldFP(tan, APF, Ty);
2389
0
      break;
2390
63
    case LibFunc_tanh:
2391
85
    case LibFunc_tanhf:
2392
85
      if (TLI->has(Func))
2393
85
        return ConstantFoldFP(tanh, APF, Ty);
2394
0
      break;
2395
16
    case LibFunc_trunc:
2396
16
    case LibFunc_truncf:
2397
16
      if (TLI->has(Func)) {
2398
16
        U.roundToIntegral(APFloat::rmTowardZero);
2399
16
        return ConstantFP::get(Ty->getContext(), U);
2400
16
      }
2401
0
      break;
2402
6.52k
    }
2403
311
    return nullptr;
2404
6.52k
  }
2405
2406
557
  if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2407
338
    switch (IntrinsicID) {
2408
133
    case Intrinsic::bswap:
2409
133
      return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
2410
125
    case Intrinsic::ctpop:
2411
125
      return ConstantInt::get(Ty, Op->getValue().popcount());
2412
80
    case Intrinsic::bitreverse:
2413
80
      return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
2414
0
    case Intrinsic::convert_from_fp16: {
2415
0
      APFloat Val(APFloat::IEEEhalf(), Op->getValue());
2416
2417
0
      bool lost = false;
2418
0
      APFloat::opStatus status = Val.convert(
2419
0
          Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
2420
2421
      // Conversion is always precise.
2422
0
      (void)status;
2423
0
      assert(status != APFloat::opInexact && !lost &&
2424
0
             "Precision lost during fp16 constfolding");
2425
2426
0
      return ConstantFP::get(Ty->getContext(), Val);
2427
0
    }
2428
2429
0
    case Intrinsic::amdgcn_s_wqm: {
2430
0
      uint64_t Val = Op->getZExtValue();
2431
0
      Val |= (Val & 0x5555555555555555ULL) << 1 |
2432
0
             ((Val >> 1) & 0x5555555555555555ULL);
2433
0
      Val |= (Val & 0x3333333333333333ULL) << 2 |
2434
0
             ((Val >> 2) & 0x3333333333333333ULL);
2435
0
      return ConstantInt::get(Ty, Val);
2436
0
    }
2437
2438
0
    case Intrinsic::amdgcn_s_quadmask: {
2439
0
      uint64_t Val = Op->getZExtValue();
2440
0
      uint64_t QuadMask = 0;
2441
0
      for (unsigned I = 0; I < Op->getBitWidth() / 4; ++I, Val >>= 4) {
2442
0
        if (!(Val & 0xF))
2443
0
          continue;
2444
2445
0
        QuadMask |= (1ULL << I);
2446
0
      }
2447
0
      return ConstantInt::get(Ty, QuadMask);
2448
0
    }
2449
2450
0
    case Intrinsic::amdgcn_s_bitreplicate: {
2451
0
      uint64_t Val = Op->getZExtValue();
2452
0
      Val = (Val & 0x000000000000FFFFULL) | (Val & 0x00000000FFFF0000ULL) << 16;
2453
0
      Val = (Val & 0x000000FF000000FFULL) | (Val & 0x0000FF000000FF00ULL) << 8;
2454
0
      Val = (Val & 0x000F000F000F000FULL) | (Val & 0x00F000F000F000F0ULL) << 4;
2455
0
      Val = (Val & 0x0303030303030303ULL) | (Val & 0x0C0C0C0C0C0C0C0CULL) << 2;
2456
0
      Val = (Val & 0x1111111111111111ULL) | (Val & 0x2222222222222222ULL) << 1;
2457
0
      Val = Val | Val << 1;
2458
0
      return ConstantInt::get(Ty, Val);
2459
0
    }
2460
2461
0
    default:
2462
0
      return nullptr;
2463
338
    }
2464
338
  }
2465
2466
219
  switch (IntrinsicID) {
2467
116
  default: break;
2468
116
  case Intrinsic::vector_reduce_add:
2469
6
  case Intrinsic::vector_reduce_mul:
2470
7
  case Intrinsic::vector_reduce_and:
2471
8
  case Intrinsic::vector_reduce_or:
2472
26
  case Intrinsic::vector_reduce_xor:
2473
60
  case Intrinsic::vector_reduce_smin:
2474
83
  case Intrinsic::vector_reduce_smax:
2475
100
  case Intrinsic::vector_reduce_umin:
2476
103
  case Intrinsic::vector_reduce_umax:
2477
103
    if (Constant *C = constantFoldVectorReduce(IntrinsicID, Operands[0]))
2478
52
      return C;
2479
51
    break;
2480
219
  }
2481
2482
  // Support ConstantVector in case we have an Undef in the top.
2483
167
  if (isa<ConstantVector>(Operands[0]) ||
2484
167
      isa<ConstantDataVector>(Operands[0])) {
2485
47
    auto *Op = cast<Constant>(Operands[0]);
2486
47
    switch (IntrinsicID) {
2487
0
    default: break;
2488
1
    case Intrinsic::x86_sse_cvtss2si:
2489
9
    case Intrinsic::x86_sse_cvtss2si64:
2490
10
    case Intrinsic::x86_sse2_cvtsd2si:
2491
14
    case Intrinsic::x86_sse2_cvtsd2si64:
2492
14
      if (ConstantFP *FPOp =
2493
14
              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2494
3
        return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2495
3
                                           /*roundTowardZero=*/false, Ty,
2496
3
                                           /*IsSigned*/true);
2497
11
      break;
2498
11
    case Intrinsic::x86_sse_cvttss2si:
2499
25
    case Intrinsic::x86_sse_cvttss2si64:
2500
32
    case Intrinsic::x86_sse2_cvttsd2si:
2501
33
    case Intrinsic::x86_sse2_cvttsd2si64:
2502
33
      if (ConstantFP *FPOp =
2503
33
              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2504
17
        return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2505
17
                                           /*roundTowardZero=*/true, Ty,
2506
17
                                           /*IsSigned*/true);
2507
16
      break;
2508
47
    }
2509
47
  }
2510
2511
147
  return nullptr;
2512
167
}
2513
2514
static Constant *evaluateCompare(const APFloat &Op1, const APFloat &Op2,
2515
0
                                 const ConstrainedFPIntrinsic *Call) {
2516
0
  APFloat::opStatus St = APFloat::opOK;
2517
0
  auto *FCmp = cast<ConstrainedFPCmpIntrinsic>(Call);
2518
0
  FCmpInst::Predicate Cond = FCmp->getPredicate();
2519
0
  if (FCmp->isSignaling()) {
2520
0
    if (Op1.isNaN() || Op2.isNaN())
2521
0
      St = APFloat::opInvalidOp;
2522
0
  } else {
2523
0
    if (Op1.isSignaling() || Op2.isSignaling())
2524
0
      St = APFloat::opInvalidOp;
2525
0
  }
2526
0
  bool Result = FCmpInst::compare(Op1, Op2, Cond);
2527
0
  if (mayFoldConstrained(const_cast<ConstrainedFPCmpIntrinsic *>(FCmp), St))
2528
0
    return ConstantInt::get(Call->getType()->getScalarType(), Result);
2529
0
  return nullptr;
2530
0
}
2531
2532
static Constant *ConstantFoldScalarCall2(StringRef Name,
2533
                                         Intrinsic::ID IntrinsicID,
2534
                                         Type *Ty,
2535
                                         ArrayRef<Constant *> Operands,
2536
                                         const TargetLibraryInfo *TLI,
2537
25.3k
                                         const CallBase *Call) {
2538
25.3k
  assert(Operands.size() == 2 && "Wrong number of operands.");
2539
2540
25.3k
  if (Ty->isFloatingPointTy()) {
2541
    // TODO: We should have undef handling for all of the FP intrinsics that
2542
    //       are attempted to be folded in this function.
2543
916
    bool IsOp0Undef = isa<UndefValue>(Operands[0]);
2544
916
    bool IsOp1Undef = isa<UndefValue>(Operands[1]);
2545
916
    switch (IntrinsicID) {
2546
143
    case Intrinsic::maxnum:
2547
152
    case Intrinsic::minnum:
2548
394
    case Intrinsic::maximum:
2549
494
    case Intrinsic::minimum:
2550
      // If one argument is undef, return the other argument.
2551
494
      if (IsOp0Undef)
2552
23
        return Operands[1];
2553
471
      if (IsOp1Undef)
2554
2
        return Operands[0];
2555
469
      break;
2556
916
    }
2557
916
  }
2558
2559
25.3k
  if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2560
889
    const APFloat &Op1V = Op1->getValueAPF();
2561
2562
889
    if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2563
851
      if (Op2->getType() != Op1->getType())
2564
0
        return nullptr;
2565
851
      const APFloat &Op2V = Op2->getValueAPF();
2566
2567
851
      if (const auto *ConstrIntr = dyn_cast<ConstrainedFPIntrinsic>(Call)) {
2568
0
        RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
2569
0
        APFloat Res = Op1V;
2570
0
        APFloat::opStatus St;
2571
0
        switch (IntrinsicID) {
2572
0
        default:
2573
0
          return nullptr;
2574
0
        case Intrinsic::experimental_constrained_fadd:
2575
0
          St = Res.add(Op2V, RM);
2576
0
          break;
2577
0
        case Intrinsic::experimental_constrained_fsub:
2578
0
          St = Res.subtract(Op2V, RM);
2579
0
          break;
2580
0
        case Intrinsic::experimental_constrained_fmul:
2581
0
          St = Res.multiply(Op2V, RM);
2582
0
          break;
2583
0
        case Intrinsic::experimental_constrained_fdiv:
2584
0
          St = Res.divide(Op2V, RM);
2585
0
          break;
2586
0
        case Intrinsic::experimental_constrained_frem:
2587
0
          St = Res.mod(Op2V);
2588
0
          break;
2589
0
        case Intrinsic::experimental_constrained_fcmp:
2590
0
        case Intrinsic::experimental_constrained_fcmps:
2591
0
          return evaluateCompare(Op1V, Op2V, ConstrIntr);
2592
0
        }
2593
0
        if (mayFoldConstrained(const_cast<ConstrainedFPIntrinsic *>(ConstrIntr),
2594
0
                               St))
2595
0
          return ConstantFP::get(Ty->getContext(), Res);
2596
0
        return nullptr;
2597
0
      }
2598
2599
851
      switch (IntrinsicID) {
2600
369
      default:
2601
369
        break;
2602
369
      case Intrinsic::copysign:
2603
13
        return ConstantFP::get(Ty->getContext(), APFloat::copySign(Op1V, Op2V));
2604
8
      case Intrinsic::minnum:
2605
8
        return ConstantFP::get(Ty->getContext(), minnum(Op1V, Op2V));
2606
133
      case Intrinsic::maxnum:
2607
133
        return ConstantFP::get(Ty->getContext(), maxnum(Op1V, Op2V));
2608
90
      case Intrinsic::minimum:
2609
90
        return ConstantFP::get(Ty->getContext(), minimum(Op1V, Op2V));
2610
238
      case Intrinsic::maximum:
2611
238
        return ConstantFP::get(Ty->getContext(), maximum(Op1V, Op2V));
2612
851
      }
2613
2614
369
      if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2615
0
        return nullptr;
2616
2617
369
      switch (IntrinsicID) {
2618
144
      default:
2619
144
        break;
2620
225
      case Intrinsic::pow:
2621
225
        return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2622
0
      case Intrinsic::amdgcn_fmul_legacy:
2623
        // The legacy behaviour is that multiplying +/- 0.0 by anything, even
2624
        // NaN or infinity, gives +0.0.
2625
0
        if (Op1V.isZero() || Op2V.isZero())
2626
0
          return ConstantFP::getZero(Ty);
2627
0
        return ConstantFP::get(Ty->getContext(), Op1V * Op2V);
2628
369
      }
2629
2630
144
      if (!TLI)
2631
0
        return nullptr;
2632
2633
144
      LibFunc Func = NotLibFunc;
2634
144
      if (!TLI->getLibFunc(Name, Func))
2635
0
        return nullptr;
2636
2637
144
      switch (Func) {
2638
0
      default:
2639
0
        break;
2640
30
      case LibFunc_pow:
2641
125
      case LibFunc_powf:
2642
136
      case LibFunc_pow_finite:
2643
142
      case LibFunc_powf_finite:
2644
142
        if (TLI->has(Func))
2645
125
          return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2646
17
        break;
2647
17
      case LibFunc_fmod:
2648
1
      case LibFunc_fmodf:
2649
1
        if (TLI->has(Func)) {
2650
1
          APFloat V = Op1->getValueAPF();
2651
1
          if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
2652
0
            return ConstantFP::get(Ty->getContext(), V);
2653
1
        }
2654
1
        break;
2655
1
      case LibFunc_remainder:
2656
0
      case LibFunc_remainderf:
2657
0
        if (TLI->has(Func)) {
2658
0
          APFloat V = Op1->getValueAPF();
2659
0
          if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
2660
0
            return ConstantFP::get(Ty->getContext(), V);
2661
0
        }
2662
0
        break;
2663
1
      case LibFunc_atan2:
2664
1
      case LibFunc_atan2f:
2665
        // atan2(+/-0.0, +/-0.0) is known to raise an exception on some libm
2666
        // (Solaris), so we do not assume a known result for that.
2667
1
        if (Op1V.isZero() && Op2V.isZero())
2668
0
          return nullptr;
2669
1
        [[fallthrough]];
2670
1
      case LibFunc_atan2_finite:
2671
1
      case LibFunc_atan2f_finite:
2672
1
        if (TLI->has(Func))
2673
1
          return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
2674
0
        break;
2675
144
      }
2676
144
    } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
2677
38
      switch (IntrinsicID) {
2678
30
      case Intrinsic::ldexp: {
2679
30
        return ConstantFP::get(
2680
30
            Ty->getContext(),
2681
30
            scalbn(Op1V, Op2C->getSExtValue(), APFloat::rmNearestTiesToEven));
2682
0
      }
2683
0
      case Intrinsic::is_fpclass: {
2684
0
        FPClassTest Mask = static_cast<FPClassTest>(Op2C->getZExtValue());
2685
0
        bool Result =
2686
0
          ((Mask & fcSNan) && Op1V.isNaN() && Op1V.isSignaling()) ||
2687
0
          ((Mask & fcQNan) && Op1V.isNaN() && !Op1V.isSignaling()) ||
2688
0
          ((Mask & fcNegInf) && Op1V.isNegInfinity()) ||
2689
0
          ((Mask & fcNegNormal) && Op1V.isNormal() && Op1V.isNegative()) ||
2690
0
          ((Mask & fcNegSubnormal) && Op1V.isDenormal() && Op1V.isNegative()) ||
2691
0
          ((Mask & fcNegZero) && Op1V.isZero() && Op1V.isNegative()) ||
2692
0
          ((Mask & fcPosZero) && Op1V.isZero() && !Op1V.isNegative()) ||
2693
0
          ((Mask & fcPosSubnormal) && Op1V.isDenormal() && !Op1V.isNegative()) ||
2694
0
          ((Mask & fcPosNormal) && Op1V.isNormal() && !Op1V.isNegative()) ||
2695
0
          ((Mask & fcPosInf) && Op1V.isPosInfinity());
2696
0
        return ConstantInt::get(Ty, Result);
2697
0
      }
2698
8
      default:
2699
8
        break;
2700
38
      }
2701
2702
8
      if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2703
0
        return nullptr;
2704
8
      if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
2705
0
        return ConstantFP::get(
2706
0
            Ty->getContext(),
2707
0
            APFloat((float)std::pow((float)Op1V.convertToDouble(),
2708
0
                                    (int)Op2C->getZExtValue())));
2709
8
      if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2710
0
        return ConstantFP::get(
2711
0
            Ty->getContext(),
2712
0
            APFloat((float)std::pow((float)Op1V.convertToDouble(),
2713
0
                                    (int)Op2C->getZExtValue())));
2714
8
      if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2715
8
        return ConstantFP::get(
2716
8
            Ty->getContext(),
2717
8
            APFloat((double)std::pow(Op1V.convertToDouble(),
2718
8
                                     (int)Op2C->getZExtValue())));
2719
8
    }
2720
18
    return nullptr;
2721
889
  }
2722
2723
24.4k
  if (Operands[0]->getType()->isIntegerTy() &&
2724
24.4k
      Operands[1]->getType()->isIntegerTy()) {
2725
24.2k
    const APInt *C0, *C1;
2726
24.2k
    if (!getConstIntOrUndef(Operands[0], C0) ||
2727
24.2k
        !getConstIntOrUndef(Operands[1], C1))
2728
0
      return nullptr;
2729
2730
24.2k
    switch (IntrinsicID) {
2731
0
    default: break;
2732
80
    case Intrinsic::smax:
2733
174
    case Intrinsic::smin:
2734
255
    case Intrinsic::umax:
2735
298
    case Intrinsic::umin:
2736
      // This is the same as for binary ops - poison propagates.
2737
      // TODO: Poison handling should be consolidated.
2738
298
      if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2739
19
        return PoisonValue::get(Ty);
2740
2741
279
      if (!C0 && !C1)
2742
2
        return UndefValue::get(Ty);
2743
277
      if (!C0 || !C1)
2744
44
        return MinMaxIntrinsic::getSaturationPoint(IntrinsicID, Ty);
2745
233
      return ConstantInt::get(
2746
233
          Ty, ICmpInst::compare(*C0, *C1,
2747
233
                                MinMaxIntrinsic::getPredicate(IntrinsicID))
2748
233
                  ? *C0
2749
233
                  : *C1);
2750
2751
10
    case Intrinsic::usub_with_overflow:
2752
41
    case Intrinsic::ssub_with_overflow:
2753
      // X - undef -> { 0, false }
2754
      // undef - X -> { 0, false }
2755
41
      if (!C0 || !C1)
2756
3
        return Constant::getNullValue(Ty);
2757
41
      [[fallthrough]];
2758
54
    case Intrinsic::uadd_with_overflow:
2759
126
    case Intrinsic::sadd_with_overflow:
2760
      // X + undef -> { -1, false }
2761
      // undef + x -> { -1, false }
2762
126
      if (!C0 || !C1) {
2763
36
        return ConstantStruct::get(
2764
36
            cast<StructType>(Ty),
2765
36
            {Constant::getAllOnesValue(Ty->getStructElementType(0)),
2766
36
             Constant::getNullValue(Ty->getStructElementType(1))});
2767
36
      }
2768
126
      [[fallthrough]];
2769
120
    case Intrinsic::smul_with_overflow:
2770
138
    case Intrinsic::umul_with_overflow: {
2771
      // undef * X -> { 0, false }
2772
      // X * undef -> { 0, false }
2773
138
      if (!C0 || !C1)
2774
5
        return Constant::getNullValue(Ty);
2775
2776
133
      APInt Res;
2777
133
      bool Overflow;
2778
133
      switch (IntrinsicID) {
2779
0
      default: llvm_unreachable("Invalid case");
2780
37
      case Intrinsic::sadd_with_overflow:
2781
37
        Res = C0->sadd_ov(*C1, Overflow);
2782
37
        break;
2783
15
      case Intrinsic::uadd_with_overflow:
2784
15
        Res = C0->uadd_ov(*C1, Overflow);
2785
15
        break;
2786
28
      case Intrinsic::ssub_with_overflow:
2787
28
        Res = C0->ssub_ov(*C1, Overflow);
2788
28
        break;
2789
10
      case Intrinsic::usub_with_overflow:
2790
10
        Res = C0->usub_ov(*C1, Overflow);
2791
10
        break;
2792
28
      case Intrinsic::smul_with_overflow:
2793
28
        Res = C0->smul_ov(*C1, Overflow);
2794
28
        break;
2795
15
      case Intrinsic::umul_with_overflow:
2796
15
        Res = C0->umul_ov(*C1, Overflow);
2797
15
        break;
2798
133
      }
2799
133
      Constant *Ops[] = {
2800
133
        ConstantInt::get(Ty->getContext(), Res),
2801
133
        ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2802
133
      };
2803
133
      return ConstantStruct::get(cast<StructType>(Ty), Ops);
2804
133
    }
2805
197
    case Intrinsic::uadd_sat:
2806
11.6k
    case Intrinsic::sadd_sat:
2807
      // This is the same as for binary ops - poison propagates.
2808
      // TODO: Poison handling should be consolidated.
2809
11.6k
      if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2810
39
        return PoisonValue::get(Ty);
2811
2812
11.6k
      if (!C0 && !C1)
2813
207
        return UndefValue::get(Ty);
2814
11.4k
      if (!C0 || !C1)
2815
313
        return Constant::getAllOnesValue(Ty);
2816
11.1k
      if (IntrinsicID == Intrinsic::uadd_sat)
2817
115
        return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2818
10.9k
      else
2819
10.9k
        return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2820
226
    case Intrinsic::usub_sat:
2821
11.0k
    case Intrinsic::ssub_sat:
2822
      // This is the same as for binary ops - poison propagates.
2823
      // TODO: Poison handling should be consolidated.
2824
11.0k
      if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2825
140
        return PoisonValue::get(Ty);
2826
2827
10.8k
      if (!C0 && !C1)
2828
163
        return UndefValue::get(Ty);
2829
10.7k
      if (!C0 || !C1)
2830
407
        return Constant::getNullValue(Ty);
2831
10.3k
      if (IntrinsicID == Intrinsic::usub_sat)
2832
68
        return ConstantInt::get(Ty, C0->usub_sat(*C1));
2833
10.2k
      else
2834
10.2k
        return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2835
168
    case Intrinsic::cttz:
2836
1.11k
    case Intrinsic::ctlz:
2837
1.11k
      assert(C1 && "Must be constant int");
2838
2839
      // cttz(0, 1) and ctlz(0, 1) are poison.
2840
1.11k
      if (C1->isOne() && (!C0 || C0->isZero()))
2841
276
        return PoisonValue::get(Ty);
2842
838
      if (!C0)
2843
33
        return Constant::getNullValue(Ty);
2844
805
      if (IntrinsicID == Intrinsic::cttz)
2845
89
        return ConstantInt::get(Ty, C0->countr_zero());
2846
716
      else
2847
716
        return ConstantInt::get(Ty, C0->countl_zero());
2848
2849
29
    case Intrinsic::abs:
2850
29
      assert(C1 && "Must be constant int");
2851
0
      assert((C1->isOne() || C1->isZero()) && "Must be 0 or 1");
2852
2853
      // Undef or minimum val operand with poison min --> undef
2854
29
      if (C1->isOne() && (!C0 || C0->isMinSignedValue()))
2855
8
        return UndefValue::get(Ty);
2856
2857
      // Undef operand with no poison min --> 0 (sign bit must be clear)
2858
21
      if (!C0)
2859
8
        return Constant::getNullValue(Ty);
2860
2861
13
      return ConstantInt::get(Ty, C0->abs());
2862
0
    case Intrinsic::amdgcn_wave_reduce_umin:
2863
0
    case Intrinsic::amdgcn_wave_reduce_umax:
2864
0
      return dyn_cast<Constant>(Operands[0]);
2865
24.2k
    }
2866
2867
0
    return nullptr;
2868
24.2k
  }
2869
2870
  // Support ConstantVector in case we have an Undef in the top.
2871
179
  if ((isa<ConstantVector>(Operands[0]) ||
2872
179
       isa<ConstantDataVector>(Operands[0])) &&
2873
      // Check for default rounding mode.
2874
      // FIXME: Support other rounding modes?
2875
179
      isa<ConstantInt>(Operands[1]) &&
2876
179
      cast<ConstantInt>(Operands[1])->getValue() == 4) {
2877
31
    auto *Op = cast<Constant>(Operands[0]);
2878
31
    switch (IntrinsicID) {
2879
0
    default: break;
2880
0
    case Intrinsic::x86_avx512_vcvtss2si32:
2881
0
    case Intrinsic::x86_avx512_vcvtss2si64:
2882
2
    case Intrinsic::x86_avx512_vcvtsd2si32:
2883
2
    case Intrinsic::x86_avx512_vcvtsd2si64:
2884
2
      if (ConstantFP *FPOp =
2885
2
              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2886
0
        return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2887
0
                                           /*roundTowardZero=*/false, Ty,
2888
0
                                           /*IsSigned*/true);
2889
2
      break;
2890
13
    case Intrinsic::x86_avx512_vcvtss2usi32:
2891
13
    case Intrinsic::x86_avx512_vcvtss2usi64:
2892
13
    case Intrinsic::x86_avx512_vcvtsd2usi32:
2893
20
    case Intrinsic::x86_avx512_vcvtsd2usi64:
2894
20
      if (ConstantFP *FPOp =
2895
20
              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2896
0
        return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2897
0
                                           /*roundTowardZero=*/false, Ty,
2898
0
                                           /*IsSigned*/false);
2899
20
      break;
2900
20
    case Intrinsic::x86_avx512_cvttss2si:
2901
2
    case Intrinsic::x86_avx512_cvttss2si64:
2902
2
    case Intrinsic::x86_avx512_cvttsd2si:
2903
2
    case Intrinsic::x86_avx512_cvttsd2si64:
2904
2
      if (ConstantFP *FPOp =
2905
2
              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2906
0
        return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2907
0
                                           /*roundTowardZero=*/true, Ty,
2908
0
                                           /*IsSigned*/true);
2909
2
      break;
2910
7
    case Intrinsic::x86_avx512_cvttss2usi:
2911
7
    case Intrinsic::x86_avx512_cvttss2usi64:
2912
7
    case Intrinsic::x86_avx512_cvttsd2usi:
2913
7
    case Intrinsic::x86_avx512_cvttsd2usi64:
2914
7
      if (ConstantFP *FPOp =
2915
7
              dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2916
0
        return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2917
0
                                           /*roundTowardZero=*/true, Ty,
2918
0
                                           /*IsSigned*/false);
2919
7
      break;
2920
31
    }
2921
31
  }
2922
179
  return nullptr;
2923
179
}
2924
2925
static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
2926
                                               const APFloat &S0,
2927
                                               const APFloat &S1,
2928
0
                                               const APFloat &S2) {
2929
0
  unsigned ID;
2930
0
  const fltSemantics &Sem = S0.getSemantics();
2931
0
  APFloat MA(Sem), SC(Sem), TC(Sem);
2932
0
  if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
2933
0
    if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
2934
      // S2 < 0
2935
0
      ID = 5;
2936
0
      SC = -S0;
2937
0
    } else {
2938
0
      ID = 4;
2939
0
      SC = S0;
2940
0
    }
2941
0
    MA = S2;
2942
0
    TC = -S1;
2943
0
  } else if (abs(S1) >= abs(S0)) {
2944
0
    if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
2945
      // S1 < 0
2946
0
      ID = 3;
2947
0
      TC = -S2;
2948
0
    } else {
2949
0
      ID = 2;
2950
0
      TC = S2;
2951
0
    }
2952
0
    MA = S1;
2953
0
    SC = S0;
2954
0
  } else {
2955
0
    if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
2956
      // S0 < 0
2957
0
      ID = 1;
2958
0
      SC = S2;
2959
0
    } else {
2960
0
      ID = 0;
2961
0
      SC = -S2;
2962
0
    }
2963
0
    MA = S0;
2964
0
    TC = -S1;
2965
0
  }
2966
0
  switch (IntrinsicID) {
2967
0
  default:
2968
0
    llvm_unreachable("unhandled amdgcn cube intrinsic");
2969
0
  case Intrinsic::amdgcn_cubeid:
2970
0
    return APFloat(Sem, ID);
2971
0
  case Intrinsic::amdgcn_cubema:
2972
0
    return MA + MA;
2973
0
  case Intrinsic::amdgcn_cubesc:
2974
0
    return SC;
2975
0
  case Intrinsic::amdgcn_cubetc:
2976
0
    return TC;
2977
0
  }
2978
0
}
2979
2980
static Constant *ConstantFoldAMDGCNPermIntrinsic(ArrayRef<Constant *> Operands,
2981
0
                                                 Type *Ty) {
2982
0
  const APInt *C0, *C1, *C2;
2983
0
  if (!getConstIntOrUndef(Operands[0], C0) ||
2984
0
      !getConstIntOrUndef(Operands[1], C1) ||
2985
0
      !getConstIntOrUndef(Operands[2], C2))
2986
0
    return nullptr;
2987
2988
0
  if (!C2)
2989
0
    return UndefValue::get(Ty);
2990
2991
0
  APInt Val(32, 0);
2992
0
  unsigned NumUndefBytes = 0;
2993
0
  for (unsigned I = 0; I < 32; I += 8) {
2994
0
    unsigned Sel = C2->extractBitsAsZExtValue(8, I);
2995
0
    unsigned B = 0;
2996
2997
0
    if (Sel >= 13)
2998
0
      B = 0xff;
2999
0
    else if (Sel == 12)
3000
0
      B = 0x00;
3001
0
    else {
3002
0
      const APInt *Src = ((Sel & 10) == 10 || (Sel & 12) == 4) ? C0 : C1;
3003
0
      if (!Src)
3004
0
        ++NumUndefBytes;
3005
0
      else if (Sel < 8)
3006
0
        B = Src->extractBitsAsZExtValue(8, (Sel & 3) * 8);
3007
0
      else
3008
0
        B = Src->extractBitsAsZExtValue(1, (Sel & 1) ? 31 : 15) * 0xff;
3009
0
    }
3010
3011
0
    Val.insertBits(B, I, 8);
3012
0
  }
3013
3014
0
  if (NumUndefBytes == 4)
3015
0
    return UndefValue::get(Ty);
3016
3017
0
  return ConstantInt::get(Ty, Val);
3018
0
}
3019
3020
static Constant *ConstantFoldScalarCall3(StringRef Name,
3021
                                         Intrinsic::ID IntrinsicID,
3022
                                         Type *Ty,
3023
                                         ArrayRef<Constant *> Operands,
3024
                                         const TargetLibraryInfo *TLI,
3025
35
                                         const CallBase *Call) {
3026
35
  assert(Operands.size() == 3 && "Wrong number of operands.");
3027
3028
35
  if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
3029
8
    if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
3030
6
      if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
3031
6
        const APFloat &C1 = Op1->getValueAPF();
3032
6
        const APFloat &C2 = Op2->getValueAPF();
3033
6
        const APFloat &C3 = Op3->getValueAPF();
3034
3035
6
        if (const auto *ConstrIntr = dyn_cast<ConstrainedFPIntrinsic>(Call)) {
3036
0
          RoundingMode RM = getEvaluationRoundingMode(ConstrIntr);
3037
0
          APFloat Res = C1;
3038
0
          APFloat::opStatus St;
3039
0
          switch (IntrinsicID) {
3040
0
          default:
3041
0
            return nullptr;
3042
0
          case Intrinsic::experimental_constrained_fma:
3043
0
          case Intrinsic::experimental_constrained_fmuladd:
3044
0
            St = Res.fusedMultiplyAdd(C2, C3, RM);
3045
0
            break;
3046
0
          }
3047
0
          if (mayFoldConstrained(
3048
0
                  const_cast<ConstrainedFPIntrinsic *>(ConstrIntr), St))
3049
0
            return ConstantFP::get(Ty->getContext(), Res);
3050
0
          return nullptr;
3051
0
        }
3052
3053
6
        switch (IntrinsicID) {
3054
0
        default: break;
3055
0
        case Intrinsic::amdgcn_fma_legacy: {
3056
          // The legacy behaviour is that multiplying +/- 0.0 by anything, even
3057
          // NaN or infinity, gives +0.0.
3058
0
          if (C1.isZero() || C2.isZero()) {
3059
            // It's tempting to just return C3 here, but that would give the
3060
            // wrong result if C3 was -0.0.
3061
0
            return ConstantFP::get(Ty->getContext(), APFloat(0.0f) + C3);
3062
0
          }
3063
0
          [[fallthrough]];
3064
0
        }
3065
6
        case Intrinsic::fma:
3066
6
        case Intrinsic::fmuladd: {
3067
6
          APFloat V = C1;
3068
6
          V.fusedMultiplyAdd(C2, C3, APFloat::rmNearestTiesToEven);
3069
6
          return ConstantFP::get(Ty->getContext(), V);
3070
6
        }
3071
0
        case Intrinsic::amdgcn_cubeid:
3072
0
        case Intrinsic::amdgcn_cubema:
3073
0
        case Intrinsic::amdgcn_cubesc:
3074
0
        case Intrinsic::amdgcn_cubetc: {
3075
0
          APFloat V = ConstantFoldAMDGCNCubeIntrinsic(IntrinsicID, C1, C2, C3);
3076
0
          return ConstantFP::get(Ty->getContext(), V);
3077
0
        }
3078
6
        }
3079
6
      }
3080
6
    }
3081
8
  }
3082
3083
29
  if (IntrinsicID == Intrinsic::smul_fix ||
3084
29
      IntrinsicID == Intrinsic::smul_fix_sat) {
3085
    // poison * C -> poison
3086
    // C * poison -> poison
3087
12
    if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
3088
0
      return PoisonValue::get(Ty);
3089
3090
12
    const APInt *C0, *C1;
3091
12
    if (!getConstIntOrUndef(Operands[0], C0) ||
3092
12
        !getConstIntOrUndef(Operands[1], C1))
3093
0
      return nullptr;
3094
3095
    // undef * C -> 0
3096
    // C * undef -> 0
3097
12
    if (!C0 || !C1)
3098
2
      return Constant::getNullValue(Ty);
3099
3100
    // This code performs rounding towards negative infinity in case the result
3101
    // cannot be represented exactly for the given scale. Targets that do care
3102
    // about rounding should use a target hook for specifying how rounding
3103
    // should be done, and provide their own folding to be consistent with
3104
    // rounding. This is the same approach as used by
3105
    // DAGTypeLegalizer::ExpandIntRes_MULFIX.
3106
10
    unsigned Scale = cast<ConstantInt>(Operands[2])->getZExtValue();
3107
10
    unsigned Width = C0->getBitWidth();
3108
10
    assert(Scale < Width && "Illegal scale.");
3109
0
    unsigned ExtendedWidth = Width * 2;
3110
10
    APInt Product =
3111
10
        (C0->sext(ExtendedWidth) * C1->sext(ExtendedWidth)).ashr(Scale);
3112
10
    if (IntrinsicID == Intrinsic::smul_fix_sat) {
3113
6
      APInt Max = APInt::getSignedMaxValue(Width).sext(ExtendedWidth);
3114
6
      APInt Min = APInt::getSignedMinValue(Width).sext(ExtendedWidth);
3115
6
      Product = APIntOps::smin(Product, Max);
3116
6
      Product = APIntOps::smax(Product, Min);
3117
6
    }
3118
10
    return ConstantInt::get(Ty->getContext(), Product.sextOrTrunc(Width));
3119
12
  }
3120
3121
17
  if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
3122
13
    const APInt *C0, *C1, *C2;
3123
13
    if (!getConstIntOrUndef(Operands[0], C0) ||
3124
13
        !getConstIntOrUndef(Operands[1], C1) ||
3125
13
        !getConstIntOrUndef(Operands[2], C2))
3126
0
      return nullptr;
3127
3128
13
    bool IsRight = IntrinsicID == Intrinsic::fshr;
3129
13
    if (!C2)
3130
0
      return Operands[IsRight ? 1 : 0];
3131
13
    if (!C0 && !C1)
3132
0
      return UndefValue::get(Ty);
3133
3134
    // The shift amount is interpreted as modulo the bitwidth. If the shift
3135
    // amount is effectively 0, avoid UB due to oversized inverse shift below.
3136
13
    unsigned BitWidth = C2->getBitWidth();
3137
13
    unsigned ShAmt = C2->urem(BitWidth);
3138
13
    if (!ShAmt)
3139
0
      return Operands[IsRight ? 1 : 0];
3140
3141
    // (C0 << ShlAmt) | (C1 >> LshrAmt)
3142
13
    unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
3143
13
    unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
3144
13
    if (!C0)
3145
0
      return ConstantInt::get(Ty, C1->lshr(LshrAmt));
3146
13
    if (!C1)
3147
0
      return ConstantInt::get(Ty, C0->shl(ShlAmt));
3148
13
    return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
3149
13
  }
3150
3151
4
  if (IntrinsicID == Intrinsic::amdgcn_perm)
3152
0
    return ConstantFoldAMDGCNPermIntrinsic(Operands, Ty);
3153
3154
4
  return nullptr;
3155
4
}
3156
3157
static Constant *ConstantFoldScalarCall(StringRef Name,
3158
                                        Intrinsic::ID IntrinsicID,
3159
                                        Type *Ty,
3160
                                        ArrayRef<Constant *> Operands,
3161
                                        const TargetLibraryInfo *TLI,
3162
40.0k
                                        const CallBase *Call) {
3163
40.0k
  if (Operands.size() == 1)
3164
14.6k
    return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
3165
3166
25.4k
  if (Operands.size() == 2)
3167
25.3k
    return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call);
3168
3169
35
  if (Operands.size() == 3)
3170
35
    return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
3171
3172
0
  return nullptr;
3173
35
}
3174
3175
static Constant *ConstantFoldFixedVectorCall(
3176
    StringRef Name, Intrinsic::ID IntrinsicID, FixedVectorType *FVTy,
3177
    ArrayRef<Constant *> Operands, const DataLayout &DL,
3178
1.34k
    const TargetLibraryInfo *TLI, const CallBase *Call) {
3179
1.34k
  SmallVector<Constant *, 4> Result(FVTy->getNumElements());
3180
1.34k
  SmallVector<Constant *, 4> Lane(Operands.size());
3181
1.34k
  Type *Ty = FVTy->getElementType();
3182
3183
1.34k
  switch (IntrinsicID) {
3184
3
  case Intrinsic::masked_load: {
3185
3
    auto *SrcPtr = Operands[0];
3186
3
    auto *Mask = Operands[2];
3187
3
    auto *Passthru = Operands[3];
3188
3189
3
    Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
3190
3191
3
    SmallVector<Constant *, 32> NewElements;
3192
3
    for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
3193
3
      auto *MaskElt = Mask->getAggregateElement(I);
3194
3
      if (!MaskElt)
3195
0
        break;
3196
3
      auto *PassthruElt = Passthru->getAggregateElement(I);
3197
3
      auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
3198
3
      if (isa<UndefValue>(MaskElt)) {
3199
1
        if (PassthruElt)
3200
1
          NewElements.push_back(PassthruElt);
3201
0
        else if (VecElt)
3202
0
          NewElements.push_back(VecElt);
3203
0
        else
3204
0
          return nullptr;
3205
1
      }
3206
3
      if (MaskElt->isNullValue()) {
3207
0
        if (!PassthruElt)
3208
0
          return nullptr;
3209
0
        NewElements.push_back(PassthruElt);
3210
3
      } else if (MaskElt->isOneValue()) {
3211
2
        if (!VecElt)
3212
2
          return nullptr;
3213
0
        NewElements.push_back(VecElt);
3214
1
      } else {
3215
1
        return nullptr;
3216
1
      }
3217
3
    }
3218
0
    if (NewElements.size() != FVTy->getNumElements())
3219
0
      return nullptr;
3220
0
    return ConstantVector::get(NewElements);
3221
0
  }
3222
0
  case Intrinsic::arm_mve_vctp8:
3223
0
  case Intrinsic::arm_mve_vctp16:
3224
0
  case Intrinsic::arm_mve_vctp32:
3225
0
  case Intrinsic::arm_mve_vctp64: {
3226
0
    if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
3227
0
      unsigned Lanes = FVTy->getNumElements();
3228
0
      uint64_t Limit = Op->getZExtValue();
3229
3230
0
      SmallVector<Constant *, 16> NCs;
3231
0
      for (unsigned i = 0; i < Lanes; i++) {
3232
0
        if (i < Limit)
3233
0
          NCs.push_back(ConstantInt::getTrue(Ty));
3234
0
        else
3235
0
          NCs.push_back(ConstantInt::getFalse(Ty));
3236
0
      }
3237
0
      return ConstantVector::get(NCs);
3238
0
    }
3239
0
    return nullptr;
3240
0
  }
3241
0
  case Intrinsic::get_active_lane_mask: {
3242
0
    auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
3243
0
    auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
3244
0
    if (Op0 && Op1) {
3245
0
      unsigned Lanes = FVTy->getNumElements();
3246
0
      uint64_t Base = Op0->getZExtValue();
3247
0
      uint64_t Limit = Op1->getZExtValue();
3248
3249
0
      SmallVector<Constant *, 16> NCs;
3250
0
      for (unsigned i = 0; i < Lanes; i++) {
3251
0
        if (Base + i < Limit)
3252
0
          NCs.push_back(ConstantInt::getTrue(Ty));
3253
0
        else
3254
0
          NCs.push_back(ConstantInt::getFalse(Ty));
3255
0
      }
3256
0
      return ConstantVector::get(NCs);
3257
0
    }
3258
0
    return nullptr;
3259
0
  }
3260
1.33k
  default:
3261
1.33k
    break;
3262
1.34k
  }
3263
3264
24.1k
  for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
3265
    // Gather a column of constants.
3266
68.4k
    for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
3267
      // Some intrinsics use a scalar type for certain arguments.
3268
45.5k
      if (isVectorIntrinsicWithScalarOpAtArg(IntrinsicID, J)) {
3269
140
        Lane[J] = Operands[J];
3270
140
        continue;
3271
140
      }
3272
3273
45.4k
      Constant *Agg = Operands[J]->getAggregateElement(I);
3274
45.4k
      if (!Agg)
3275
0
        return nullptr;
3276
3277
45.4k
      Lane[J] = Agg;
3278
45.4k
    }
3279
3280
    // Use the regular scalar folding to simplify this column.
3281
22.8k
    Constant *Folded =
3282
22.8k
        ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
3283
22.8k
    if (!Folded)
3284
24
      return nullptr;
3285
22.8k
    Result[I] = Folded;
3286
22.8k
  }
3287
3288
1.31k
  return ConstantVector::get(Result);
3289
1.33k
}
3290
3291
static Constant *ConstantFoldScalableVectorCall(
3292
    StringRef Name, Intrinsic::ID IntrinsicID, ScalableVectorType *SVTy,
3293
    ArrayRef<Constant *> Operands, const DataLayout &DL,
3294
0
    const TargetLibraryInfo *TLI, const CallBase *Call) {
3295
0
  switch (IntrinsicID) {
3296
0
  case Intrinsic::aarch64_sve_convert_from_svbool: {
3297
0
    auto *Src = dyn_cast<Constant>(Operands[0]);
3298
0
    if (!Src || !Src->isNullValue())
3299
0
      break;
3300
3301
0
    return ConstantInt::getFalse(SVTy);
3302
0
  }
3303
0
  default:
3304
0
    break;
3305
0
  }
3306
0
  return nullptr;
3307
0
}
3308
3309
static std::pair<Constant *, Constant *>
3310
0
ConstantFoldScalarFrexpCall(Constant *Op, Type *IntTy) {
3311
0
  if (isa<PoisonValue>(Op))
3312
0
    return {Op, PoisonValue::get(IntTy)};
3313
3314
0
  auto *ConstFP = dyn_cast<ConstantFP>(Op);
3315
0
  if (!ConstFP)
3316
0
    return {};
3317
3318
0
  const APFloat &U = ConstFP->getValueAPF();
3319
0
  int FrexpExp;
3320
0
  APFloat FrexpMant = frexp(U, FrexpExp, APFloat::rmNearestTiesToEven);
3321
0
  Constant *Result0 = ConstantFP::get(ConstFP->getType(), FrexpMant);
3322
3323
  // The exponent is an "unspecified value" for inf/nan. We use zero to avoid
3324
  // using undef.
3325
0
  Constant *Result1 = FrexpMant.isFinite() ? ConstantInt::get(IntTy, FrexpExp)
3326
0
                                           : ConstantInt::getNullValue(IntTy);
3327
0
  return {Result0, Result1};
3328
0
}
3329
3330
/// Handle intrinsics that return tuples, which may be tuples of vectors.
3331
static Constant *
3332
ConstantFoldStructCall(StringRef Name, Intrinsic::ID IntrinsicID,
3333
                       StructType *StTy, ArrayRef<Constant *> Operands,
3334
                       const DataLayout &DL, const TargetLibraryInfo *TLI,
3335
323
                       const CallBase *Call) {
3336
3337
323
  switch (IntrinsicID) {
3338
0
  case Intrinsic::frexp: {
3339
0
    Type *Ty0 = StTy->getContainedType(0);
3340
0
    Type *Ty1 = StTy->getContainedType(1)->getScalarType();
3341
3342
0
    if (auto *FVTy0 = dyn_cast<FixedVectorType>(Ty0)) {
3343
0
      SmallVector<Constant *, 4> Results0(FVTy0->getNumElements());
3344
0
      SmallVector<Constant *, 4> Results1(FVTy0->getNumElements());
3345
3346
0
      for (unsigned I = 0, E = FVTy0->getNumElements(); I != E; ++I) {
3347
0
        Constant *Lane = Operands[0]->getAggregateElement(I);
3348
0
        std::tie(Results0[I], Results1[I]) =
3349
0
            ConstantFoldScalarFrexpCall(Lane, Ty1);
3350
0
        if (!Results0[I])
3351
0
          return nullptr;
3352
0
      }
3353
3354
0
      return ConstantStruct::get(StTy, ConstantVector::get(Results0),
3355
0
                                 ConstantVector::get(Results1));
3356
0
    }
3357
3358
0
    auto [Result0, Result1] = ConstantFoldScalarFrexpCall(Operands[0], Ty1);
3359
0
    if (!Result0)
3360
0
      return nullptr;
3361
0
    return ConstantStruct::get(StTy, Result0, Result1);
3362
0
  }
3363
323
  default:
3364
    // TODO: Constant folding of vector intrinsics that fall through here does
3365
    // not work (e.g. overflow intrinsics)
3366
323
    return ConstantFoldScalarCall(Name, IntrinsicID, StTy, Operands, TLI, Call);
3367
323
  }
3368
3369
0
  return nullptr;
3370
323
}
3371
3372
} // end anonymous namespace
3373
3374
Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F,
3375
                                 ArrayRef<Constant *> Operands,
3376
18.6k
                                 const TargetLibraryInfo *TLI) {
3377
18.6k
  if (Call->isNoBuiltin())
3378
0
    return nullptr;
3379
18.6k
  if (!F->hasName())
3380
0
    return nullptr;
3381
3382
  // If this is not an intrinsic and not recognized as a library call, bail out.
3383
18.6k
  Intrinsic::ID IID = F->getIntrinsicID();
3384
18.6k
  if (IID == Intrinsic::not_intrinsic) {
3385
6.86k
    if (!TLI)
3386
36
      return nullptr;
3387
6.82k
    LibFunc LibF;
3388
6.82k
    if (!TLI->getLibFunc(*F, LibF))
3389
65
      return nullptr;
3390
6.82k
  }
3391
3392
18.5k
  StringRef Name = F->getName();
3393
18.5k
  Type *Ty = F->getReturnType();
3394
18.5k
  if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
3395
1.34k
    return ConstantFoldFixedVectorCall(
3396
1.34k
        Name, IID, FVTy, Operands, F->getParent()->getDataLayout(), TLI, Call);
3397
3398
17.2k
  if (auto *SVTy = dyn_cast<ScalableVectorType>(Ty))
3399
0
    return ConstantFoldScalableVectorCall(
3400
0
        Name, IID, SVTy, Operands, F->getParent()->getDataLayout(), TLI, Call);
3401
3402
17.2k
  if (auto *StTy = dyn_cast<StructType>(Ty))
3403
323
    return ConstantFoldStructCall(Name, IID, StTy, Operands,
3404
323
                                  F->getParent()->getDataLayout(), TLI, Call);
3405
3406
  // TODO: If this is a library function, we already discovered that above,
3407
  //       so we should pass the LibFunc, not the name (and it might be better
3408
  //       still to separate intrinsic handling from libcalls).
3409
16.8k
  return ConstantFoldScalarCall(Name, IID, Ty, Operands, TLI, Call);
3410
17.2k
}
3411
3412
bool llvm::isMathLibCallNoop(const CallBase *Call,
3413
11.2k
                             const TargetLibraryInfo *TLI) {
3414
  // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
3415
  // (and to some extent ConstantFoldScalarCall).
3416
11.2k
  if (Call->isNoBuiltin() || Call->isStrictFP())
3417
0
    return false;
3418
11.2k
  Function *F = Call->getCalledFunction();
3419
11.2k
  if (!F)
3420
0
    return false;
3421
3422
11.2k
  LibFunc Func;
3423
11.2k
  if (!TLI || !TLI->getLibFunc(*F, Func))
3424
11.1k
    return false;
3425
3426
110
  if (Call->arg_size() == 1) {
3427
0
    if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
3428
0
      const APFloat &Op = OpC->getValueAPF();
3429
0
      switch (Func) {
3430
0
      case LibFunc_logl:
3431
0
      case LibFunc_log:
3432
0
      case LibFunc_logf:
3433
0
      case LibFunc_log2l:
3434
0
      case LibFunc_log2:
3435
0
      case LibFunc_log2f:
3436
0
      case LibFunc_log10l:
3437
0
      case LibFunc_log10:
3438
0
      case LibFunc_log10f:
3439
0
        return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
3440
3441
0
      case LibFunc_expl:
3442
0
      case LibFunc_exp:
3443
0
      case LibFunc_expf:
3444
        // FIXME: These boundaries are slightly conservative.
3445
0
        if (OpC->getType()->isDoubleTy())
3446
0
          return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
3447
0
        if (OpC->getType()->isFloatTy())
3448
0
          return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
3449
0
        break;
3450
3451
0
      case LibFunc_exp2l:
3452
0
      case LibFunc_exp2:
3453
0
      case LibFunc_exp2f:
3454
        // FIXME: These boundaries are slightly conservative.
3455
0
        if (OpC->getType()->isDoubleTy())
3456
0
          return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
3457
0
        if (OpC->getType()->isFloatTy())
3458
0
          return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
3459
0
        break;
3460
3461
0
      case LibFunc_sinl:
3462
0
      case LibFunc_sin:
3463
0
      case LibFunc_sinf:
3464
0
      case LibFunc_cosl:
3465
0
      case LibFunc_cos:
3466
0
      case LibFunc_cosf:
3467
0
        return !Op.isInfinity();
3468
3469
0
      case LibFunc_tanl:
3470
0
      case LibFunc_tan:
3471
0
      case LibFunc_tanf: {
3472
        // FIXME: Stop using the host math library.
3473
        // FIXME: The computation isn't done in the right precision.
3474
0
        Type *Ty = OpC->getType();
3475
0
        if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy())
3476
0
          return ConstantFoldFP(tan, OpC->getValueAPF(), Ty) != nullptr;
3477
0
        break;
3478
0
      }
3479
3480
0
      case LibFunc_atan:
3481
0
      case LibFunc_atanf:
3482
0
      case LibFunc_atanl:
3483
        // Per POSIX, this MAY fail if Op is denormal. We choose not failing.
3484
0
        return true;
3485
3486
3487
0
      case LibFunc_asinl:
3488
0
      case LibFunc_asin:
3489
0
      case LibFunc_asinf:
3490
0
      case LibFunc_acosl:
3491
0
      case LibFunc_acos:
3492
0
      case LibFunc_acosf:
3493
0
        return !(Op < APFloat(Op.getSemantics(), "-1") ||
3494
0
                 Op > APFloat(Op.getSemantics(), "1"));
3495
3496
0
      case LibFunc_sinh:
3497
0
      case LibFunc_cosh:
3498
0
      case LibFunc_sinhf:
3499
0
      case LibFunc_coshf:
3500
0
      case LibFunc_sinhl:
3501
0
      case LibFunc_coshl:
3502
        // FIXME: These boundaries are slightly conservative.
3503
0
        if (OpC->getType()->isDoubleTy())
3504
0
          return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
3505
0
        if (OpC->getType()->isFloatTy())
3506
0
          return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
3507
0
        break;
3508
3509
0
      case LibFunc_sqrtl:
3510
0
      case LibFunc_sqrt:
3511
0
      case LibFunc_sqrtf:
3512
0
        return Op.isNaN() || Op.isZero() || !Op.isNegative();
3513
3514
      // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
3515
      // maybe others?
3516
0
      default:
3517
0
        break;
3518
0
      }
3519
0
    }
3520
0
  }
3521
3522
110
  if (Call->arg_size() == 2) {
3523
62
    ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
3524
62
    ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
3525
62
    if (Op0C && Op1C) {
3526
0
      const APFloat &Op0 = Op0C->getValueAPF();
3527
0
      const APFloat &Op1 = Op1C->getValueAPF();
3528
3529
0
      switch (Func) {
3530
0
      case LibFunc_powl:
3531
0
      case LibFunc_pow:
3532
0
      case LibFunc_powf: {
3533
        // FIXME: Stop using the host math library.
3534
        // FIXME: The computation isn't done in the right precision.
3535
0
        Type *Ty = Op0C->getType();
3536
0
        if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
3537
0
          if (Ty == Op1C->getType())
3538
0
            return ConstantFoldBinaryFP(pow, Op0, Op1, Ty) != nullptr;
3539
0
        }
3540
0
        break;
3541
0
      }
3542
3543
0
      case LibFunc_fmodl:
3544
0
      case LibFunc_fmod:
3545
0
      case LibFunc_fmodf:
3546
0
      case LibFunc_remainderl:
3547
0
      case LibFunc_remainder:
3548
0
      case LibFunc_remainderf:
3549
0
        return Op0.isNaN() || Op1.isNaN() ||
3550
0
               (!Op0.isInfinity() && !Op1.isZero());
3551
3552
0
      case LibFunc_atan2:
3553
0
      case LibFunc_atan2f:
3554
0
      case LibFunc_atan2l:
3555
        // Although IEEE-754 says atan2(+/-0.0, +/-0.0) are well-defined, and
3556
        // GLIBC and MSVC do not appear to raise an error on those, we
3557
        // cannot rely on that behavior. POSIX and C11 say that a domain error
3558
        // may occur, so allow for that possibility.
3559
0
        return !Op0.isZero() || !Op1.isZero();
3560
3561
0
      default:
3562
0
        break;
3563
0
      }
3564
0
    }
3565
62
  }
3566
3567
110
  return false;
3568
110
}
3569
3570
0
void TargetFolder::anchor() {}