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/Constants.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalValue.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/InstrTypes.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/IntrinsicInst.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/IntrinsicsAMDGPU.h"
45 #include "llvm/IR/IntrinsicsARM.h"
46 #include "llvm/IR/IntrinsicsWebAssembly.h"
47 #include "llvm/IR/IntrinsicsX86.h"
48 #include "llvm/IR/Operator.h"
49 #include "llvm/IR/Type.h"
50 #include "llvm/IR/Value.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/KnownBits.h"
54 #include "llvm/Support/MathExtras.h"
55 #include <cassert>
56 #include <cerrno>
57 #include <cfenv>
58 #include <cmath>
59 #include <cstddef>
60 #include <cstdint>
61 
62 using namespace llvm;
63 
64 namespace {
65 
66 //===----------------------------------------------------------------------===//
67 // Constant Folding internal helper functions
68 //===----------------------------------------------------------------------===//
69 
70 static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
71                                         Constant *C, Type *SrcEltTy,
72                                         unsigned NumSrcElts,
73                                         const DataLayout &DL) {
74   // Now that we know that the input value is a vector of integers, just shift
75   // and insert them into our result.
76   unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
77   for (unsigned i = 0; i != NumSrcElts; ++i) {
78     Constant *Element;
79     if (DL.isLittleEndian())
80       Element = C->getAggregateElement(NumSrcElts - i - 1);
81     else
82       Element = C->getAggregateElement(i);
83 
84     if (Element && isa<UndefValue>(Element)) {
85       Result <<= BitShift;
86       continue;
87     }
88 
89     auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
90     if (!ElementCI)
91       return ConstantExpr::getBitCast(C, DestTy);
92 
93     Result <<= BitShift;
94     Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
95   }
96 
97   return nullptr;
98 }
99 
100 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
101 /// This always returns a non-null constant, but it may be a
102 /// ConstantExpr if unfoldable.
103 Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
104   assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) &&
105          "Invalid constantexpr bitcast!");
106 
107   // Catch the obvious splat cases.
108   if (C->isNullValue() && !DestTy->isX86_MMXTy())
109     return Constant::getNullValue(DestTy);
110   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
111       !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
112     return Constant::getAllOnesValue(DestTy);
113 
114   if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
115     // Handle a vector->scalar integer/fp cast.
116     if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
117       unsigned NumSrcElts = cast<FixedVectorType>(VTy)->getNumElements();
118       Type *SrcEltTy = VTy->getElementType();
119 
120       // If the vector is a vector of floating point, convert it to vector of int
121       // to simplify things.
122       if (SrcEltTy->isFloatingPointTy()) {
123         unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
124         auto *SrcIVTy = FixedVectorType::get(
125             IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
126         // Ask IR to do the conversion now that #elts line up.
127         C = ConstantExpr::getBitCast(C, SrcIVTy);
128       }
129 
130       APInt Result(DL.getTypeSizeInBits(DestTy), 0);
131       if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
132                                                 SrcEltTy, NumSrcElts, DL))
133         return CE;
134 
135       if (isa<IntegerType>(DestTy))
136         return ConstantInt::get(DestTy, Result);
137 
138       APFloat FP(DestTy->getFltSemantics(), Result);
139       return ConstantFP::get(DestTy->getContext(), FP);
140     }
141   }
142 
143   // The code below only handles casts to vectors currently.
144   auto *DestVTy = dyn_cast<VectorType>(DestTy);
145   if (!DestVTy)
146     return ConstantExpr::getBitCast(C, DestTy);
147 
148   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
149   // vector so the code below can handle it uniformly.
150   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
151     Constant *Ops = C; // don't take the address of C!
152     return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
153   }
154 
155   // If this is a bitcast from constant vector -> vector, fold it.
156   if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
157     return ConstantExpr::getBitCast(C, DestTy);
158 
159   // If the element types match, IR can fold it.
160   unsigned NumDstElt = cast<FixedVectorType>(DestVTy)->getNumElements();
161   unsigned NumSrcElt = cast<FixedVectorType>(C->getType())->getNumElements();
162   if (NumDstElt == NumSrcElt)
163     return ConstantExpr::getBitCast(C, DestTy);
164 
165   Type *SrcEltTy = cast<VectorType>(C->getType())->getElementType();
166   Type *DstEltTy = DestVTy->getElementType();
167 
168   // Otherwise, we're changing the number of elements in a vector, which
169   // requires endianness information to do the right thing.  For example,
170   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
171   // folds to (little endian):
172   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
173   // and to (big endian):
174   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
175 
176   // First thing is first.  We only want to think about integer here, so if
177   // we have something in FP form, recast it as integer.
178   if (DstEltTy->isFloatingPointTy()) {
179     // Fold to an vector of integers with same size as our FP type.
180     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
181     auto *DestIVTy = FixedVectorType::get(
182         IntegerType::get(C->getContext(), FPWidth), NumDstElt);
183     // Recursively handle this integer conversion, if possible.
184     C = FoldBitCast(C, DestIVTy, DL);
185 
186     // Finally, IR can handle this now that #elts line up.
187     return ConstantExpr::getBitCast(C, DestTy);
188   }
189 
190   // Okay, we know the destination is integer, if the input is FP, convert
191   // it to integer first.
192   if (SrcEltTy->isFloatingPointTy()) {
193     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
194     auto *SrcIVTy = FixedVectorType::get(
195         IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
196     // Ask IR to do the conversion now that #elts line up.
197     C = ConstantExpr::getBitCast(C, SrcIVTy);
198     // If IR wasn't able to fold it, bail out.
199     if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
200         !isa<ConstantDataVector>(C))
201       return C;
202   }
203 
204   // Now we know that the input and output vectors are both integer vectors
205   // of the same size, and that their #elements is not the same.  Do the
206   // conversion here, which depends on whether the input or output has
207   // more elements.
208   bool isLittleEndian = DL.isLittleEndian();
209 
210   SmallVector<Constant*, 32> Result;
211   if (NumDstElt < NumSrcElt) {
212     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
213     Constant *Zero = Constant::getNullValue(DstEltTy);
214     unsigned Ratio = NumSrcElt/NumDstElt;
215     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
216     unsigned SrcElt = 0;
217     for (unsigned i = 0; i != NumDstElt; ++i) {
218       // Build each element of the result.
219       Constant *Elt = Zero;
220       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
221       for (unsigned j = 0; j != Ratio; ++j) {
222         Constant *Src = C->getAggregateElement(SrcElt++);
223         if (Src && isa<UndefValue>(Src))
224           Src = Constant::getNullValue(
225               cast<VectorType>(C->getType())->getElementType());
226         else
227           Src = dyn_cast_or_null<ConstantInt>(Src);
228         if (!Src)  // Reject constantexpr elements.
229           return ConstantExpr::getBitCast(C, DestTy);
230 
231         // Zero extend the element to the right size.
232         Src = ConstantExpr::getZExt(Src, Elt->getType());
233 
234         // Shift it to the right place, depending on endianness.
235         Src = ConstantExpr::getShl(Src,
236                                    ConstantInt::get(Src->getType(), ShiftAmt));
237         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
238 
239         // Mix it in.
240         Elt = ConstantExpr::getOr(Elt, Src);
241       }
242       Result.push_back(Elt);
243     }
244     return ConstantVector::get(Result);
245   }
246 
247   // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
248   unsigned Ratio = NumDstElt/NumSrcElt;
249   unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
250 
251   // Loop over each source value, expanding into multiple results.
252   for (unsigned i = 0; i != NumSrcElt; ++i) {
253     auto *Element = C->getAggregateElement(i);
254 
255     if (!Element) // Reject constantexpr elements.
256       return ConstantExpr::getBitCast(C, DestTy);
257 
258     if (isa<UndefValue>(Element)) {
259       // Correctly Propagate undef values.
260       Result.append(Ratio, UndefValue::get(DstEltTy));
261       continue;
262     }
263 
264     auto *Src = dyn_cast<ConstantInt>(Element);
265     if (!Src)
266       return ConstantExpr::getBitCast(C, DestTy);
267 
268     unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
269     for (unsigned j = 0; j != Ratio; ++j) {
270       // Shift the piece of the value into the right place, depending on
271       // endianness.
272       Constant *Elt = ConstantExpr::getLShr(Src,
273                                   ConstantInt::get(Src->getType(), ShiftAmt));
274       ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
275 
276       // Truncate the element to an integer with the same pointer size and
277       // convert the element back to a pointer using a inttoptr.
278       if (DstEltTy->isPointerTy()) {
279         IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
280         Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
281         Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
282         continue;
283       }
284 
285       // Truncate and remember this piece.
286       Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
287     }
288   }
289 
290   return ConstantVector::get(Result);
291 }
292 
293 } // end anonymous namespace
294 
295 /// If this constant is a constant offset from a global, return the global and
296 /// the constant. Because of constantexprs, this function is recursive.
297 bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
298                                       APInt &Offset, const DataLayout &DL) {
299   // Trivial case, constant is the global.
300   if ((GV = dyn_cast<GlobalValue>(C))) {
301     unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType());
302     Offset = APInt(BitWidth, 0);
303     return true;
304   }
305 
306   // Otherwise, if this isn't a constant expr, bail out.
307   auto *CE = dyn_cast<ConstantExpr>(C);
308   if (!CE) return false;
309 
310   // Look through ptr->int and ptr->ptr casts.
311   if (CE->getOpcode() == Instruction::PtrToInt ||
312       CE->getOpcode() == Instruction::BitCast)
313     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
314 
315   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
316   auto *GEP = dyn_cast<GEPOperator>(CE);
317   if (!GEP)
318     return false;
319 
320   unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType());
321   APInt TmpOffset(BitWidth, 0);
322 
323   // If the base isn't a global+constant, we aren't either.
324   if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
325     return false;
326 
327   // Otherwise, add any offset that our operands provide.
328   if (!GEP->accumulateConstantOffset(DL, TmpOffset))
329     return false;
330 
331   Offset = TmpOffset;
332   return true;
333 }
334 
335 Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy,
336                                          const DataLayout &DL) {
337   do {
338     Type *SrcTy = C->getType();
339     uint64_t DestSize = DL.getTypeSizeInBits(DestTy);
340     uint64_t SrcSize = DL.getTypeSizeInBits(SrcTy);
341     if (SrcSize < DestSize)
342       return nullptr;
343 
344     // Catch the obvious splat cases (since all-zeros can coerce non-integral
345     // pointers legally).
346     if (C->isNullValue() && !DestTy->isX86_MMXTy())
347       return Constant::getNullValue(DestTy);
348     if (C->isAllOnesValue() &&
349         (DestTy->isIntegerTy() || DestTy->isFloatingPointTy() ||
350          DestTy->isVectorTy()) &&
351         !DestTy->isX86_MMXTy() && !DestTy->isPtrOrPtrVectorTy())
352       // Get ones when the input is trivial, but
353       // only for supported types inside getAllOnesValue.
354       return Constant::getAllOnesValue(DestTy);
355 
356     // If the type sizes are the same and a cast is legal, just directly
357     // cast the constant.
358     // But be careful not to coerce non-integral pointers illegally.
359     if (SrcSize == DestSize &&
360         DL.isNonIntegralPointerType(SrcTy->getScalarType()) ==
361             DL.isNonIntegralPointerType(DestTy->getScalarType())) {
362       Instruction::CastOps Cast = Instruction::BitCast;
363       // If we are going from a pointer to int or vice versa, we spell the cast
364       // differently.
365       if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
366         Cast = Instruction::IntToPtr;
367       else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
368         Cast = Instruction::PtrToInt;
369 
370       if (CastInst::castIsValid(Cast, C, DestTy))
371         return ConstantExpr::getCast(Cast, C, DestTy);
372     }
373 
374     // If this isn't an aggregate type, there is nothing we can do to drill down
375     // and find a bitcastable constant.
376     if (!SrcTy->isAggregateType())
377       return nullptr;
378 
379     // We're simulating a load through a pointer that was bitcast to point to
380     // a different type, so we can try to walk down through the initial
381     // elements of an aggregate to see if some part of the aggregate is
382     // castable to implement the "load" semantic model.
383     if (SrcTy->isStructTy()) {
384       // Struct types might have leading zero-length elements like [0 x i32],
385       // which are certainly not what we are looking for, so skip them.
386       unsigned Elem = 0;
387       Constant *ElemC;
388       do {
389         ElemC = C->getAggregateElement(Elem++);
390       } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()).isZero());
391       C = ElemC;
392     } else {
393       C = C->getAggregateElement(0u);
394     }
395   } while (C);
396 
397   return nullptr;
398 }
399 
400 namespace {
401 
402 /// Recursive helper to read bits out of global. C is the constant being copied
403 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
404 /// results into and BytesLeft is the number of bytes left in
405 /// the CurPtr buffer. DL is the DataLayout.
406 bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
407                         unsigned BytesLeft, const DataLayout &DL) {
408   assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
409          "Out of range access");
410 
411   // If this element is zero or undefined, we can just return since *CurPtr is
412   // zero initialized.
413   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
414     return true;
415 
416   if (auto *CI = dyn_cast<ConstantInt>(C)) {
417     if (CI->getBitWidth() > 64 ||
418         (CI->getBitWidth() & 7) != 0)
419       return false;
420 
421     uint64_t Val = CI->getZExtValue();
422     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
423 
424     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
425       int n = ByteOffset;
426       if (!DL.isLittleEndian())
427         n = IntBytes - n - 1;
428       CurPtr[i] = (unsigned char)(Val >> (n * 8));
429       ++ByteOffset;
430     }
431     return true;
432   }
433 
434   if (auto *CFP = dyn_cast<ConstantFP>(C)) {
435     if (CFP->getType()->isDoubleTy()) {
436       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
437       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
438     }
439     if (CFP->getType()->isFloatTy()){
440       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
441       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
442     }
443     if (CFP->getType()->isHalfTy()){
444       C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
445       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
446     }
447     return false;
448   }
449 
450   if (auto *CS = dyn_cast<ConstantStruct>(C)) {
451     const StructLayout *SL = DL.getStructLayout(CS->getType());
452     unsigned Index = SL->getElementContainingOffset(ByteOffset);
453     uint64_t CurEltOffset = SL->getElementOffset(Index);
454     ByteOffset -= CurEltOffset;
455 
456     while (true) {
457       // If the element access is to the element itself and not to tail padding,
458       // read the bytes from the element.
459       uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
460 
461       if (ByteOffset < EltSize &&
462           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
463                               BytesLeft, DL))
464         return false;
465 
466       ++Index;
467 
468       // Check to see if we read from the last struct element, if so we're done.
469       if (Index == CS->getType()->getNumElements())
470         return true;
471 
472       // If we read all of the bytes we needed from this element we're done.
473       uint64_t NextEltOffset = SL->getElementOffset(Index);
474 
475       if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
476         return true;
477 
478       // Move to the next element of the struct.
479       CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
480       BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
481       ByteOffset = 0;
482       CurEltOffset = NextEltOffset;
483     }
484     // not reached.
485   }
486 
487   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
488       isa<ConstantDataSequential>(C)) {
489     uint64_t NumElts;
490     Type *EltTy;
491     if (auto *AT = dyn_cast<ArrayType>(C->getType())) {
492       NumElts = AT->getNumElements();
493       EltTy = AT->getElementType();
494     } else {
495       NumElts = cast<FixedVectorType>(C->getType())->getNumElements();
496       EltTy = cast<FixedVectorType>(C->getType())->getElementType();
497     }
498     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
499     uint64_t Index = ByteOffset / EltSize;
500     uint64_t Offset = ByteOffset - Index * EltSize;
501 
502     for (; Index != NumElts; ++Index) {
503       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
504                               BytesLeft, DL))
505         return false;
506 
507       uint64_t BytesWritten = EltSize - Offset;
508       assert(BytesWritten <= EltSize && "Not indexing into this element?");
509       if (BytesWritten >= BytesLeft)
510         return true;
511 
512       Offset = 0;
513       BytesLeft -= BytesWritten;
514       CurPtr += BytesWritten;
515     }
516     return true;
517   }
518 
519   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
520     if (CE->getOpcode() == Instruction::IntToPtr &&
521         CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
522       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
523                                 BytesLeft, DL);
524     }
525   }
526 
527   // Otherwise, unknown initializer type.
528   return false;
529 }
530 
531 Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
532                                           const DataLayout &DL) {
533   // Bail out early. Not expect to load from scalable global variable.
534   if (isa<ScalableVectorType>(LoadTy))
535     return nullptr;
536 
537   auto *PTy = cast<PointerType>(C->getType());
538   auto *IntType = dyn_cast<IntegerType>(LoadTy);
539 
540   // If this isn't an integer load we can't fold it directly.
541   if (!IntType) {
542     unsigned AS = PTy->getAddressSpace();
543 
544     // If this is a float/double load, we can try folding it as an int32/64 load
545     // and then bitcast the result.  This can be useful for union cases.  Note
546     // that address spaces don't matter here since we're not going to result in
547     // an actual new load.
548     Type *MapTy;
549     if (LoadTy->isHalfTy())
550       MapTy = Type::getInt16Ty(C->getContext());
551     else if (LoadTy->isFloatTy())
552       MapTy = Type::getInt32Ty(C->getContext());
553     else if (LoadTy->isDoubleTy())
554       MapTy = Type::getInt64Ty(C->getContext());
555     else if (LoadTy->isVectorTy()) {
556       MapTy = PointerType::getIntNTy(
557           C->getContext(), DL.getTypeSizeInBits(LoadTy).getFixedSize());
558     } else
559       return nullptr;
560 
561     C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
562     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL)) {
563       if (Res->isNullValue() && !LoadTy->isX86_MMXTy())
564         // Materializing a zero can be done trivially without a bitcast
565         return Constant::getNullValue(LoadTy);
566       Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy;
567       Res = FoldBitCast(Res, CastTy, DL);
568       if (LoadTy->isPtrOrPtrVectorTy()) {
569         // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr
570         if (Res->isNullValue() && !LoadTy->isX86_MMXTy())
571           return Constant::getNullValue(LoadTy);
572         if (DL.isNonIntegralPointerType(LoadTy->getScalarType()))
573           // Be careful not to replace a load of an addrspace value with an inttoptr here
574           return nullptr;
575         Res = ConstantExpr::getCast(Instruction::IntToPtr, Res, LoadTy);
576       }
577       return Res;
578     }
579     return nullptr;
580   }
581 
582   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
583   if (BytesLoaded > 32 || BytesLoaded == 0)
584     return nullptr;
585 
586   GlobalValue *GVal;
587   APInt OffsetAI;
588   if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
589     return nullptr;
590 
591   auto *GV = dyn_cast<GlobalVariable>(GVal);
592   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
593       !GV->getInitializer()->getType()->isSized())
594     return nullptr;
595 
596   int64_t Offset = OffsetAI.getSExtValue();
597   int64_t InitializerSize =
598       DL.getTypeAllocSize(GV->getInitializer()->getType()).getFixedSize();
599 
600   // If we're not accessing anything in this constant, the result is undefined.
601   if (Offset <= -1 * static_cast<int64_t>(BytesLoaded))
602     return UndefValue::get(IntType);
603 
604   // If we're not accessing anything in this constant, the result is undefined.
605   if (Offset >= InitializerSize)
606     return UndefValue::get(IntType);
607 
608   unsigned char RawBytes[32] = {0};
609   unsigned char *CurPtr = RawBytes;
610   unsigned BytesLeft = BytesLoaded;
611 
612   // If we're loading off the beginning of the global, some bytes may be valid.
613   if (Offset < 0) {
614     CurPtr += -Offset;
615     BytesLeft += Offset;
616     Offset = 0;
617   }
618 
619   if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
620     return nullptr;
621 
622   APInt ResultVal = APInt(IntType->getBitWidth(), 0);
623   if (DL.isLittleEndian()) {
624     ResultVal = RawBytes[BytesLoaded - 1];
625     for (unsigned i = 1; i != BytesLoaded; ++i) {
626       ResultVal <<= 8;
627       ResultVal |= RawBytes[BytesLoaded - 1 - i];
628     }
629   } else {
630     ResultVal = RawBytes[0];
631     for (unsigned i = 1; i != BytesLoaded; ++i) {
632       ResultVal <<= 8;
633       ResultVal |= RawBytes[i];
634     }
635   }
636 
637   return ConstantInt::get(IntType->getContext(), ResultVal);
638 }
639 
640 Constant *ConstantFoldLoadThroughBitcastExpr(ConstantExpr *CE, Type *DestTy,
641                                              const DataLayout &DL) {
642   auto *SrcPtr = CE->getOperand(0);
643   auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
644   if (!SrcPtrTy)
645     return nullptr;
646   Type *SrcTy = SrcPtrTy->getPointerElementType();
647 
648   Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
649   if (!C)
650     return nullptr;
651 
652   return llvm::ConstantFoldLoadThroughBitcast(C, DestTy, DL);
653 }
654 
655 } // end anonymous namespace
656 
657 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
658                                              const DataLayout &DL) {
659   // First, try the easy cases:
660   if (auto *GV = dyn_cast<GlobalVariable>(C))
661     if (GV->isConstant() && GV->hasDefinitiveInitializer())
662       return GV->getInitializer();
663 
664   if (auto *GA = dyn_cast<GlobalAlias>(C))
665     if (GA->getAliasee() && !GA->isInterposable())
666       return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
667 
668   // If the loaded value isn't a constant expr, we can't handle it.
669   auto *CE = dyn_cast<ConstantExpr>(C);
670   if (!CE)
671     return nullptr;
672 
673   if (CE->getOpcode() == Instruction::GetElementPtr) {
674     if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
675       if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
676         if (Constant *V =
677              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
678           return V;
679       }
680     }
681   }
682 
683   if (CE->getOpcode() == Instruction::BitCast)
684     if (Constant *LoadedC = ConstantFoldLoadThroughBitcastExpr(CE, Ty, DL))
685       return LoadedC;
686 
687   // Instead of loading constant c string, use corresponding integer value
688   // directly if string length is small enough.
689   StringRef Str;
690   if (getConstantStringInfo(CE, Str) && !Str.empty()) {
691     size_t StrLen = Str.size();
692     unsigned NumBits = Ty->getPrimitiveSizeInBits();
693     // Replace load with immediate integer if the result is an integer or fp
694     // value.
695     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
696         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
697       APInt StrVal(NumBits, 0);
698       APInt SingleChar(NumBits, 0);
699       if (DL.isLittleEndian()) {
700         for (unsigned char C : reverse(Str.bytes())) {
701           SingleChar = static_cast<uint64_t>(C);
702           StrVal = (StrVal << 8) | SingleChar;
703         }
704       } else {
705         for (unsigned char C : Str.bytes()) {
706           SingleChar = static_cast<uint64_t>(C);
707           StrVal = (StrVal << 8) | SingleChar;
708         }
709         // Append NULL at the end.
710         SingleChar = 0;
711         StrVal = (StrVal << 8) | SingleChar;
712       }
713 
714       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
715       if (Ty->isFloatingPointTy())
716         Res = ConstantExpr::getBitCast(Res, Ty);
717       return Res;
718     }
719   }
720 
721   // If this load comes from anywhere in a constant global, and if the global
722   // is all undef or zero, we know what it loads.
723   if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(CE))) {
724     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
725       if (GV->getInitializer()->isNullValue())
726         return Constant::getNullValue(Ty);
727       if (isa<UndefValue>(GV->getInitializer()))
728         return UndefValue::get(Ty);
729     }
730   }
731 
732   // Try hard to fold loads from bitcasted strange and non-type-safe things.
733   return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
734 }
735 
736 namespace {
737 
738 Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
739   if (LI->isVolatile()) return nullptr;
740 
741   if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
742     return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
743 
744   return nullptr;
745 }
746 
747 /// One of Op0/Op1 is a constant expression.
748 /// Attempt to symbolically evaluate the result of a binary operator merging
749 /// these together.  If target data info is available, it is provided as DL,
750 /// otherwise DL is null.
751 Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
752                                     const DataLayout &DL) {
753   // SROA
754 
755   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
756   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
757   // bits.
758 
759   if (Opc == Instruction::And) {
760     KnownBits Known0 = computeKnownBits(Op0, DL);
761     KnownBits Known1 = computeKnownBits(Op1, DL);
762     if ((Known1.One | Known0.Zero).isAllOnesValue()) {
763       // All the bits of Op0 that the 'and' could be masking are already zero.
764       return Op0;
765     }
766     if ((Known0.One | Known1.Zero).isAllOnesValue()) {
767       // All the bits of Op1 that the 'and' could be masking are already zero.
768       return Op1;
769     }
770 
771     Known0 &= Known1;
772     if (Known0.isConstant())
773       return ConstantInt::get(Op0->getType(), Known0.getConstant());
774   }
775 
776   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
777   // constant.  This happens frequently when iterating over a global array.
778   if (Opc == Instruction::Sub) {
779     GlobalValue *GV1, *GV2;
780     APInt Offs1, Offs2;
781 
782     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
783       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
784         unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
785 
786         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
787         // PtrToInt may change the bitwidth so we have convert to the right size
788         // first.
789         return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
790                                                 Offs2.zextOrTrunc(OpSize));
791       }
792   }
793 
794   return nullptr;
795 }
796 
797 /// If array indices are not pointer-sized integers, explicitly cast them so
798 /// that they aren't implicitly casted by the getelementptr.
799 Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
800                          Type *ResultTy, Optional<unsigned> InRangeIndex,
801                          const DataLayout &DL, const TargetLibraryInfo *TLI) {
802   Type *IntIdxTy = DL.getIndexType(ResultTy);
803   Type *IntIdxScalarTy = IntIdxTy->getScalarType();
804 
805   bool Any = false;
806   SmallVector<Constant*, 32> NewIdxs;
807   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
808     if ((i == 1 ||
809          !isa<StructType>(GetElementPtrInst::getIndexedType(
810              SrcElemTy, Ops.slice(1, i - 1)))) &&
811         Ops[i]->getType()->getScalarType() != IntIdxScalarTy) {
812       Any = true;
813       Type *NewType = Ops[i]->getType()->isVectorTy()
814                           ? IntIdxTy
815                           : IntIdxScalarTy;
816       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
817                                                                       true,
818                                                                       NewType,
819                                                                       true),
820                                               Ops[i], NewType));
821     } else
822       NewIdxs.push_back(Ops[i]);
823   }
824 
825   if (!Any)
826     return nullptr;
827 
828   Constant *C = ConstantExpr::getGetElementPtr(
829       SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
830   return ConstantFoldConstant(C, DL, TLI);
831 }
832 
833 /// Strip the pointer casts, but preserve the address space information.
834 Constant *StripPtrCastKeepAS(Constant *Ptr, Type *&ElemTy) {
835   assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
836   auto *OldPtrTy = cast<PointerType>(Ptr->getType());
837   Ptr = cast<Constant>(Ptr->stripPointerCasts());
838   auto *NewPtrTy = cast<PointerType>(Ptr->getType());
839 
840   ElemTy = NewPtrTy->getPointerElementType();
841 
842   // Preserve the address space number of the pointer.
843   if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
844     NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
845     Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
846   }
847   return Ptr;
848 }
849 
850 /// If we can symbolically evaluate the GEP constant expression, do so.
851 Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
852                                   ArrayRef<Constant *> Ops,
853                                   const DataLayout &DL,
854                                   const TargetLibraryInfo *TLI) {
855   const GEPOperator *InnermostGEP = GEP;
856   bool InBounds = GEP->isInBounds();
857 
858   Type *SrcElemTy = GEP->getSourceElementType();
859   Type *ResElemTy = GEP->getResultElementType();
860   Type *ResTy = GEP->getType();
861   if (!SrcElemTy->isSized() || isa<ScalableVectorType>(SrcElemTy))
862     return nullptr;
863 
864   if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
865                                    GEP->getInRangeIndex(), DL, TLI))
866     return C;
867 
868   Constant *Ptr = Ops[0];
869   if (!Ptr->getType()->isPointerTy())
870     return nullptr;
871 
872   Type *IntIdxTy = DL.getIndexType(Ptr->getType());
873 
874   // If this is a constant expr gep that is effectively computing an
875   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
876   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
877       if (!isa<ConstantInt>(Ops[i])) {
878 
879         // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
880         // "inttoptr (sub (ptrtoint Ptr), V)"
881         if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
882           auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
883           assert((!CE || CE->getType() == IntIdxTy) &&
884                  "CastGEPIndices didn't canonicalize index types!");
885           if (CE && CE->getOpcode() == Instruction::Sub &&
886               CE->getOperand(0)->isNullValue()) {
887             Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
888             Res = ConstantExpr::getSub(Res, CE->getOperand(1));
889             Res = ConstantExpr::getIntToPtr(Res, ResTy);
890             return ConstantFoldConstant(Res, DL, TLI);
891           }
892         }
893         return nullptr;
894       }
895 
896   unsigned BitWidth = DL.getTypeSizeInBits(IntIdxTy);
897   APInt Offset =
898       APInt(BitWidth,
899             DL.getIndexedOffsetInType(
900                 SrcElemTy,
901                 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
902   Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
903 
904   // If this is a GEP of a GEP, fold it all into a single GEP.
905   while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
906     InnermostGEP = GEP;
907     InBounds &= GEP->isInBounds();
908 
909     SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
910 
911     // Do not try the incorporate the sub-GEP if some index is not a number.
912     bool AllConstantInt = true;
913     for (Value *NestedOp : NestedOps)
914       if (!isa<ConstantInt>(NestedOp)) {
915         AllConstantInt = false;
916         break;
917       }
918     if (!AllConstantInt)
919       break;
920 
921     Ptr = cast<Constant>(GEP->getOperand(0));
922     SrcElemTy = GEP->getSourceElementType();
923     Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
924     Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
925   }
926 
927   // If the base value for this address is a literal integer value, fold the
928   // getelementptr to the resulting integer value casted to the pointer type.
929   APInt BasePtr(BitWidth, 0);
930   if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
931     if (CE->getOpcode() == Instruction::IntToPtr) {
932       if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
933         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
934     }
935   }
936 
937   auto *PTy = cast<PointerType>(Ptr->getType());
938   if ((Ptr->isNullValue() || BasePtr != 0) &&
939       !DL.isNonIntegralPointerType(PTy)) {
940     Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
941     return ConstantExpr::getIntToPtr(C, ResTy);
942   }
943 
944   // Otherwise form a regular getelementptr. Recompute the indices so that
945   // we eliminate over-indexing of the notional static type array bounds.
946   // This makes it easy to determine if the getelementptr is "inbounds".
947   // Also, this helps GlobalOpt do SROA on GlobalVariables.
948   Type *Ty = PTy;
949   SmallVector<Constant *, 32> NewIdxs;
950 
951   do {
952     if (!Ty->isStructTy()) {
953       if (Ty->isPointerTy()) {
954         // The only pointer indexing we'll do is on the first index of the GEP.
955         if (!NewIdxs.empty())
956           break;
957 
958         Ty = SrcElemTy;
959 
960         // Only handle pointers to sized types, not pointers to functions.
961         if (!Ty->isSized())
962           return nullptr;
963       } else {
964         Type *NextTy = GetElementPtrInst::getTypeAtIndex(Ty, (uint64_t)0);
965         if (!NextTy)
966           break;
967         Ty = NextTy;
968       }
969 
970       // Determine which element of the array the offset points into.
971       APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
972       if (ElemSize == 0) {
973         // The element size is 0. This may be [0 x Ty]*, so just use a zero
974         // index for this level and proceed to the next level to see if it can
975         // accommodate the offset.
976         NewIdxs.push_back(ConstantInt::get(IntIdxTy, 0));
977       } else {
978         // The element size is non-zero divide the offset by the element
979         // size (rounding down), to compute the index at this level.
980         bool Overflow;
981         APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
982         if (Overflow)
983           break;
984         Offset -= NewIdx * ElemSize;
985         NewIdxs.push_back(ConstantInt::get(IntIdxTy, NewIdx));
986       }
987     } else {
988       auto *STy = cast<StructType>(Ty);
989       // If we end up with an offset that isn't valid for this struct type, we
990       // can't re-form this GEP in a regular form, so bail out. The pointer
991       // operand likely went through casts that are necessary to make the GEP
992       // sensible.
993       const StructLayout &SL = *DL.getStructLayout(STy);
994       if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
995         break;
996 
997       // Determine which field of the struct the offset points into. The
998       // getZExtValue is fine as we've already ensured that the offset is
999       // within the range representable by the StructLayout API.
1000       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
1001       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1002                                          ElIdx));
1003       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
1004       Ty = STy->getTypeAtIndex(ElIdx);
1005     }
1006   } while (Ty != ResElemTy);
1007 
1008   // If we haven't used up the entire offset by descending the static
1009   // type, then the offset is pointing into the middle of an indivisible
1010   // member, so we can't simplify it.
1011   if (Offset != 0)
1012     return nullptr;
1013 
1014   // Preserve the inrange index from the innermost GEP if possible. We must
1015   // have calculated the same indices up to and including the inrange index.
1016   Optional<unsigned> InRangeIndex;
1017   if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
1018     if (SrcElemTy == InnermostGEP->getSourceElementType() &&
1019         NewIdxs.size() > *LastIRIndex) {
1020       InRangeIndex = LastIRIndex;
1021       for (unsigned I = 0; I <= *LastIRIndex; ++I)
1022         if (NewIdxs[I] != InnermostGEP->getOperand(I + 1))
1023           return nullptr;
1024     }
1025 
1026   // Create a GEP.
1027   Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
1028                                                InBounds, InRangeIndex);
1029   assert(C->getType()->getPointerElementType() == Ty &&
1030          "Computed GetElementPtr has unexpected type!");
1031 
1032   // If we ended up indexing a member with a type that doesn't match
1033   // the type of what the original indices indexed, add a cast.
1034   if (Ty != ResElemTy)
1035     C = FoldBitCast(C, ResTy, DL);
1036 
1037   return C;
1038 }
1039 
1040 /// Attempt to constant fold an instruction with the
1041 /// specified opcode and operands.  If successful, the constant result is
1042 /// returned, if not, null is returned.  Note that this function can fail when
1043 /// attempting to fold instructions like loads and stores, which have no
1044 /// constant expression form.
1045 Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
1046                                        ArrayRef<Constant *> Ops,
1047                                        const DataLayout &DL,
1048                                        const TargetLibraryInfo *TLI) {
1049   Type *DestTy = InstOrCE->getType();
1050 
1051   if (Instruction::isUnaryOp(Opcode))
1052     return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL);
1053 
1054   if (Instruction::isBinaryOp(Opcode))
1055     return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
1056 
1057   if (Instruction::isCast(Opcode))
1058     return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1059 
1060   if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
1061     if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1062       return C;
1063 
1064     return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1065                                           Ops.slice(1), GEP->isInBounds(),
1066                                           GEP->getInRangeIndex());
1067   }
1068 
1069   if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1070     return CE->getWithOperands(Ops);
1071 
1072   switch (Opcode) {
1073   default: return nullptr;
1074   case Instruction::ICmp:
1075   case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1076   case Instruction::Freeze:
1077     return isGuaranteedNotToBeUndefOrPoison(Ops[0]) ? Ops[0] : nullptr;
1078   case Instruction::Call:
1079     if (auto *F = dyn_cast<Function>(Ops.back())) {
1080       const auto *Call = cast<CallBase>(InstOrCE);
1081       if (canConstantFoldCallTo(Call, F))
1082         return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI);
1083     }
1084     return nullptr;
1085   case Instruction::Select:
1086     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1087   case Instruction::ExtractElement:
1088     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1089   case Instruction::ExtractValue:
1090     return ConstantExpr::getExtractValue(
1091         Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices());
1092   case Instruction::InsertElement:
1093     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1094   case Instruction::ShuffleVector:
1095     return ConstantExpr::getShuffleVector(
1096         Ops[0], Ops[1], cast<ShuffleVectorInst>(InstOrCE)->getShuffleMask());
1097   }
1098 }
1099 
1100 } // end anonymous namespace
1101 
1102 //===----------------------------------------------------------------------===//
1103 // Constant Folding public APIs
1104 //===----------------------------------------------------------------------===//
1105 
1106 namespace {
1107 
1108 Constant *
1109 ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1110                          const TargetLibraryInfo *TLI,
1111                          SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1112   if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1113     return const_cast<Constant *>(C);
1114 
1115   SmallVector<Constant *, 8> Ops;
1116   for (const Use &OldU : C->operands()) {
1117     Constant *OldC = cast<Constant>(&OldU);
1118     Constant *NewC = OldC;
1119     // Recursively fold the ConstantExpr's operands. If we have already folded
1120     // a ConstantExpr, we don't have to process it again.
1121     if (isa<ConstantVector>(OldC) || isa<ConstantExpr>(OldC)) {
1122       auto It = FoldedOps.find(OldC);
1123       if (It == FoldedOps.end()) {
1124         NewC = ConstantFoldConstantImpl(OldC, DL, TLI, FoldedOps);
1125         FoldedOps.insert({OldC, NewC});
1126       } else {
1127         NewC = It->second;
1128       }
1129     }
1130     Ops.push_back(NewC);
1131   }
1132 
1133   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1134     if (CE->isCompare())
1135       return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1136                                              DL, TLI);
1137 
1138     return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
1139   }
1140 
1141   assert(isa<ConstantVector>(C));
1142   return ConstantVector::get(Ops);
1143 }
1144 
1145 } // end anonymous namespace
1146 
1147 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
1148                                         const TargetLibraryInfo *TLI) {
1149   // Handle PHI nodes quickly here...
1150   if (auto *PN = dyn_cast<PHINode>(I)) {
1151     Constant *CommonValue = nullptr;
1152 
1153     SmallDenseMap<Constant *, Constant *> FoldedOps;
1154     for (Value *Incoming : PN->incoming_values()) {
1155       // If the incoming value is undef then skip it.  Note that while we could
1156       // skip the value if it is equal to the phi node itself we choose not to
1157       // because that would break the rule that constant folding only applies if
1158       // all operands are constants.
1159       if (isa<UndefValue>(Incoming))
1160         continue;
1161       // If the incoming value is not a constant, then give up.
1162       auto *C = dyn_cast<Constant>(Incoming);
1163       if (!C)
1164         return nullptr;
1165       // Fold the PHI's operands.
1166       C = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1167       // If the incoming value is a different constant to
1168       // the one we saw previously, then give up.
1169       if (CommonValue && C != CommonValue)
1170         return nullptr;
1171       CommonValue = C;
1172     }
1173 
1174     // If we reach here, all incoming values are the same constant or undef.
1175     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
1176   }
1177 
1178   // Scan the operand list, checking to see if they are all constants, if so,
1179   // hand off to ConstantFoldInstOperandsImpl.
1180   if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1181     return nullptr;
1182 
1183   SmallDenseMap<Constant *, Constant *> FoldedOps;
1184   SmallVector<Constant *, 8> Ops;
1185   for (const Use &OpU : I->operands()) {
1186     auto *Op = cast<Constant>(&OpU);
1187     // Fold the Instruction's operands.
1188     Op = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps);
1189     Ops.push_back(Op);
1190   }
1191 
1192   if (const auto *CI = dyn_cast<CmpInst>(I))
1193     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
1194                                            DL, TLI);
1195 
1196   if (const auto *LI = dyn_cast<LoadInst>(I))
1197     return ConstantFoldLoadInst(LI, DL);
1198 
1199   if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
1200     return ConstantExpr::getInsertValue(
1201                                 cast<Constant>(IVI->getAggregateOperand()),
1202                                 cast<Constant>(IVI->getInsertedValueOperand()),
1203                                 IVI->getIndices());
1204   }
1205 
1206   if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
1207     return ConstantExpr::getExtractValue(
1208                                     cast<Constant>(EVI->getAggregateOperand()),
1209                                     EVI->getIndices());
1210   }
1211 
1212   return ConstantFoldInstOperands(I, Ops, DL, TLI);
1213 }
1214 
1215 Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1216                                      const TargetLibraryInfo *TLI) {
1217   SmallDenseMap<Constant *, Constant *> FoldedOps;
1218   return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
1219 }
1220 
1221 Constant *llvm::ConstantFoldInstOperands(Instruction *I,
1222                                          ArrayRef<Constant *> Ops,
1223                                          const DataLayout &DL,
1224                                          const TargetLibraryInfo *TLI) {
1225   return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
1226 }
1227 
1228 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1229                                                 Constant *Ops0, Constant *Ops1,
1230                                                 const DataLayout &DL,
1231                                                 const TargetLibraryInfo *TLI) {
1232   // fold: icmp (inttoptr x), null         -> icmp x, 0
1233   // fold: icmp null, (inttoptr x)         -> icmp 0, x
1234   // fold: icmp (ptrtoint x), 0            -> icmp x, null
1235   // fold: icmp 0, (ptrtoint x)            -> icmp null, x
1236   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1237   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1238   //
1239   // FIXME: The following comment is out of data and the DataLayout is here now.
1240   // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1241   // around to know if bit truncation is happening.
1242   if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1243     if (Ops1->isNullValue()) {
1244       if (CE0->getOpcode() == Instruction::IntToPtr) {
1245         Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1246         // Convert the integer value to the right size to ensure we get the
1247         // proper extension or truncation.
1248         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1249                                                    IntPtrTy, false);
1250         Constant *Null = Constant::getNullValue(C->getType());
1251         return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1252       }
1253 
1254       // Only do this transformation if the int is intptrty in size, otherwise
1255       // there is a truncation or extension that we aren't modeling.
1256       if (CE0->getOpcode() == Instruction::PtrToInt) {
1257         Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1258         if (CE0->getType() == IntPtrTy) {
1259           Constant *C = CE0->getOperand(0);
1260           Constant *Null = Constant::getNullValue(C->getType());
1261           return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1262         }
1263       }
1264     }
1265 
1266     if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1267       if (CE0->getOpcode() == CE1->getOpcode()) {
1268         if (CE0->getOpcode() == Instruction::IntToPtr) {
1269           Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1270 
1271           // Convert the integer value to the right size to ensure we get the
1272           // proper extension or truncation.
1273           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1274                                                       IntPtrTy, false);
1275           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1276                                                       IntPtrTy, false);
1277           return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1278         }
1279 
1280         // Only do this transformation if the int is intptrty in size, otherwise
1281         // there is a truncation or extension that we aren't modeling.
1282         if (CE0->getOpcode() == Instruction::PtrToInt) {
1283           Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1284           if (CE0->getType() == IntPtrTy &&
1285               CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1286             return ConstantFoldCompareInstOperands(
1287                 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1288           }
1289         }
1290       }
1291     }
1292 
1293     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1294     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1295     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1296         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1297       Constant *LHS = ConstantFoldCompareInstOperands(
1298           Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1299       Constant *RHS = ConstantFoldCompareInstOperands(
1300           Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1301       unsigned OpC =
1302         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1303       return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
1304     }
1305   } else if (isa<ConstantExpr>(Ops1)) {
1306     // If RHS is a constant expression, but the left side isn't, swap the
1307     // operands and try again.
1308     Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate);
1309     return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
1310   }
1311 
1312   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1313 }
1314 
1315 Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op,
1316                                            const DataLayout &DL) {
1317   assert(Instruction::isUnaryOp(Opcode));
1318 
1319   return ConstantExpr::get(Opcode, Op);
1320 }
1321 
1322 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1323                                              Constant *RHS,
1324                                              const DataLayout &DL) {
1325   assert(Instruction::isBinaryOp(Opcode));
1326   if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1327     if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1328       return C;
1329 
1330   return ConstantExpr::get(Opcode, LHS, RHS);
1331 }
1332 
1333 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1334                                         Type *DestTy, const DataLayout &DL) {
1335   assert(Instruction::isCast(Opcode));
1336   switch (Opcode) {
1337   default:
1338     llvm_unreachable("Missing case");
1339   case Instruction::PtrToInt:
1340     // If the input is a inttoptr, eliminate the pair.  This requires knowing
1341     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1342     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1343       if (CE->getOpcode() == Instruction::IntToPtr) {
1344         Constant *Input = CE->getOperand(0);
1345         unsigned InWidth = Input->getType()->getScalarSizeInBits();
1346         unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1347         if (PtrWidth < InWidth) {
1348           Constant *Mask =
1349             ConstantInt::get(CE->getContext(),
1350                              APInt::getLowBitsSet(InWidth, PtrWidth));
1351           Input = ConstantExpr::getAnd(Input, Mask);
1352         }
1353         // Do a zext or trunc to get to the dest size.
1354         return ConstantExpr::getIntegerCast(Input, DestTy, false);
1355       }
1356     }
1357     return ConstantExpr::getCast(Opcode, C, DestTy);
1358   case Instruction::IntToPtr:
1359     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1360     // the int size is >= the ptr size and the address spaces are the same.
1361     // This requires knowing the width of a pointer, so it can't be done in
1362     // ConstantExpr::getCast.
1363     if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1364       if (CE->getOpcode() == Instruction::PtrToInt) {
1365         Constant *SrcPtr = CE->getOperand(0);
1366         unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1367         unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1368 
1369         if (MidIntSize >= SrcPtrSize) {
1370           unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1371           if (SrcAS == DestTy->getPointerAddressSpace())
1372             return FoldBitCast(CE->getOperand(0), DestTy, DL);
1373         }
1374       }
1375     }
1376 
1377     return ConstantExpr::getCast(Opcode, C, DestTy);
1378   case Instruction::Trunc:
1379   case Instruction::ZExt:
1380   case Instruction::SExt:
1381   case Instruction::FPTrunc:
1382   case Instruction::FPExt:
1383   case Instruction::UIToFP:
1384   case Instruction::SIToFP:
1385   case Instruction::FPToUI:
1386   case Instruction::FPToSI:
1387   case Instruction::AddrSpaceCast:
1388       return ConstantExpr::getCast(Opcode, C, DestTy);
1389   case Instruction::BitCast:
1390     return FoldBitCast(C, DestTy, DL);
1391   }
1392 }
1393 
1394 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1395                                                        ConstantExpr *CE) {
1396   if (!CE->getOperand(1)->isNullValue())
1397     return nullptr;  // Do not allow stepping over the value!
1398 
1399   // Loop over all of the operands, tracking down which value we are
1400   // addressing.
1401   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1402     C = C->getAggregateElement(CE->getOperand(i));
1403     if (!C)
1404       return nullptr;
1405   }
1406   return C;
1407 }
1408 
1409 Constant *
1410 llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1411                                         ArrayRef<Constant *> Indices) {
1412   // Loop over all of the operands, tracking down which value we are
1413   // addressing.
1414   for (Constant *Index : Indices) {
1415     C = C->getAggregateElement(Index);
1416     if (!C)
1417       return nullptr;
1418   }
1419   return C;
1420 }
1421 
1422 //===----------------------------------------------------------------------===//
1423 //  Constant Folding for Calls
1424 //
1425 
1426 bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) {
1427   if (Call->isNoBuiltin())
1428     return false;
1429   switch (F->getIntrinsicID()) {
1430   // Operations that do not operate floating-point numbers and do not depend on
1431   // FP environment can be folded even in strictfp functions.
1432   case Intrinsic::bswap:
1433   case Intrinsic::ctpop:
1434   case Intrinsic::ctlz:
1435   case Intrinsic::cttz:
1436   case Intrinsic::fshl:
1437   case Intrinsic::fshr:
1438   case Intrinsic::launder_invariant_group:
1439   case Intrinsic::strip_invariant_group:
1440   case Intrinsic::masked_load:
1441   case Intrinsic::abs:
1442   case Intrinsic::smax:
1443   case Intrinsic::smin:
1444   case Intrinsic::umax:
1445   case Intrinsic::umin:
1446   case Intrinsic::sadd_with_overflow:
1447   case Intrinsic::uadd_with_overflow:
1448   case Intrinsic::ssub_with_overflow:
1449   case Intrinsic::usub_with_overflow:
1450   case Intrinsic::smul_with_overflow:
1451   case Intrinsic::umul_with_overflow:
1452   case Intrinsic::sadd_sat:
1453   case Intrinsic::uadd_sat:
1454   case Intrinsic::ssub_sat:
1455   case Intrinsic::usub_sat:
1456   case Intrinsic::smul_fix:
1457   case Intrinsic::smul_fix_sat:
1458   case Intrinsic::bitreverse:
1459   case Intrinsic::is_constant:
1460   case Intrinsic::experimental_vector_reduce_add:
1461   case Intrinsic::experimental_vector_reduce_mul:
1462   case Intrinsic::experimental_vector_reduce_and:
1463   case Intrinsic::experimental_vector_reduce_or:
1464   case Intrinsic::experimental_vector_reduce_xor:
1465   case Intrinsic::experimental_vector_reduce_smin:
1466   case Intrinsic::experimental_vector_reduce_smax:
1467   case Intrinsic::experimental_vector_reduce_umin:
1468   case Intrinsic::experimental_vector_reduce_umax:
1469   // Target intrinsics
1470   case Intrinsic::arm_mve_vctp8:
1471   case Intrinsic::arm_mve_vctp16:
1472   case Intrinsic::arm_mve_vctp32:
1473   case Intrinsic::arm_mve_vctp64:
1474   // WebAssembly float semantics are always known
1475   case Intrinsic::wasm_trunc_signed:
1476   case Intrinsic::wasm_trunc_unsigned:
1477   case Intrinsic::wasm_trunc_saturate_signed:
1478   case Intrinsic::wasm_trunc_saturate_unsigned:
1479     return true;
1480 
1481   // Floating point operations cannot be folded in strictfp functions in
1482   // general case. They can be folded if FP environment is known to compiler.
1483   case Intrinsic::minnum:
1484   case Intrinsic::maxnum:
1485   case Intrinsic::minimum:
1486   case Intrinsic::maximum:
1487   case Intrinsic::log:
1488   case Intrinsic::log2:
1489   case Intrinsic::log10:
1490   case Intrinsic::exp:
1491   case Intrinsic::exp2:
1492   case Intrinsic::sqrt:
1493   case Intrinsic::sin:
1494   case Intrinsic::cos:
1495   case Intrinsic::pow:
1496   case Intrinsic::powi:
1497   case Intrinsic::fma:
1498   case Intrinsic::fmuladd:
1499   case Intrinsic::convert_from_fp16:
1500   case Intrinsic::convert_to_fp16:
1501   case Intrinsic::amdgcn_cos:
1502   case Intrinsic::amdgcn_cubeid:
1503   case Intrinsic::amdgcn_cubema:
1504   case Intrinsic::amdgcn_cubesc:
1505   case Intrinsic::amdgcn_cubetc:
1506   case Intrinsic::amdgcn_fmul_legacy:
1507   case Intrinsic::amdgcn_fract:
1508   case Intrinsic::amdgcn_ldexp:
1509   case Intrinsic::amdgcn_sin:
1510   // The intrinsics below depend on rounding mode in MXCSR.
1511   case Intrinsic::x86_sse_cvtss2si:
1512   case Intrinsic::x86_sse_cvtss2si64:
1513   case Intrinsic::x86_sse_cvttss2si:
1514   case Intrinsic::x86_sse_cvttss2si64:
1515   case Intrinsic::x86_sse2_cvtsd2si:
1516   case Intrinsic::x86_sse2_cvtsd2si64:
1517   case Intrinsic::x86_sse2_cvttsd2si:
1518   case Intrinsic::x86_sse2_cvttsd2si64:
1519   case Intrinsic::x86_avx512_vcvtss2si32:
1520   case Intrinsic::x86_avx512_vcvtss2si64:
1521   case Intrinsic::x86_avx512_cvttss2si:
1522   case Intrinsic::x86_avx512_cvttss2si64:
1523   case Intrinsic::x86_avx512_vcvtsd2si32:
1524   case Intrinsic::x86_avx512_vcvtsd2si64:
1525   case Intrinsic::x86_avx512_cvttsd2si:
1526   case Intrinsic::x86_avx512_cvttsd2si64:
1527   case Intrinsic::x86_avx512_vcvtss2usi32:
1528   case Intrinsic::x86_avx512_vcvtss2usi64:
1529   case Intrinsic::x86_avx512_cvttss2usi:
1530   case Intrinsic::x86_avx512_cvttss2usi64:
1531   case Intrinsic::x86_avx512_vcvtsd2usi32:
1532   case Intrinsic::x86_avx512_vcvtsd2usi64:
1533   case Intrinsic::x86_avx512_cvttsd2usi:
1534   case Intrinsic::x86_avx512_cvttsd2usi64:
1535     return !Call->isStrictFP();
1536 
1537   // Sign operations are actually bitwise operations, they do not raise
1538   // exceptions even for SNANs.
1539   case Intrinsic::fabs:
1540   case Intrinsic::copysign:
1541   // Non-constrained variants of rounding operations means default FP
1542   // environment, they can be folded in any case.
1543   case Intrinsic::ceil:
1544   case Intrinsic::floor:
1545   case Intrinsic::round:
1546   case Intrinsic::roundeven:
1547   case Intrinsic::trunc:
1548   case Intrinsic::nearbyint:
1549   case Intrinsic::rint:
1550   // Constrained intrinsics can be folded if FP environment is known
1551   // to compiler.
1552   case Intrinsic::experimental_constrained_ceil:
1553   case Intrinsic::experimental_constrained_floor:
1554   case Intrinsic::experimental_constrained_round:
1555   case Intrinsic::experimental_constrained_roundeven:
1556   case Intrinsic::experimental_constrained_trunc:
1557   case Intrinsic::experimental_constrained_nearbyint:
1558   case Intrinsic::experimental_constrained_rint:
1559     return true;
1560   default:
1561     return false;
1562   case Intrinsic::not_intrinsic: break;
1563   }
1564 
1565   if (!F->hasName() || Call->isStrictFP())
1566     return false;
1567 
1568   // In these cases, the check of the length is required.  We don't want to
1569   // return true for a name like "cos\0blah" which strcmp would return equal to
1570   // "cos", but has length 8.
1571   StringRef Name = F->getName();
1572   switch (Name[0]) {
1573   default:
1574     return false;
1575   case 'a':
1576     return Name == "acos" || Name == "acosf" ||
1577            Name == "asin" || Name == "asinf" ||
1578            Name == "atan" || Name == "atanf" ||
1579            Name == "atan2" || Name == "atan2f";
1580   case 'c':
1581     return Name == "ceil" || Name == "ceilf" ||
1582            Name == "cos" || Name == "cosf" ||
1583            Name == "cosh" || Name == "coshf";
1584   case 'e':
1585     return Name == "exp" || Name == "expf" ||
1586            Name == "exp2" || Name == "exp2f";
1587   case 'f':
1588     return Name == "fabs" || Name == "fabsf" ||
1589            Name == "floor" || Name == "floorf" ||
1590            Name == "fmod" || Name == "fmodf";
1591   case 'l':
1592     return Name == "log" || Name == "logf" ||
1593            Name == "log2" || Name == "log2f" ||
1594            Name == "log10" || Name == "log10f";
1595   case 'n':
1596     return Name == "nearbyint" || Name == "nearbyintf";
1597   case 'p':
1598     return Name == "pow" || Name == "powf";
1599   case 'r':
1600     return Name == "remainder" || Name == "remainderf" ||
1601            Name == "rint" || Name == "rintf" ||
1602            Name == "round" || Name == "roundf";
1603   case 's':
1604     return Name == "sin" || Name == "sinf" ||
1605            Name == "sinh" || Name == "sinhf" ||
1606            Name == "sqrt" || Name == "sqrtf";
1607   case 't':
1608     return Name == "tan" || Name == "tanf" ||
1609            Name == "tanh" || Name == "tanhf" ||
1610            Name == "trunc" || Name == "truncf";
1611   case '_':
1612     // Check for various function names that get used for the math functions
1613     // when the header files are preprocessed with the macro
1614     // __FINITE_MATH_ONLY__ enabled.
1615     // The '12' here is the length of the shortest name that can match.
1616     // We need to check the size before looking at Name[1] and Name[2]
1617     // so we may as well check a limit that will eliminate mismatches.
1618     if (Name.size() < 12 || Name[1] != '_')
1619       return false;
1620     switch (Name[2]) {
1621     default:
1622       return false;
1623     case 'a':
1624       return Name == "__acos_finite" || Name == "__acosf_finite" ||
1625              Name == "__asin_finite" || Name == "__asinf_finite" ||
1626              Name == "__atan2_finite" || Name == "__atan2f_finite";
1627     case 'c':
1628       return Name == "__cosh_finite" || Name == "__coshf_finite";
1629     case 'e':
1630       return Name == "__exp_finite" || Name == "__expf_finite" ||
1631              Name == "__exp2_finite" || Name == "__exp2f_finite";
1632     case 'l':
1633       return Name == "__log_finite" || Name == "__logf_finite" ||
1634              Name == "__log10_finite" || Name == "__log10f_finite";
1635     case 'p':
1636       return Name == "__pow_finite" || Name == "__powf_finite";
1637     case 's':
1638       return Name == "__sinh_finite" || Name == "__sinhf_finite";
1639     }
1640   }
1641 }
1642 
1643 namespace {
1644 
1645 Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1646   if (Ty->isHalfTy() || Ty->isFloatTy()) {
1647     APFloat APF(V);
1648     bool unused;
1649     APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
1650     return ConstantFP::get(Ty->getContext(), APF);
1651   }
1652   if (Ty->isDoubleTy())
1653     return ConstantFP::get(Ty->getContext(), APFloat(V));
1654   llvm_unreachable("Can only constant fold half/float/double");
1655 }
1656 
1657 /// Clear the floating-point exception state.
1658 inline void llvm_fenv_clearexcept() {
1659 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1660   feclearexcept(FE_ALL_EXCEPT);
1661 #endif
1662   errno = 0;
1663 }
1664 
1665 /// Test if a floating-point exception was raised.
1666 inline bool llvm_fenv_testexcept() {
1667   int errno_val = errno;
1668   if (errno_val == ERANGE || errno_val == EDOM)
1669     return true;
1670 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1671   if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1672     return true;
1673 #endif
1674   return false;
1675 }
1676 
1677 Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
1678   llvm_fenv_clearexcept();
1679   V = NativeFP(V);
1680   if (llvm_fenv_testexcept()) {
1681     llvm_fenv_clearexcept();
1682     return nullptr;
1683   }
1684 
1685   return GetConstantFoldFPValue(V, Ty);
1686 }
1687 
1688 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1689                                double W, Type *Ty) {
1690   llvm_fenv_clearexcept();
1691   V = NativeFP(V, W);
1692   if (llvm_fenv_testexcept()) {
1693     llvm_fenv_clearexcept();
1694     return nullptr;
1695   }
1696 
1697   return GetConstantFoldFPValue(V, Ty);
1698 }
1699 
1700 Constant *ConstantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
1701   FixedVectorType *VT = dyn_cast<FixedVectorType>(Op->getType());
1702   if (!VT)
1703     return nullptr;
1704   ConstantInt *CI = dyn_cast<ConstantInt>(Op->getAggregateElement(0U));
1705   if (!CI)
1706     return nullptr;
1707   APInt Acc = CI->getValue();
1708 
1709   for (unsigned I = 1; I < VT->getNumElements(); I++) {
1710     if (!(CI = dyn_cast<ConstantInt>(Op->getAggregateElement(I))))
1711       return nullptr;
1712     const APInt &X = CI->getValue();
1713     switch (IID) {
1714     case Intrinsic::experimental_vector_reduce_add:
1715       Acc = Acc + X;
1716       break;
1717     case Intrinsic::experimental_vector_reduce_mul:
1718       Acc = Acc * X;
1719       break;
1720     case Intrinsic::experimental_vector_reduce_and:
1721       Acc = Acc & X;
1722       break;
1723     case Intrinsic::experimental_vector_reduce_or:
1724       Acc = Acc | X;
1725       break;
1726     case Intrinsic::experimental_vector_reduce_xor:
1727       Acc = Acc ^ X;
1728       break;
1729     case Intrinsic::experimental_vector_reduce_smin:
1730       Acc = APIntOps::smin(Acc, X);
1731       break;
1732     case Intrinsic::experimental_vector_reduce_smax:
1733       Acc = APIntOps::smax(Acc, X);
1734       break;
1735     case Intrinsic::experimental_vector_reduce_umin:
1736       Acc = APIntOps::umin(Acc, X);
1737       break;
1738     case Intrinsic::experimental_vector_reduce_umax:
1739       Acc = APIntOps::umax(Acc, X);
1740       break;
1741     }
1742   }
1743 
1744   return ConstantInt::get(Op->getContext(), Acc);
1745 }
1746 
1747 /// Attempt to fold an SSE floating point to integer conversion of a constant
1748 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1749 /// used (toward nearest, ties to even). This matches the behavior of the
1750 /// non-truncating SSE instructions in the default rounding mode. The desired
1751 /// integer type Ty is used to select how many bits are available for the
1752 /// result. Returns null if the conversion cannot be performed, otherwise
1753 /// returns the Constant value resulting from the conversion.
1754 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1755                                       Type *Ty, bool IsSigned) {
1756   // All of these conversion intrinsics form an integer of at most 64bits.
1757   unsigned ResultWidth = Ty->getIntegerBitWidth();
1758   assert(ResultWidth <= 64 &&
1759          "Can only constant fold conversions to 64 and 32 bit ints");
1760 
1761   uint64_t UIntVal;
1762   bool isExact = false;
1763   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1764                                               : APFloat::rmNearestTiesToEven;
1765   APFloat::opStatus status =
1766       Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1767                            IsSigned, mode, &isExact);
1768   if (status != APFloat::opOK &&
1769       (!roundTowardZero || status != APFloat::opInexact))
1770     return nullptr;
1771   return ConstantInt::get(Ty, UIntVal, IsSigned);
1772 }
1773 
1774 double getValueAsDouble(ConstantFP *Op) {
1775   Type *Ty = Op->getType();
1776 
1777   if (Ty->isFloatTy())
1778     return Op->getValueAPF().convertToFloat();
1779 
1780   if (Ty->isDoubleTy())
1781     return Op->getValueAPF().convertToDouble();
1782 
1783   bool unused;
1784   APFloat APF = Op->getValueAPF();
1785   APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
1786   return APF.convertToDouble();
1787 }
1788 
1789 static bool isManifestConstant(const Constant *c) {
1790   if (isa<ConstantData>(c)) {
1791     return true;
1792   } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) {
1793     for (const Value *subc : c->operand_values()) {
1794       if (!isManifestConstant(cast<Constant>(subc)))
1795         return false;
1796     }
1797     return true;
1798   }
1799   return false;
1800 }
1801 
1802 static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1803   if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1804     C = &CI->getValue();
1805     return true;
1806   }
1807   if (isa<UndefValue>(Op)) {
1808     C = nullptr;
1809     return true;
1810   }
1811   return false;
1812 }
1813 
1814 static Constant *ConstantFoldScalarCall1(StringRef Name,
1815                                          Intrinsic::ID IntrinsicID,
1816                                          Type *Ty,
1817                                          ArrayRef<Constant *> Operands,
1818                                          const TargetLibraryInfo *TLI,
1819                                          const CallBase *Call) {
1820   assert(Operands.size() == 1 && "Wrong number of operands.");
1821 
1822   if (IntrinsicID == Intrinsic::is_constant) {
1823     // We know we have a "Constant" argument. But we want to only
1824     // return true for manifest constants, not those that depend on
1825     // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1826     if (isManifestConstant(Operands[0]))
1827       return ConstantInt::getTrue(Ty->getContext());
1828     return nullptr;
1829   }
1830   if (isa<UndefValue>(Operands[0])) {
1831     // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1832     // ctpop() is between 0 and bitwidth, pick 0 for undef.
1833     if (IntrinsicID == Intrinsic::cos ||
1834         IntrinsicID == Intrinsic::ctpop)
1835       return Constant::getNullValue(Ty);
1836     if (IntrinsicID == Intrinsic::bswap ||
1837         IntrinsicID == Intrinsic::bitreverse ||
1838         IntrinsicID == Intrinsic::launder_invariant_group ||
1839         IntrinsicID == Intrinsic::strip_invariant_group)
1840       return Operands[0];
1841   }
1842 
1843   if (isa<ConstantPointerNull>(Operands[0])) {
1844     // launder(null) == null == strip(null) iff in addrspace 0
1845     if (IntrinsicID == Intrinsic::launder_invariant_group ||
1846         IntrinsicID == Intrinsic::strip_invariant_group) {
1847       // If instruction is not yet put in a basic block (e.g. when cloning
1848       // a function during inlining), Call's caller may not be available.
1849       // So check Call's BB first before querying Call->getCaller.
1850       const Function *Caller =
1851           Call->getParent() ? Call->getCaller() : nullptr;
1852       if (Caller &&
1853           !NullPointerIsDefined(
1854               Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1855         return Operands[0];
1856       }
1857       return nullptr;
1858     }
1859   }
1860 
1861   if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1862     if (IntrinsicID == Intrinsic::convert_to_fp16) {
1863       APFloat Val(Op->getValueAPF());
1864 
1865       bool lost = false;
1866       Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1867 
1868       return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1869     }
1870 
1871     APFloat U = Op->getValueAPF();
1872 
1873     if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
1874         IntrinsicID == Intrinsic::wasm_trunc_unsigned ||
1875         IntrinsicID == Intrinsic::wasm_trunc_saturate_signed ||
1876         IntrinsicID == Intrinsic::wasm_trunc_saturate_unsigned) {
1877 
1878       bool Saturating = IntrinsicID == Intrinsic::wasm_trunc_saturate_signed ||
1879                         IntrinsicID == Intrinsic::wasm_trunc_saturate_unsigned;
1880       bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed ||
1881                     IntrinsicID == Intrinsic::wasm_trunc_saturate_signed;
1882 
1883       if (U.isNaN())
1884         return Saturating ? ConstantInt::get(Ty, 0) : nullptr;
1885 
1886       unsigned Width = Ty->getIntegerBitWidth();
1887       APSInt Int(Width, !Signed);
1888       bool IsExact = false;
1889       APFloat::opStatus Status =
1890           U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
1891 
1892       if (Status == APFloat::opOK || Status == APFloat::opInexact)
1893         return ConstantInt::get(Ty, Int);
1894 
1895       if (!Saturating)
1896         return nullptr;
1897 
1898       if (U.isNegative())
1899         return Signed ? ConstantInt::get(Ty, APInt::getSignedMinValue(Width))
1900                       : ConstantInt::get(Ty, APInt::getMinValue(Width));
1901       else
1902         return Signed ? ConstantInt::get(Ty, APInt::getSignedMaxValue(Width))
1903                       : ConstantInt::get(Ty, APInt::getMaxValue(Width));
1904     }
1905 
1906     if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1907       return nullptr;
1908 
1909     // Use internal versions of these intrinsics.
1910 
1911     if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) {
1912       U.roundToIntegral(APFloat::rmNearestTiesToEven);
1913       return ConstantFP::get(Ty->getContext(), U);
1914     }
1915 
1916     if (IntrinsicID == Intrinsic::round) {
1917       U.roundToIntegral(APFloat::rmNearestTiesToAway);
1918       return ConstantFP::get(Ty->getContext(), U);
1919     }
1920 
1921     if (IntrinsicID == Intrinsic::roundeven) {
1922       U.roundToIntegral(APFloat::rmNearestTiesToEven);
1923       return ConstantFP::get(Ty->getContext(), U);
1924     }
1925 
1926     if (IntrinsicID == Intrinsic::ceil) {
1927       U.roundToIntegral(APFloat::rmTowardPositive);
1928       return ConstantFP::get(Ty->getContext(), U);
1929     }
1930 
1931     if (IntrinsicID == Intrinsic::floor) {
1932       U.roundToIntegral(APFloat::rmTowardNegative);
1933       return ConstantFP::get(Ty->getContext(), U);
1934     }
1935 
1936     if (IntrinsicID == Intrinsic::trunc) {
1937       U.roundToIntegral(APFloat::rmTowardZero);
1938       return ConstantFP::get(Ty->getContext(), U);
1939     }
1940 
1941     if (IntrinsicID == Intrinsic::fabs) {
1942       U.clearSign();
1943       return ConstantFP::get(Ty->getContext(), U);
1944     }
1945 
1946     if (IntrinsicID == Intrinsic::amdgcn_fract) {
1947       // The v_fract instruction behaves like the OpenCL spec, which defines
1948       // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
1949       //   there to prevent fract(-small) from returning 1.0. It returns the
1950       //   largest positive floating-point number less than 1.0."
1951       APFloat FloorU(U);
1952       FloorU.roundToIntegral(APFloat::rmTowardNegative);
1953       APFloat FractU(U - FloorU);
1954       APFloat AlmostOne(U.getSemantics(), 1);
1955       AlmostOne.next(/*nextDown*/ true);
1956       return ConstantFP::get(Ty->getContext(), minimum(FractU, AlmostOne));
1957     }
1958 
1959     // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
1960     // raise FP exceptions, unless the argument is signaling NaN.
1961 
1962     Optional<APFloat::roundingMode> RM;
1963     switch (IntrinsicID) {
1964     default:
1965       break;
1966     case Intrinsic::experimental_constrained_nearbyint:
1967     case Intrinsic::experimental_constrained_rint: {
1968       auto CI = cast<ConstrainedFPIntrinsic>(Call);
1969       RM = CI->getRoundingMode();
1970       if (!RM || RM.getValue() == RoundingMode::Dynamic)
1971         return nullptr;
1972       break;
1973     }
1974     case Intrinsic::experimental_constrained_round:
1975       RM = APFloat::rmNearestTiesToAway;
1976       break;
1977     case Intrinsic::experimental_constrained_ceil:
1978       RM = APFloat::rmTowardPositive;
1979       break;
1980     case Intrinsic::experimental_constrained_floor:
1981       RM = APFloat::rmTowardNegative;
1982       break;
1983     case Intrinsic::experimental_constrained_trunc:
1984       RM = APFloat::rmTowardZero;
1985       break;
1986     }
1987     if (RM) {
1988       auto CI = cast<ConstrainedFPIntrinsic>(Call);
1989       if (U.isFinite()) {
1990         APFloat::opStatus St = U.roundToIntegral(*RM);
1991         if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
1992             St == APFloat::opInexact) {
1993           Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
1994           if (EB && *EB == fp::ebStrict)
1995             return nullptr;
1996         }
1997       } else if (U.isSignaling()) {
1998         Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
1999         if (EB && *EB != fp::ebIgnore)
2000           return nullptr;
2001         U = APFloat::getQNaN(U.getSemantics());
2002       }
2003       return ConstantFP::get(Ty->getContext(), U);
2004     }
2005 
2006     /// We only fold functions with finite arguments. Folding NaN and inf is
2007     /// likely to be aborted with an exception anyway, and some host libms
2008     /// have known errors raising exceptions.
2009     if (!U.isFinite())
2010       return nullptr;
2011 
2012     /// Currently APFloat versions of these functions do not exist, so we use
2013     /// the host native double versions.  Float versions are not called
2014     /// directly but for all these it is true (float)(f((double)arg)) ==
2015     /// f(arg).  Long double not supported yet.
2016     double V = getValueAsDouble(Op);
2017 
2018     switch (IntrinsicID) {
2019       default: break;
2020       case Intrinsic::log:
2021         return ConstantFoldFP(log, V, Ty);
2022       case Intrinsic::log2:
2023         // TODO: What about hosts that lack a C99 library?
2024         return ConstantFoldFP(Log2, V, Ty);
2025       case Intrinsic::log10:
2026         // TODO: What about hosts that lack a C99 library?
2027         return ConstantFoldFP(log10, V, Ty);
2028       case Intrinsic::exp:
2029         return ConstantFoldFP(exp, V, Ty);
2030       case Intrinsic::exp2:
2031         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2032         return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
2033       case Intrinsic::sin:
2034         return ConstantFoldFP(sin, V, Ty);
2035       case Intrinsic::cos:
2036         return ConstantFoldFP(cos, V, Ty);
2037       case Intrinsic::sqrt:
2038         return ConstantFoldFP(sqrt, V, Ty);
2039       case Intrinsic::amdgcn_cos:
2040       case Intrinsic::amdgcn_sin:
2041         if (V < -256.0 || V > 256.0)
2042           // The gfx8 and gfx9 architectures handle arguments outside the range
2043           // [-256, 256] differently. This should be a rare case so bail out
2044           // rather than trying to handle the difference.
2045           return nullptr;
2046         bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
2047         double V4 = V * 4.0;
2048         if (V4 == floor(V4)) {
2049           // Force exact results for quarter-integer inputs.
2050           const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
2051           V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
2052         } else {
2053           if (IsCos)
2054             V = cos(V * 2.0 * numbers::pi);
2055           else
2056             V = sin(V * 2.0 * numbers::pi);
2057         }
2058         return GetConstantFoldFPValue(V, Ty);
2059     }
2060 
2061     if (!TLI)
2062       return nullptr;
2063 
2064     LibFunc Func = NotLibFunc;
2065     TLI->getLibFunc(Name, Func);
2066     switch (Func) {
2067     default:
2068       break;
2069     case LibFunc_acos:
2070     case LibFunc_acosf:
2071     case LibFunc_acos_finite:
2072     case LibFunc_acosf_finite:
2073       if (TLI->has(Func))
2074         return ConstantFoldFP(acos, V, Ty);
2075       break;
2076     case LibFunc_asin:
2077     case LibFunc_asinf:
2078     case LibFunc_asin_finite:
2079     case LibFunc_asinf_finite:
2080       if (TLI->has(Func))
2081         return ConstantFoldFP(asin, V, Ty);
2082       break;
2083     case LibFunc_atan:
2084     case LibFunc_atanf:
2085       if (TLI->has(Func))
2086         return ConstantFoldFP(atan, V, Ty);
2087       break;
2088     case LibFunc_ceil:
2089     case LibFunc_ceilf:
2090       if (TLI->has(Func)) {
2091         U.roundToIntegral(APFloat::rmTowardPositive);
2092         return ConstantFP::get(Ty->getContext(), U);
2093       }
2094       break;
2095     case LibFunc_cos:
2096     case LibFunc_cosf:
2097       if (TLI->has(Func))
2098         return ConstantFoldFP(cos, V, Ty);
2099       break;
2100     case LibFunc_cosh:
2101     case LibFunc_coshf:
2102     case LibFunc_cosh_finite:
2103     case LibFunc_coshf_finite:
2104       if (TLI->has(Func))
2105         return ConstantFoldFP(cosh, V, Ty);
2106       break;
2107     case LibFunc_exp:
2108     case LibFunc_expf:
2109     case LibFunc_exp_finite:
2110     case LibFunc_expf_finite:
2111       if (TLI->has(Func))
2112         return ConstantFoldFP(exp, V, Ty);
2113       break;
2114     case LibFunc_exp2:
2115     case LibFunc_exp2f:
2116     case LibFunc_exp2_finite:
2117     case LibFunc_exp2f_finite:
2118       if (TLI->has(Func))
2119         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2120         return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
2121       break;
2122     case LibFunc_fabs:
2123     case LibFunc_fabsf:
2124       if (TLI->has(Func)) {
2125         U.clearSign();
2126         return ConstantFP::get(Ty->getContext(), U);
2127       }
2128       break;
2129     case LibFunc_floor:
2130     case LibFunc_floorf:
2131       if (TLI->has(Func)) {
2132         U.roundToIntegral(APFloat::rmTowardNegative);
2133         return ConstantFP::get(Ty->getContext(), U);
2134       }
2135       break;
2136     case LibFunc_log:
2137     case LibFunc_logf:
2138     case LibFunc_log_finite:
2139     case LibFunc_logf_finite:
2140       if (V > 0.0 && TLI->has(Func))
2141         return ConstantFoldFP(log, V, Ty);
2142       break;
2143     case LibFunc_log2:
2144     case LibFunc_log2f:
2145     case LibFunc_log2_finite:
2146     case LibFunc_log2f_finite:
2147       if (V > 0.0 && TLI->has(Func))
2148         // TODO: What about hosts that lack a C99 library?
2149         return ConstantFoldFP(Log2, V, Ty);
2150       break;
2151     case LibFunc_log10:
2152     case LibFunc_log10f:
2153     case LibFunc_log10_finite:
2154     case LibFunc_log10f_finite:
2155       if (V > 0.0 && TLI->has(Func))
2156         // TODO: What about hosts that lack a C99 library?
2157         return ConstantFoldFP(log10, V, Ty);
2158       break;
2159     case LibFunc_nearbyint:
2160     case LibFunc_nearbyintf:
2161     case LibFunc_rint:
2162     case LibFunc_rintf:
2163       if (TLI->has(Func)) {
2164         U.roundToIntegral(APFloat::rmNearestTiesToEven);
2165         return ConstantFP::get(Ty->getContext(), U);
2166       }
2167       break;
2168     case LibFunc_round:
2169     case LibFunc_roundf:
2170       if (TLI->has(Func)) {
2171         U.roundToIntegral(APFloat::rmNearestTiesToAway);
2172         return ConstantFP::get(Ty->getContext(), U);
2173       }
2174       break;
2175     case LibFunc_sin:
2176     case LibFunc_sinf:
2177       if (TLI->has(Func))
2178         return ConstantFoldFP(sin, V, Ty);
2179       break;
2180     case LibFunc_sinh:
2181     case LibFunc_sinhf:
2182     case LibFunc_sinh_finite:
2183     case LibFunc_sinhf_finite:
2184       if (TLI->has(Func))
2185         return ConstantFoldFP(sinh, V, Ty);
2186       break;
2187     case LibFunc_sqrt:
2188     case LibFunc_sqrtf:
2189       if (V >= 0.0 && TLI->has(Func))
2190         return ConstantFoldFP(sqrt, V, Ty);
2191       break;
2192     case LibFunc_tan:
2193     case LibFunc_tanf:
2194       if (TLI->has(Func))
2195         return ConstantFoldFP(tan, V, Ty);
2196       break;
2197     case LibFunc_tanh:
2198     case LibFunc_tanhf:
2199       if (TLI->has(Func))
2200         return ConstantFoldFP(tanh, V, Ty);
2201       break;
2202     case LibFunc_trunc:
2203     case LibFunc_truncf:
2204       if (TLI->has(Func)) {
2205         U.roundToIntegral(APFloat::rmTowardZero);
2206         return ConstantFP::get(Ty->getContext(), U);
2207       }
2208       break;
2209     }
2210     return nullptr;
2211   }
2212 
2213   if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2214     switch (IntrinsicID) {
2215     case Intrinsic::bswap:
2216       return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
2217     case Intrinsic::ctpop:
2218       return ConstantInt::get(Ty, Op->getValue().countPopulation());
2219     case Intrinsic::bitreverse:
2220       return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
2221     case Intrinsic::convert_from_fp16: {
2222       APFloat Val(APFloat::IEEEhalf(), Op->getValue());
2223 
2224       bool lost = false;
2225       APFloat::opStatus status = Val.convert(
2226           Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
2227 
2228       // Conversion is always precise.
2229       (void)status;
2230       assert(status == APFloat::opOK && !lost &&
2231              "Precision lost during fp16 constfolding");
2232 
2233       return ConstantFP::get(Ty->getContext(), Val);
2234     }
2235     default:
2236       return nullptr;
2237     }
2238   }
2239 
2240   if (isa<ConstantAggregateZero>(Operands[0])) {
2241     switch (IntrinsicID) {
2242     default: break;
2243     case Intrinsic::experimental_vector_reduce_add:
2244     case Intrinsic::experimental_vector_reduce_mul:
2245     case Intrinsic::experimental_vector_reduce_and:
2246     case Intrinsic::experimental_vector_reduce_or:
2247     case Intrinsic::experimental_vector_reduce_xor:
2248     case Intrinsic::experimental_vector_reduce_smin:
2249     case Intrinsic::experimental_vector_reduce_smax:
2250     case Intrinsic::experimental_vector_reduce_umin:
2251     case Intrinsic::experimental_vector_reduce_umax:
2252       return ConstantInt::get(Ty, 0);
2253     }
2254   }
2255 
2256   // Support ConstantVector in case we have an Undef in the top.
2257   if (isa<ConstantVector>(Operands[0]) ||
2258       isa<ConstantDataVector>(Operands[0])) {
2259     auto *Op = cast<Constant>(Operands[0]);
2260     switch (IntrinsicID) {
2261     default: break;
2262     case Intrinsic::experimental_vector_reduce_add:
2263     case Intrinsic::experimental_vector_reduce_mul:
2264     case Intrinsic::experimental_vector_reduce_and:
2265     case Intrinsic::experimental_vector_reduce_or:
2266     case Intrinsic::experimental_vector_reduce_xor:
2267     case Intrinsic::experimental_vector_reduce_smin:
2268     case Intrinsic::experimental_vector_reduce_smax:
2269     case Intrinsic::experimental_vector_reduce_umin:
2270     case Intrinsic::experimental_vector_reduce_umax:
2271       if (Constant *C = ConstantFoldVectorReduce(IntrinsicID, Op))
2272         return C;
2273       break;
2274     case Intrinsic::x86_sse_cvtss2si:
2275     case Intrinsic::x86_sse_cvtss2si64:
2276     case Intrinsic::x86_sse2_cvtsd2si:
2277     case Intrinsic::x86_sse2_cvtsd2si64:
2278       if (ConstantFP *FPOp =
2279               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2280         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2281                                            /*roundTowardZero=*/false, Ty,
2282                                            /*IsSigned*/true);
2283       break;
2284     case Intrinsic::x86_sse_cvttss2si:
2285     case Intrinsic::x86_sse_cvttss2si64:
2286     case Intrinsic::x86_sse2_cvttsd2si:
2287     case Intrinsic::x86_sse2_cvttsd2si64:
2288       if (ConstantFP *FPOp =
2289               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2290         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2291                                            /*roundTowardZero=*/true, Ty,
2292                                            /*IsSigned*/true);
2293       break;
2294     }
2295   }
2296 
2297   return nullptr;
2298 }
2299 
2300 static Constant *ConstantFoldScalarCall2(StringRef Name,
2301                                          Intrinsic::ID IntrinsicID,
2302                                          Type *Ty,
2303                                          ArrayRef<Constant *> Operands,
2304                                          const TargetLibraryInfo *TLI,
2305                                          const CallBase *Call) {
2306   assert(Operands.size() == 2 && "Wrong number of operands.");
2307 
2308   if (Ty->isFloatingPointTy()) {
2309     // TODO: We should have undef handling for all of the FP intrinsics that
2310     //       are attempted to be folded in this function.
2311     bool IsOp0Undef = isa<UndefValue>(Operands[0]);
2312     bool IsOp1Undef = isa<UndefValue>(Operands[1]);
2313     switch (IntrinsicID) {
2314     case Intrinsic::maxnum:
2315     case Intrinsic::minnum:
2316     case Intrinsic::maximum:
2317     case Intrinsic::minimum:
2318       // If one argument is undef, return the other argument.
2319       if (IsOp0Undef)
2320         return Operands[1];
2321       if (IsOp1Undef)
2322         return Operands[0];
2323       break;
2324     }
2325   }
2326 
2327   if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2328     if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2329       return nullptr;
2330     double Op1V = getValueAsDouble(Op1);
2331 
2332     if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2333       if (Op2->getType() != Op1->getType())
2334         return nullptr;
2335 
2336       double Op2V = getValueAsDouble(Op2);
2337       if (IntrinsicID == Intrinsic::pow) {
2338         return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2339       }
2340       if (IntrinsicID == Intrinsic::copysign) {
2341         APFloat V1 = Op1->getValueAPF();
2342         const APFloat &V2 = Op2->getValueAPF();
2343         V1.copySign(V2);
2344         return ConstantFP::get(Ty->getContext(), V1);
2345       }
2346 
2347       if (IntrinsicID == Intrinsic::minnum) {
2348         const APFloat &C1 = Op1->getValueAPF();
2349         const APFloat &C2 = Op2->getValueAPF();
2350         return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
2351       }
2352 
2353       if (IntrinsicID == Intrinsic::maxnum) {
2354         const APFloat &C1 = Op1->getValueAPF();
2355         const APFloat &C2 = Op2->getValueAPF();
2356         return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
2357       }
2358 
2359       if (IntrinsicID == Intrinsic::minimum) {
2360         const APFloat &C1 = Op1->getValueAPF();
2361         const APFloat &C2 = Op2->getValueAPF();
2362         return ConstantFP::get(Ty->getContext(), minimum(C1, C2));
2363       }
2364 
2365       if (IntrinsicID == Intrinsic::maximum) {
2366         const APFloat &C1 = Op1->getValueAPF();
2367         const APFloat &C2 = Op2->getValueAPF();
2368         return ConstantFP::get(Ty->getContext(), maximum(C1, C2));
2369       }
2370 
2371       if (IntrinsicID == Intrinsic::amdgcn_fmul_legacy) {
2372         const APFloat &C1 = Op1->getValueAPF();
2373         const APFloat &C2 = Op2->getValueAPF();
2374         // The legacy behaviour is that multiplying zero by anything, even NaN
2375         // or infinity, gives +0.0.
2376         if (C1.isZero() || C2.isZero())
2377           return ConstantFP::getNullValue(Ty);
2378         return ConstantFP::get(Ty->getContext(), C1 * C2);
2379       }
2380 
2381       if (!TLI)
2382         return nullptr;
2383 
2384       LibFunc Func = NotLibFunc;
2385       TLI->getLibFunc(Name, Func);
2386       switch (Func) {
2387       default:
2388         break;
2389       case LibFunc_pow:
2390       case LibFunc_powf:
2391       case LibFunc_pow_finite:
2392       case LibFunc_powf_finite:
2393         if (TLI->has(Func))
2394           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2395         break;
2396       case LibFunc_fmod:
2397       case LibFunc_fmodf:
2398         if (TLI->has(Func)) {
2399           APFloat V = Op1->getValueAPF();
2400           if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
2401             return ConstantFP::get(Ty->getContext(), V);
2402         }
2403         break;
2404       case LibFunc_remainder:
2405       case LibFunc_remainderf:
2406         if (TLI->has(Func)) {
2407           APFloat V = Op1->getValueAPF();
2408           if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
2409             return ConstantFP::get(Ty->getContext(), V);
2410         }
2411         break;
2412       case LibFunc_atan2:
2413       case LibFunc_atan2f:
2414       case LibFunc_atan2_finite:
2415       case LibFunc_atan2f_finite:
2416         if (TLI->has(Func))
2417           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
2418         break;
2419       }
2420     } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
2421       if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
2422         return ConstantFP::get(Ty->getContext(),
2423                                APFloat((float)std::pow((float)Op1V,
2424                                                (int)Op2C->getZExtValue())));
2425       if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2426         return ConstantFP::get(Ty->getContext(),
2427                                APFloat((float)std::pow((float)Op1V,
2428                                                (int)Op2C->getZExtValue())));
2429       if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2430         return ConstantFP::get(Ty->getContext(),
2431                                APFloat((double)std::pow((double)Op1V,
2432                                                  (int)Op2C->getZExtValue())));
2433 
2434       if (IntrinsicID == Intrinsic::amdgcn_ldexp) {
2435         // FIXME: Should flush denorms depending on FP mode, but that's ignored
2436         // everywhere else.
2437 
2438         // scalbn is equivalent to ldexp with float radix 2
2439         APFloat Result = scalbn(Op1->getValueAPF(), Op2C->getSExtValue(),
2440                                 APFloat::rmNearestTiesToEven);
2441         return ConstantFP::get(Ty->getContext(), Result);
2442       }
2443     }
2444     return nullptr;
2445   }
2446 
2447   if (Operands[0]->getType()->isIntegerTy() &&
2448       Operands[1]->getType()->isIntegerTy()) {
2449     const APInt *C0, *C1;
2450     if (!getConstIntOrUndef(Operands[0], C0) ||
2451         !getConstIntOrUndef(Operands[1], C1))
2452       return nullptr;
2453 
2454     unsigned BitWidth = Ty->getScalarSizeInBits();
2455     switch (IntrinsicID) {
2456     default: break;
2457     case Intrinsic::smax:
2458       if (!C0 && !C1)
2459         return UndefValue::get(Ty);
2460       if (!C0 || !C1)
2461         return ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
2462       return ConstantInt::get(Ty, C0->sgt(*C1) ? *C0 : *C1);
2463 
2464     case Intrinsic::smin:
2465       if (!C0 && !C1)
2466         return UndefValue::get(Ty);
2467       if (!C0 || !C1)
2468         return ConstantInt::get(Ty, APInt::getSignedMinValue(BitWidth));
2469       return ConstantInt::get(Ty, C0->slt(*C1) ? *C0 : *C1);
2470 
2471     case Intrinsic::umax:
2472       if (!C0 && !C1)
2473         return UndefValue::get(Ty);
2474       if (!C0 || !C1)
2475         return ConstantInt::get(Ty, APInt::getMaxValue(BitWidth));
2476       return ConstantInt::get(Ty, C0->ugt(*C1) ? *C0 : *C1);
2477 
2478     case Intrinsic::umin:
2479       if (!C0 && !C1)
2480         return UndefValue::get(Ty);
2481       if (!C0 || !C1)
2482         return ConstantInt::get(Ty, APInt::getMinValue(BitWidth));
2483       return ConstantInt::get(Ty, C0->ult(*C1) ? *C0 : *C1);
2484 
2485     case Intrinsic::usub_with_overflow:
2486     case Intrinsic::ssub_with_overflow:
2487     case Intrinsic::uadd_with_overflow:
2488     case Intrinsic::sadd_with_overflow:
2489       // X - undef -> { undef, false }
2490       // undef - X -> { undef, false }
2491       // X + undef -> { undef, false }
2492       // undef + x -> { undef, false }
2493       if (!C0 || !C1) {
2494         return ConstantStruct::get(
2495             cast<StructType>(Ty),
2496             {UndefValue::get(Ty->getStructElementType(0)),
2497              Constant::getNullValue(Ty->getStructElementType(1))});
2498       }
2499       LLVM_FALLTHROUGH;
2500     case Intrinsic::smul_with_overflow:
2501     case Intrinsic::umul_with_overflow: {
2502       // undef * X -> { 0, false }
2503       // X * undef -> { 0, false }
2504       if (!C0 || !C1)
2505         return Constant::getNullValue(Ty);
2506 
2507       APInt Res;
2508       bool Overflow;
2509       switch (IntrinsicID) {
2510       default: llvm_unreachable("Invalid case");
2511       case Intrinsic::sadd_with_overflow:
2512         Res = C0->sadd_ov(*C1, Overflow);
2513         break;
2514       case Intrinsic::uadd_with_overflow:
2515         Res = C0->uadd_ov(*C1, Overflow);
2516         break;
2517       case Intrinsic::ssub_with_overflow:
2518         Res = C0->ssub_ov(*C1, Overflow);
2519         break;
2520       case Intrinsic::usub_with_overflow:
2521         Res = C0->usub_ov(*C1, Overflow);
2522         break;
2523       case Intrinsic::smul_with_overflow:
2524         Res = C0->smul_ov(*C1, Overflow);
2525         break;
2526       case Intrinsic::umul_with_overflow:
2527         Res = C0->umul_ov(*C1, Overflow);
2528         break;
2529       }
2530       Constant *Ops[] = {
2531         ConstantInt::get(Ty->getContext(), Res),
2532         ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2533       };
2534       return ConstantStruct::get(cast<StructType>(Ty), Ops);
2535     }
2536     case Intrinsic::uadd_sat:
2537     case Intrinsic::sadd_sat:
2538       if (!C0 && !C1)
2539         return UndefValue::get(Ty);
2540       if (!C0 || !C1)
2541         return Constant::getAllOnesValue(Ty);
2542       if (IntrinsicID == Intrinsic::uadd_sat)
2543         return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2544       else
2545         return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2546     case Intrinsic::usub_sat:
2547     case Intrinsic::ssub_sat:
2548       if (!C0 && !C1)
2549         return UndefValue::get(Ty);
2550       if (!C0 || !C1)
2551         return Constant::getNullValue(Ty);
2552       if (IntrinsicID == Intrinsic::usub_sat)
2553         return ConstantInt::get(Ty, C0->usub_sat(*C1));
2554       else
2555         return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2556     case Intrinsic::cttz:
2557     case Intrinsic::ctlz:
2558       assert(C1 && "Must be constant int");
2559 
2560       // cttz(0, 1) and ctlz(0, 1) are undef.
2561       if (C1->isOneValue() && (!C0 || C0->isNullValue()))
2562         return UndefValue::get(Ty);
2563       if (!C0)
2564         return Constant::getNullValue(Ty);
2565       if (IntrinsicID == Intrinsic::cttz)
2566         return ConstantInt::get(Ty, C0->countTrailingZeros());
2567       else
2568         return ConstantInt::get(Ty, C0->countLeadingZeros());
2569 
2570     case Intrinsic::abs:
2571       // Undef or minimum val operand with poison min --> undef
2572       assert(C1 && "Must be constant int");
2573       if (C1->isOneValue() && (!C0 || C0->isMinSignedValue()))
2574         return UndefValue::get(Ty);
2575 
2576       // Undef operand with no poison min --> 0 (sign bit must be clear)
2577       if (C1->isNullValue() && !C0)
2578         return Constant::getNullValue(Ty);
2579 
2580       return ConstantInt::get(Ty, C0->abs());
2581     }
2582 
2583     return nullptr;
2584   }
2585 
2586   // Support ConstantVector in case we have an Undef in the top.
2587   if ((isa<ConstantVector>(Operands[0]) ||
2588        isa<ConstantDataVector>(Operands[0])) &&
2589       // Check for default rounding mode.
2590       // FIXME: Support other rounding modes?
2591       isa<ConstantInt>(Operands[1]) &&
2592       cast<ConstantInt>(Operands[1])->getValue() == 4) {
2593     auto *Op = cast<Constant>(Operands[0]);
2594     switch (IntrinsicID) {
2595     default: break;
2596     case Intrinsic::x86_avx512_vcvtss2si32:
2597     case Intrinsic::x86_avx512_vcvtss2si64:
2598     case Intrinsic::x86_avx512_vcvtsd2si32:
2599     case Intrinsic::x86_avx512_vcvtsd2si64:
2600       if (ConstantFP *FPOp =
2601               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2602         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2603                                            /*roundTowardZero=*/false, Ty,
2604                                            /*IsSigned*/true);
2605       break;
2606     case Intrinsic::x86_avx512_vcvtss2usi32:
2607     case Intrinsic::x86_avx512_vcvtss2usi64:
2608     case Intrinsic::x86_avx512_vcvtsd2usi32:
2609     case Intrinsic::x86_avx512_vcvtsd2usi64:
2610       if (ConstantFP *FPOp =
2611               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2612         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2613                                            /*roundTowardZero=*/false, Ty,
2614                                            /*IsSigned*/false);
2615       break;
2616     case Intrinsic::x86_avx512_cvttss2si:
2617     case Intrinsic::x86_avx512_cvttss2si64:
2618     case Intrinsic::x86_avx512_cvttsd2si:
2619     case Intrinsic::x86_avx512_cvttsd2si64:
2620       if (ConstantFP *FPOp =
2621               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2622         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2623                                            /*roundTowardZero=*/true, Ty,
2624                                            /*IsSigned*/true);
2625       break;
2626     case Intrinsic::x86_avx512_cvttss2usi:
2627     case Intrinsic::x86_avx512_cvttss2usi64:
2628     case Intrinsic::x86_avx512_cvttsd2usi:
2629     case Intrinsic::x86_avx512_cvttsd2usi64:
2630       if (ConstantFP *FPOp =
2631               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2632         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2633                                            /*roundTowardZero=*/true, Ty,
2634                                            /*IsSigned*/false);
2635       break;
2636     }
2637   }
2638   return nullptr;
2639 }
2640 
2641 static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
2642                                                const APFloat &S0,
2643                                                const APFloat &S1,
2644                                                const APFloat &S2) {
2645   unsigned ID;
2646   const fltSemantics &Sem = S0.getSemantics();
2647   APFloat MA(Sem), SC(Sem), TC(Sem);
2648   if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
2649     if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
2650       // S2 < 0
2651       ID = 5;
2652       SC = -S0;
2653     } else {
2654       ID = 4;
2655       SC = S0;
2656     }
2657     MA = S2;
2658     TC = -S1;
2659   } else if (abs(S1) >= abs(S0)) {
2660     if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
2661       // S1 < 0
2662       ID = 3;
2663       TC = -S2;
2664     } else {
2665       ID = 2;
2666       TC = S2;
2667     }
2668     MA = S1;
2669     SC = S0;
2670   } else {
2671     if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
2672       // S0 < 0
2673       ID = 1;
2674       SC = S2;
2675     } else {
2676       ID = 0;
2677       SC = -S2;
2678     }
2679     MA = S0;
2680     TC = -S1;
2681   }
2682   switch (IntrinsicID) {
2683   default:
2684     llvm_unreachable("unhandled amdgcn cube intrinsic");
2685   case Intrinsic::amdgcn_cubeid:
2686     return APFloat(Sem, ID);
2687   case Intrinsic::amdgcn_cubema:
2688     return MA + MA;
2689   case Intrinsic::amdgcn_cubesc:
2690     return SC;
2691   case Intrinsic::amdgcn_cubetc:
2692     return TC;
2693   }
2694 }
2695 
2696 static Constant *ConstantFoldScalarCall3(StringRef Name,
2697                                          Intrinsic::ID IntrinsicID,
2698                                          Type *Ty,
2699                                          ArrayRef<Constant *> Operands,
2700                                          const TargetLibraryInfo *TLI,
2701                                          const CallBase *Call) {
2702   assert(Operands.size() == 3 && "Wrong number of operands.");
2703 
2704   if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2705     if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2706       if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
2707         switch (IntrinsicID) {
2708         default: break;
2709         case Intrinsic::fma:
2710         case Intrinsic::fmuladd: {
2711           APFloat V = Op1->getValueAPF();
2712           V.fusedMultiplyAdd(Op2->getValueAPF(), Op3->getValueAPF(),
2713                              APFloat::rmNearestTiesToEven);
2714           return ConstantFP::get(Ty->getContext(), V);
2715         }
2716         case Intrinsic::amdgcn_cubeid:
2717         case Intrinsic::amdgcn_cubema:
2718         case Intrinsic::amdgcn_cubesc:
2719         case Intrinsic::amdgcn_cubetc: {
2720           APFloat V = ConstantFoldAMDGCNCubeIntrinsic(
2721               IntrinsicID, Op1->getValueAPF(), Op2->getValueAPF(),
2722               Op3->getValueAPF());
2723           return ConstantFP::get(Ty->getContext(), V);
2724         }
2725         }
2726       }
2727     }
2728   }
2729 
2730   if (const auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
2731     if (const auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
2732       if (const auto *Op3 = dyn_cast<ConstantInt>(Operands[2])) {
2733         switch (IntrinsicID) {
2734         default: break;
2735         case Intrinsic::smul_fix:
2736         case Intrinsic::smul_fix_sat: {
2737           // This code performs rounding towards negative infinity in case the
2738           // result cannot be represented exactly for the given scale. Targets
2739           // that do care about rounding should use a target hook for specifying
2740           // how rounding should be done, and provide their own folding to be
2741           // consistent with rounding. This is the same approach as used by
2742           // DAGTypeLegalizer::ExpandIntRes_MULFIX.
2743           const APInt &Lhs = Op1->getValue();
2744           const APInt &Rhs = Op2->getValue();
2745           unsigned Scale = Op3->getValue().getZExtValue();
2746           unsigned Width = Lhs.getBitWidth();
2747           assert(Scale < Width && "Illegal scale.");
2748           unsigned ExtendedWidth = Width * 2;
2749           APInt Product = (Lhs.sextOrSelf(ExtendedWidth) *
2750                            Rhs.sextOrSelf(ExtendedWidth)).ashr(Scale);
2751           if (IntrinsicID == Intrinsic::smul_fix_sat) {
2752             APInt MaxValue =
2753               APInt::getSignedMaxValue(Width).sextOrSelf(ExtendedWidth);
2754             APInt MinValue =
2755               APInt::getSignedMinValue(Width).sextOrSelf(ExtendedWidth);
2756             Product = APIntOps::smin(Product, MaxValue);
2757             Product = APIntOps::smax(Product, MinValue);
2758           }
2759           return ConstantInt::get(Ty->getContext(),
2760                                   Product.sextOrTrunc(Width));
2761         }
2762         }
2763       }
2764     }
2765   }
2766 
2767   if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
2768     const APInt *C0, *C1, *C2;
2769     if (!getConstIntOrUndef(Operands[0], C0) ||
2770         !getConstIntOrUndef(Operands[1], C1) ||
2771         !getConstIntOrUndef(Operands[2], C2))
2772       return nullptr;
2773 
2774     bool IsRight = IntrinsicID == Intrinsic::fshr;
2775     if (!C2)
2776       return Operands[IsRight ? 1 : 0];
2777     if (!C0 && !C1)
2778       return UndefValue::get(Ty);
2779 
2780     // The shift amount is interpreted as modulo the bitwidth. If the shift
2781     // amount is effectively 0, avoid UB due to oversized inverse shift below.
2782     unsigned BitWidth = C2->getBitWidth();
2783     unsigned ShAmt = C2->urem(BitWidth);
2784     if (!ShAmt)
2785       return Operands[IsRight ? 1 : 0];
2786 
2787     // (C0 << ShlAmt) | (C1 >> LshrAmt)
2788     unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
2789     unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
2790     if (!C0)
2791       return ConstantInt::get(Ty, C1->lshr(LshrAmt));
2792     if (!C1)
2793       return ConstantInt::get(Ty, C0->shl(ShlAmt));
2794     return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
2795   }
2796 
2797   return nullptr;
2798 }
2799 
2800 static Constant *ConstantFoldScalarCall(StringRef Name,
2801                                         Intrinsic::ID IntrinsicID,
2802                                         Type *Ty,
2803                                         ArrayRef<Constant *> Operands,
2804                                         const TargetLibraryInfo *TLI,
2805                                         const CallBase *Call) {
2806   if (Operands.size() == 1)
2807     return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
2808 
2809   if (Operands.size() == 2)
2810     return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call);
2811 
2812   if (Operands.size() == 3)
2813     return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
2814 
2815   return nullptr;
2816 }
2817 
2818 static Constant *ConstantFoldVectorCall(StringRef Name,
2819                                         Intrinsic::ID IntrinsicID,
2820                                         VectorType *VTy,
2821                                         ArrayRef<Constant *> Operands,
2822                                         const DataLayout &DL,
2823                                         const TargetLibraryInfo *TLI,
2824                                         const CallBase *Call) {
2825   // Do not iterate on scalable vector. The number of elements is unknown at
2826   // compile-time.
2827   if (isa<ScalableVectorType>(VTy))
2828     return nullptr;
2829 
2830   auto *FVTy = cast<FixedVectorType>(VTy);
2831 
2832   SmallVector<Constant *, 4> Result(FVTy->getNumElements());
2833   SmallVector<Constant *, 4> Lane(Operands.size());
2834   Type *Ty = FVTy->getElementType();
2835 
2836   switch (IntrinsicID) {
2837   case Intrinsic::masked_load: {
2838     auto *SrcPtr = Operands[0];
2839     auto *Mask = Operands[2];
2840     auto *Passthru = Operands[3];
2841 
2842     Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
2843 
2844     SmallVector<Constant *, 32> NewElements;
2845     for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
2846       auto *MaskElt = Mask->getAggregateElement(I);
2847       if (!MaskElt)
2848         break;
2849       auto *PassthruElt = Passthru->getAggregateElement(I);
2850       auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2851       if (isa<UndefValue>(MaskElt)) {
2852         if (PassthruElt)
2853           NewElements.push_back(PassthruElt);
2854         else if (VecElt)
2855           NewElements.push_back(VecElt);
2856         else
2857           return nullptr;
2858       }
2859       if (MaskElt->isNullValue()) {
2860         if (!PassthruElt)
2861           return nullptr;
2862         NewElements.push_back(PassthruElt);
2863       } else if (MaskElt->isOneValue()) {
2864         if (!VecElt)
2865           return nullptr;
2866         NewElements.push_back(VecElt);
2867       } else {
2868         return nullptr;
2869       }
2870     }
2871     if (NewElements.size() != FVTy->getNumElements())
2872       return nullptr;
2873     return ConstantVector::get(NewElements);
2874   }
2875   case Intrinsic::arm_mve_vctp8:
2876   case Intrinsic::arm_mve_vctp16:
2877   case Intrinsic::arm_mve_vctp32:
2878   case Intrinsic::arm_mve_vctp64: {
2879     if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2880       unsigned Lanes = FVTy->getNumElements();
2881       uint64_t Limit = Op->getZExtValue();
2882       // vctp64 are currently modelled as returning a v4i1, not a v2i1. Make
2883       // sure we get the limit right in that case and set all relevant lanes.
2884       if (IntrinsicID == Intrinsic::arm_mve_vctp64)
2885         Limit *= 2;
2886 
2887       SmallVector<Constant *, 16> NCs;
2888       for (unsigned i = 0; i < Lanes; i++) {
2889         if (i < Limit)
2890           NCs.push_back(ConstantInt::getTrue(Ty));
2891         else
2892           NCs.push_back(ConstantInt::getFalse(Ty));
2893       }
2894       return ConstantVector::get(NCs);
2895     }
2896     break;
2897   }
2898   default:
2899     break;
2900   }
2901 
2902   for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
2903     // Gather a column of constants.
2904     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
2905       // Some intrinsics use a scalar type for certain arguments.
2906       if (hasVectorInstrinsicScalarOpd(IntrinsicID, J)) {
2907         Lane[J] = Operands[J];
2908         continue;
2909       }
2910 
2911       Constant *Agg = Operands[J]->getAggregateElement(I);
2912       if (!Agg)
2913         return nullptr;
2914 
2915       Lane[J] = Agg;
2916     }
2917 
2918     // Use the regular scalar folding to simplify this column.
2919     Constant *Folded =
2920         ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
2921     if (!Folded)
2922       return nullptr;
2923     Result[I] = Folded;
2924   }
2925 
2926   return ConstantVector::get(Result);
2927 }
2928 
2929 } // end anonymous namespace
2930 
2931 Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F,
2932                                  ArrayRef<Constant *> Operands,
2933                                  const TargetLibraryInfo *TLI) {
2934   if (Call->isNoBuiltin())
2935     return nullptr;
2936   if (!F->hasName())
2937     return nullptr;
2938   StringRef Name = F->getName();
2939 
2940   Type *Ty = F->getReturnType();
2941 
2942   if (auto *VTy = dyn_cast<VectorType>(Ty))
2943     return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
2944                                   F->getParent()->getDataLayout(), TLI, Call);
2945 
2946   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI,
2947                                 Call);
2948 }
2949 
2950 bool llvm::isMathLibCallNoop(const CallBase *Call,
2951                              const TargetLibraryInfo *TLI) {
2952   // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2953   // (and to some extent ConstantFoldScalarCall).
2954   if (Call->isNoBuiltin() || Call->isStrictFP())
2955     return false;
2956   Function *F = Call->getCalledFunction();
2957   if (!F)
2958     return false;
2959 
2960   LibFunc Func;
2961   if (!TLI || !TLI->getLibFunc(*F, Func))
2962     return false;
2963 
2964   if (Call->getNumArgOperands() == 1) {
2965     if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
2966       const APFloat &Op = OpC->getValueAPF();
2967       switch (Func) {
2968       case LibFunc_logl:
2969       case LibFunc_log:
2970       case LibFunc_logf:
2971       case LibFunc_log2l:
2972       case LibFunc_log2:
2973       case LibFunc_log2f:
2974       case LibFunc_log10l:
2975       case LibFunc_log10:
2976       case LibFunc_log10f:
2977         return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2978 
2979       case LibFunc_expl:
2980       case LibFunc_exp:
2981       case LibFunc_expf:
2982         // FIXME: These boundaries are slightly conservative.
2983         if (OpC->getType()->isDoubleTy())
2984           return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
2985         if (OpC->getType()->isFloatTy())
2986           return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
2987         break;
2988 
2989       case LibFunc_exp2l:
2990       case LibFunc_exp2:
2991       case LibFunc_exp2f:
2992         // FIXME: These boundaries are slightly conservative.
2993         if (OpC->getType()->isDoubleTy())
2994           return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
2995         if (OpC->getType()->isFloatTy())
2996           return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
2997         break;
2998 
2999       case LibFunc_sinl:
3000       case LibFunc_sin:
3001       case LibFunc_sinf:
3002       case LibFunc_cosl:
3003       case LibFunc_cos:
3004       case LibFunc_cosf:
3005         return !Op.isInfinity();
3006 
3007       case LibFunc_tanl:
3008       case LibFunc_tan:
3009       case LibFunc_tanf: {
3010         // FIXME: Stop using the host math library.
3011         // FIXME: The computation isn't done in the right precision.
3012         Type *Ty = OpC->getType();
3013         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
3014           double OpV = getValueAsDouble(OpC);
3015           return ConstantFoldFP(tan, OpV, Ty) != nullptr;
3016         }
3017         break;
3018       }
3019 
3020       case LibFunc_asinl:
3021       case LibFunc_asin:
3022       case LibFunc_asinf:
3023       case LibFunc_acosl:
3024       case LibFunc_acos:
3025       case LibFunc_acosf:
3026         return !(Op < APFloat(Op.getSemantics(), "-1") ||
3027                  Op > APFloat(Op.getSemantics(), "1"));
3028 
3029       case LibFunc_sinh:
3030       case LibFunc_cosh:
3031       case LibFunc_sinhf:
3032       case LibFunc_coshf:
3033       case LibFunc_sinhl:
3034       case LibFunc_coshl:
3035         // FIXME: These boundaries are slightly conservative.
3036         if (OpC->getType()->isDoubleTy())
3037           return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
3038         if (OpC->getType()->isFloatTy())
3039           return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
3040         break;
3041 
3042       case LibFunc_sqrtl:
3043       case LibFunc_sqrt:
3044       case LibFunc_sqrtf:
3045         return Op.isNaN() || Op.isZero() || !Op.isNegative();
3046 
3047       // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
3048       // maybe others?
3049       default:
3050         break;
3051       }
3052     }
3053   }
3054 
3055   if (Call->getNumArgOperands() == 2) {
3056     ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
3057     ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
3058     if (Op0C && Op1C) {
3059       const APFloat &Op0 = Op0C->getValueAPF();
3060       const APFloat &Op1 = Op1C->getValueAPF();
3061 
3062       switch (Func) {
3063       case LibFunc_powl:
3064       case LibFunc_pow:
3065       case LibFunc_powf: {
3066         // FIXME: Stop using the host math library.
3067         // FIXME: The computation isn't done in the right precision.
3068         Type *Ty = Op0C->getType();
3069         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
3070           if (Ty == Op1C->getType()) {
3071             double Op0V = getValueAsDouble(Op0C);
3072             double Op1V = getValueAsDouble(Op1C);
3073             return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
3074           }
3075         }
3076         break;
3077       }
3078 
3079       case LibFunc_fmodl:
3080       case LibFunc_fmod:
3081       case LibFunc_fmodf:
3082       case LibFunc_remainderl:
3083       case LibFunc_remainder:
3084       case LibFunc_remainderf:
3085         return Op0.isNaN() || Op1.isNaN() ||
3086                (!Op0.isInfinity() && !Op1.isZero());
3087 
3088       default:
3089         break;
3090       }
3091     }
3092   }
3093 
3094   return false;
3095 }
3096 
3097 void TargetFolder::anchor() {}
3098