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