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