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