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::amdgcn_perm:
1474   case Intrinsic::arm_mve_vctp8:
1475   case Intrinsic::arm_mve_vctp16:
1476   case Intrinsic::arm_mve_vctp32:
1477   case Intrinsic::arm_mve_vctp64:
1478   case Intrinsic::aarch64_sve_convert_from_svbool:
1479   // WebAssembly float semantics are always known
1480   case Intrinsic::wasm_trunc_signed:
1481   case Intrinsic::wasm_trunc_unsigned:
1482     return true;
1483 
1484   // Floating point operations cannot be folded in strictfp functions in
1485   // general case. They can be folded if FP environment is known to compiler.
1486   case Intrinsic::minnum:
1487   case Intrinsic::maxnum:
1488   case Intrinsic::minimum:
1489   case Intrinsic::maximum:
1490   case Intrinsic::log:
1491   case Intrinsic::log2:
1492   case Intrinsic::log10:
1493   case Intrinsic::exp:
1494   case Intrinsic::exp2:
1495   case Intrinsic::sqrt:
1496   case Intrinsic::sin:
1497   case Intrinsic::cos:
1498   case Intrinsic::pow:
1499   case Intrinsic::powi:
1500   case Intrinsic::fma:
1501   case Intrinsic::fmuladd:
1502   case Intrinsic::fptoui_sat:
1503   case Intrinsic::fptosi_sat:
1504   case Intrinsic::convert_from_fp16:
1505   case Intrinsic::convert_to_fp16:
1506   case Intrinsic::amdgcn_cos:
1507   case Intrinsic::amdgcn_cubeid:
1508   case Intrinsic::amdgcn_cubema:
1509   case Intrinsic::amdgcn_cubesc:
1510   case Intrinsic::amdgcn_cubetc:
1511   case Intrinsic::amdgcn_fmul_legacy:
1512   case Intrinsic::amdgcn_fma_legacy:
1513   case Intrinsic::amdgcn_fract:
1514   case Intrinsic::amdgcn_ldexp:
1515   case Intrinsic::amdgcn_sin:
1516   // The intrinsics below depend on rounding mode in MXCSR.
1517   case Intrinsic::x86_sse_cvtss2si:
1518   case Intrinsic::x86_sse_cvtss2si64:
1519   case Intrinsic::x86_sse_cvttss2si:
1520   case Intrinsic::x86_sse_cvttss2si64:
1521   case Intrinsic::x86_sse2_cvtsd2si:
1522   case Intrinsic::x86_sse2_cvtsd2si64:
1523   case Intrinsic::x86_sse2_cvttsd2si:
1524   case Intrinsic::x86_sse2_cvttsd2si64:
1525   case Intrinsic::x86_avx512_vcvtss2si32:
1526   case Intrinsic::x86_avx512_vcvtss2si64:
1527   case Intrinsic::x86_avx512_cvttss2si:
1528   case Intrinsic::x86_avx512_cvttss2si64:
1529   case Intrinsic::x86_avx512_vcvtsd2si32:
1530   case Intrinsic::x86_avx512_vcvtsd2si64:
1531   case Intrinsic::x86_avx512_cvttsd2si:
1532   case Intrinsic::x86_avx512_cvttsd2si64:
1533   case Intrinsic::x86_avx512_vcvtss2usi32:
1534   case Intrinsic::x86_avx512_vcvtss2usi64:
1535   case Intrinsic::x86_avx512_cvttss2usi:
1536   case Intrinsic::x86_avx512_cvttss2usi64:
1537   case Intrinsic::x86_avx512_vcvtsd2usi32:
1538   case Intrinsic::x86_avx512_vcvtsd2usi64:
1539   case Intrinsic::x86_avx512_cvttsd2usi:
1540   case Intrinsic::x86_avx512_cvttsd2usi64:
1541     return !Call->isStrictFP();
1542 
1543   // Sign operations are actually bitwise operations, they do not raise
1544   // exceptions even for SNANs.
1545   case Intrinsic::fabs:
1546   case Intrinsic::copysign:
1547   // Non-constrained variants of rounding operations means default FP
1548   // environment, they can be folded in any case.
1549   case Intrinsic::ceil:
1550   case Intrinsic::floor:
1551   case Intrinsic::round:
1552   case Intrinsic::roundeven:
1553   case Intrinsic::trunc:
1554   case Intrinsic::nearbyint:
1555   case Intrinsic::rint:
1556   // Constrained intrinsics can be folded if FP environment is known
1557   // to compiler.
1558   case Intrinsic::experimental_constrained_ceil:
1559   case Intrinsic::experimental_constrained_floor:
1560   case Intrinsic::experimental_constrained_round:
1561   case Intrinsic::experimental_constrained_roundeven:
1562   case Intrinsic::experimental_constrained_trunc:
1563   case Intrinsic::experimental_constrained_nearbyint:
1564   case Intrinsic::experimental_constrained_rint:
1565     return true;
1566   default:
1567     return false;
1568   case Intrinsic::not_intrinsic: break;
1569   }
1570 
1571   if (!F->hasName() || Call->isStrictFP())
1572     return false;
1573 
1574   // In these cases, the check of the length is required.  We don't want to
1575   // return true for a name like "cos\0blah" which strcmp would return equal to
1576   // "cos", but has length 8.
1577   StringRef Name = F->getName();
1578   switch (Name[0]) {
1579   default:
1580     return false;
1581   case 'a':
1582     return Name == "acos" || Name == "acosf" ||
1583            Name == "asin" || Name == "asinf" ||
1584            Name == "atan" || Name == "atanf" ||
1585            Name == "atan2" || Name == "atan2f";
1586   case 'c':
1587     return Name == "ceil" || Name == "ceilf" ||
1588            Name == "cos" || Name == "cosf" ||
1589            Name == "cosh" || Name == "coshf";
1590   case 'e':
1591     return Name == "exp" || Name == "expf" ||
1592            Name == "exp2" || Name == "exp2f";
1593   case 'f':
1594     return Name == "fabs" || Name == "fabsf" ||
1595            Name == "floor" || Name == "floorf" ||
1596            Name == "fmod" || Name == "fmodf";
1597   case 'l':
1598     return Name == "log" || Name == "logf" ||
1599            Name == "log2" || Name == "log2f" ||
1600            Name == "log10" || Name == "log10f";
1601   case 'n':
1602     return Name == "nearbyint" || Name == "nearbyintf";
1603   case 'p':
1604     return Name == "pow" || Name == "powf";
1605   case 'r':
1606     return Name == "remainder" || Name == "remainderf" ||
1607            Name == "rint" || Name == "rintf" ||
1608            Name == "round" || Name == "roundf";
1609   case 's':
1610     return Name == "sin" || Name == "sinf" ||
1611            Name == "sinh" || Name == "sinhf" ||
1612            Name == "sqrt" || Name == "sqrtf";
1613   case 't':
1614     return Name == "tan" || Name == "tanf" ||
1615            Name == "tanh" || Name == "tanhf" ||
1616            Name == "trunc" || Name == "truncf";
1617   case '_':
1618     // Check for various function names that get used for the math functions
1619     // when the header files are preprocessed with the macro
1620     // __FINITE_MATH_ONLY__ enabled.
1621     // The '12' here is the length of the shortest name that can match.
1622     // We need to check the size before looking at Name[1] and Name[2]
1623     // so we may as well check a limit that will eliminate mismatches.
1624     if (Name.size() < 12 || Name[1] != '_')
1625       return false;
1626     switch (Name[2]) {
1627     default:
1628       return false;
1629     case 'a':
1630       return Name == "__acos_finite" || Name == "__acosf_finite" ||
1631              Name == "__asin_finite" || Name == "__asinf_finite" ||
1632              Name == "__atan2_finite" || Name == "__atan2f_finite";
1633     case 'c':
1634       return Name == "__cosh_finite" || Name == "__coshf_finite";
1635     case 'e':
1636       return Name == "__exp_finite" || Name == "__expf_finite" ||
1637              Name == "__exp2_finite" || Name == "__exp2f_finite";
1638     case 'l':
1639       return Name == "__log_finite" || Name == "__logf_finite" ||
1640              Name == "__log10_finite" || Name == "__log10f_finite";
1641     case 'p':
1642       return Name == "__pow_finite" || Name == "__powf_finite";
1643     case 's':
1644       return Name == "__sinh_finite" || Name == "__sinhf_finite";
1645     }
1646   }
1647 }
1648 
1649 namespace {
1650 
1651 Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1652   if (Ty->isHalfTy() || Ty->isFloatTy()) {
1653     APFloat APF(V);
1654     bool unused;
1655     APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused);
1656     return ConstantFP::get(Ty->getContext(), APF);
1657   }
1658   if (Ty->isDoubleTy())
1659     return ConstantFP::get(Ty->getContext(), APFloat(V));
1660   llvm_unreachable("Can only constant fold half/float/double");
1661 }
1662 
1663 /// Clear the floating-point exception state.
1664 inline void llvm_fenv_clearexcept() {
1665 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1666   feclearexcept(FE_ALL_EXCEPT);
1667 #endif
1668   errno = 0;
1669 }
1670 
1671 /// Test if a floating-point exception was raised.
1672 inline bool llvm_fenv_testexcept() {
1673   int errno_val = errno;
1674   if (errno_val == ERANGE || errno_val == EDOM)
1675     return true;
1676 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1677   if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1678     return true;
1679 #endif
1680   return false;
1681 }
1682 
1683 Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
1684   llvm_fenv_clearexcept();
1685   V = NativeFP(V);
1686   if (llvm_fenv_testexcept()) {
1687     llvm_fenv_clearexcept();
1688     return nullptr;
1689   }
1690 
1691   return GetConstantFoldFPValue(V, Ty);
1692 }
1693 
1694 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1695                                double W, Type *Ty) {
1696   llvm_fenv_clearexcept();
1697   V = NativeFP(V, W);
1698   if (llvm_fenv_testexcept()) {
1699     llvm_fenv_clearexcept();
1700     return nullptr;
1701   }
1702 
1703   return GetConstantFoldFPValue(V, Ty);
1704 }
1705 
1706 Constant *constantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) {
1707   FixedVectorType *VT = dyn_cast<FixedVectorType>(Op->getType());
1708   if (!VT)
1709     return nullptr;
1710 
1711   // This isn't strictly necessary, but handle the special/common case of zero:
1712   // all integer reductions of a zero input produce zero.
1713   if (isa<ConstantAggregateZero>(Op))
1714     return ConstantInt::get(VT->getElementType(), 0);
1715 
1716   // This is the same as the underlying binops - poison propagates.
1717   if (isa<PoisonValue>(Op))
1718     return PoisonValue::get(VT->getElementType());
1719 
1720   // TODO: Handle undef.
1721   if (!isa<ConstantVector>(Op) && !isa<ConstantDataVector>(Op))
1722     return nullptr;
1723 
1724   auto *EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(0U));
1725   if (!EltC)
1726     return nullptr;
1727 
1728   APInt Acc = EltC->getValue();
1729   for (unsigned I = 1, E = VT->getNumElements(); I != E; I++) {
1730     if (!(EltC = dyn_cast<ConstantInt>(Op->getAggregateElement(I))))
1731       return nullptr;
1732     const APInt &X = EltC->getValue();
1733     switch (IID) {
1734     case Intrinsic::vector_reduce_add:
1735       Acc = Acc + X;
1736       break;
1737     case Intrinsic::vector_reduce_mul:
1738       Acc = Acc * X;
1739       break;
1740     case Intrinsic::vector_reduce_and:
1741       Acc = Acc & X;
1742       break;
1743     case Intrinsic::vector_reduce_or:
1744       Acc = Acc | X;
1745       break;
1746     case Intrinsic::vector_reduce_xor:
1747       Acc = Acc ^ X;
1748       break;
1749     case Intrinsic::vector_reduce_smin:
1750       Acc = APIntOps::smin(Acc, X);
1751       break;
1752     case Intrinsic::vector_reduce_smax:
1753       Acc = APIntOps::smax(Acc, X);
1754       break;
1755     case Intrinsic::vector_reduce_umin:
1756       Acc = APIntOps::umin(Acc, X);
1757       break;
1758     case Intrinsic::vector_reduce_umax:
1759       Acc = APIntOps::umax(Acc, X);
1760       break;
1761     }
1762   }
1763 
1764   return ConstantInt::get(Op->getContext(), Acc);
1765 }
1766 
1767 /// Attempt to fold an SSE floating point to integer conversion of a constant
1768 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1769 /// used (toward nearest, ties to even). This matches the behavior of the
1770 /// non-truncating SSE instructions in the default rounding mode. The desired
1771 /// integer type Ty is used to select how many bits are available for the
1772 /// result. Returns null if the conversion cannot be performed, otherwise
1773 /// returns the Constant value resulting from the conversion.
1774 Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1775                                       Type *Ty, bool IsSigned) {
1776   // All of these conversion intrinsics form an integer of at most 64bits.
1777   unsigned ResultWidth = Ty->getIntegerBitWidth();
1778   assert(ResultWidth <= 64 &&
1779          "Can only constant fold conversions to 64 and 32 bit ints");
1780 
1781   uint64_t UIntVal;
1782   bool isExact = false;
1783   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1784                                               : APFloat::rmNearestTiesToEven;
1785   APFloat::opStatus status =
1786       Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1787                            IsSigned, mode, &isExact);
1788   if (status != APFloat::opOK &&
1789       (!roundTowardZero || status != APFloat::opInexact))
1790     return nullptr;
1791   return ConstantInt::get(Ty, UIntVal, IsSigned);
1792 }
1793 
1794 double getValueAsDouble(ConstantFP *Op) {
1795   Type *Ty = Op->getType();
1796 
1797   if (Ty->isFloatTy())
1798     return Op->getValueAPF().convertToFloat();
1799 
1800   if (Ty->isDoubleTy())
1801     return Op->getValueAPF().convertToDouble();
1802 
1803   bool unused;
1804   APFloat APF = Op->getValueAPF();
1805   APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
1806   return APF.convertToDouble();
1807 }
1808 
1809 static bool isManifestConstant(const Constant *c) {
1810   if (isa<ConstantData>(c)) {
1811     return true;
1812   } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) {
1813     for (const Value *subc : c->operand_values()) {
1814       if (!isManifestConstant(cast<Constant>(subc)))
1815         return false;
1816     }
1817     return true;
1818   }
1819   return false;
1820 }
1821 
1822 static bool getConstIntOrUndef(Value *Op, const APInt *&C) {
1823   if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1824     C = &CI->getValue();
1825     return true;
1826   }
1827   if (isa<UndefValue>(Op)) {
1828     C = nullptr;
1829     return true;
1830   }
1831   return false;
1832 }
1833 
1834 static Constant *ConstantFoldScalarCall1(StringRef Name,
1835                                          Intrinsic::ID IntrinsicID,
1836                                          Type *Ty,
1837                                          ArrayRef<Constant *> Operands,
1838                                          const TargetLibraryInfo *TLI,
1839                                          const CallBase *Call) {
1840   assert(Operands.size() == 1 && "Wrong number of operands.");
1841 
1842   if (IntrinsicID == Intrinsic::is_constant) {
1843     // We know we have a "Constant" argument. But we want to only
1844     // return true for manifest constants, not those that depend on
1845     // constants with unknowable values, e.g. GlobalValue or BlockAddress.
1846     if (isManifestConstant(Operands[0]))
1847       return ConstantInt::getTrue(Ty->getContext());
1848     return nullptr;
1849   }
1850   if (isa<UndefValue>(Operands[0])) {
1851     // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN.
1852     // ctpop() is between 0 and bitwidth, pick 0 for undef.
1853     // fptoui.sat and fptosi.sat can always fold to zero (for a zero input).
1854     if (IntrinsicID == Intrinsic::cos ||
1855         IntrinsicID == Intrinsic::ctpop ||
1856         IntrinsicID == Intrinsic::fptoui_sat ||
1857         IntrinsicID == Intrinsic::fptosi_sat)
1858       return Constant::getNullValue(Ty);
1859     if (IntrinsicID == Intrinsic::bswap ||
1860         IntrinsicID == Intrinsic::bitreverse ||
1861         IntrinsicID == Intrinsic::launder_invariant_group ||
1862         IntrinsicID == Intrinsic::strip_invariant_group)
1863       return Operands[0];
1864   }
1865 
1866   if (isa<ConstantPointerNull>(Operands[0])) {
1867     // launder(null) == null == strip(null) iff in addrspace 0
1868     if (IntrinsicID == Intrinsic::launder_invariant_group ||
1869         IntrinsicID == Intrinsic::strip_invariant_group) {
1870       // If instruction is not yet put in a basic block (e.g. when cloning
1871       // a function during inlining), Call's caller may not be available.
1872       // So check Call's BB first before querying Call->getCaller.
1873       const Function *Caller =
1874           Call->getParent() ? Call->getCaller() : nullptr;
1875       if (Caller &&
1876           !NullPointerIsDefined(
1877               Caller, Operands[0]->getType()->getPointerAddressSpace())) {
1878         return Operands[0];
1879       }
1880       return nullptr;
1881     }
1882   }
1883 
1884   if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
1885     if (IntrinsicID == Intrinsic::convert_to_fp16) {
1886       APFloat Val(Op->getValueAPF());
1887 
1888       bool lost = false;
1889       Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
1890 
1891       return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1892     }
1893 
1894     APFloat U = Op->getValueAPF();
1895 
1896     if (IntrinsicID == Intrinsic::wasm_trunc_signed ||
1897         IntrinsicID == Intrinsic::wasm_trunc_unsigned) {
1898       bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed;
1899 
1900       if (U.isNaN())
1901         return nullptr;
1902 
1903       unsigned Width = Ty->getIntegerBitWidth();
1904       APSInt Int(Width, !Signed);
1905       bool IsExact = false;
1906       APFloat::opStatus Status =
1907           U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
1908 
1909       if (Status == APFloat::opOK || Status == APFloat::opInexact)
1910         return ConstantInt::get(Ty, Int);
1911 
1912       return nullptr;
1913     }
1914 
1915     if (IntrinsicID == Intrinsic::fptoui_sat ||
1916         IntrinsicID == Intrinsic::fptosi_sat) {
1917       // convertToInteger() already has the desired saturation semantics.
1918       APSInt Int(Ty->getIntegerBitWidth(),
1919                  IntrinsicID == Intrinsic::fptoui_sat);
1920       bool IsExact;
1921       U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact);
1922       return ConstantInt::get(Ty, Int);
1923     }
1924 
1925     if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1926       return nullptr;
1927 
1928     // Use internal versions of these intrinsics.
1929 
1930     if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) {
1931       U.roundToIntegral(APFloat::rmNearestTiesToEven);
1932       return ConstantFP::get(Ty->getContext(), U);
1933     }
1934 
1935     if (IntrinsicID == Intrinsic::round) {
1936       U.roundToIntegral(APFloat::rmNearestTiesToAway);
1937       return ConstantFP::get(Ty->getContext(), U);
1938     }
1939 
1940     if (IntrinsicID == Intrinsic::roundeven) {
1941       U.roundToIntegral(APFloat::rmNearestTiesToEven);
1942       return ConstantFP::get(Ty->getContext(), U);
1943     }
1944 
1945     if (IntrinsicID == Intrinsic::ceil) {
1946       U.roundToIntegral(APFloat::rmTowardPositive);
1947       return ConstantFP::get(Ty->getContext(), U);
1948     }
1949 
1950     if (IntrinsicID == Intrinsic::floor) {
1951       U.roundToIntegral(APFloat::rmTowardNegative);
1952       return ConstantFP::get(Ty->getContext(), U);
1953     }
1954 
1955     if (IntrinsicID == Intrinsic::trunc) {
1956       U.roundToIntegral(APFloat::rmTowardZero);
1957       return ConstantFP::get(Ty->getContext(), U);
1958     }
1959 
1960     if (IntrinsicID == Intrinsic::fabs) {
1961       U.clearSign();
1962       return ConstantFP::get(Ty->getContext(), U);
1963     }
1964 
1965     if (IntrinsicID == Intrinsic::amdgcn_fract) {
1966       // The v_fract instruction behaves like the OpenCL spec, which defines
1967       // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is
1968       //   there to prevent fract(-small) from returning 1.0. It returns the
1969       //   largest positive floating-point number less than 1.0."
1970       APFloat FloorU(U);
1971       FloorU.roundToIntegral(APFloat::rmTowardNegative);
1972       APFloat FractU(U - FloorU);
1973       APFloat AlmostOne(U.getSemantics(), 1);
1974       AlmostOne.next(/*nextDown*/ true);
1975       return ConstantFP::get(Ty->getContext(), minimum(FractU, AlmostOne));
1976     }
1977 
1978     // Rounding operations (floor, trunc, ceil, round and nearbyint) do not
1979     // raise FP exceptions, unless the argument is signaling NaN.
1980 
1981     Optional<APFloat::roundingMode> RM;
1982     switch (IntrinsicID) {
1983     default:
1984       break;
1985     case Intrinsic::experimental_constrained_nearbyint:
1986     case Intrinsic::experimental_constrained_rint: {
1987       auto CI = cast<ConstrainedFPIntrinsic>(Call);
1988       RM = CI->getRoundingMode();
1989       if (!RM || RM.getValue() == RoundingMode::Dynamic)
1990         return nullptr;
1991       break;
1992     }
1993     case Intrinsic::experimental_constrained_round:
1994       RM = APFloat::rmNearestTiesToAway;
1995       break;
1996     case Intrinsic::experimental_constrained_ceil:
1997       RM = APFloat::rmTowardPositive;
1998       break;
1999     case Intrinsic::experimental_constrained_floor:
2000       RM = APFloat::rmTowardNegative;
2001       break;
2002     case Intrinsic::experimental_constrained_trunc:
2003       RM = APFloat::rmTowardZero;
2004       break;
2005     }
2006     if (RM) {
2007       auto CI = cast<ConstrainedFPIntrinsic>(Call);
2008       if (U.isFinite()) {
2009         APFloat::opStatus St = U.roundToIntegral(*RM);
2010         if (IntrinsicID == Intrinsic::experimental_constrained_rint &&
2011             St == APFloat::opInexact) {
2012           Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2013           if (EB && *EB == fp::ebStrict)
2014             return nullptr;
2015         }
2016       } else if (U.isSignaling()) {
2017         Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior();
2018         if (EB && *EB != fp::ebIgnore)
2019           return nullptr;
2020         U = APFloat::getQNaN(U.getSemantics());
2021       }
2022       return ConstantFP::get(Ty->getContext(), U);
2023     }
2024 
2025     /// We only fold functions with finite arguments. Folding NaN and inf is
2026     /// likely to be aborted with an exception anyway, and some host libms
2027     /// have known errors raising exceptions.
2028     if (!U.isFinite())
2029       return nullptr;
2030 
2031     /// Currently APFloat versions of these functions do not exist, so we use
2032     /// the host native double versions.  Float versions are not called
2033     /// directly but for all these it is true (float)(f((double)arg)) ==
2034     /// f(arg).  Long double not supported yet.
2035     double V = getValueAsDouble(Op);
2036 
2037     switch (IntrinsicID) {
2038       default: break;
2039       case Intrinsic::log:
2040         return ConstantFoldFP(log, V, Ty);
2041       case Intrinsic::log2:
2042         // TODO: What about hosts that lack a C99 library?
2043         return ConstantFoldFP(Log2, V, Ty);
2044       case Intrinsic::log10:
2045         // TODO: What about hosts that lack a C99 library?
2046         return ConstantFoldFP(log10, V, Ty);
2047       case Intrinsic::exp:
2048         return ConstantFoldFP(exp, V, Ty);
2049       case Intrinsic::exp2:
2050         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2051         return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
2052       case Intrinsic::sin:
2053         return ConstantFoldFP(sin, V, Ty);
2054       case Intrinsic::cos:
2055         return ConstantFoldFP(cos, V, Ty);
2056       case Intrinsic::sqrt:
2057         return ConstantFoldFP(sqrt, V, Ty);
2058       case Intrinsic::amdgcn_cos:
2059       case Intrinsic::amdgcn_sin:
2060         if (V < -256.0 || V > 256.0)
2061           // The gfx8 and gfx9 architectures handle arguments outside the range
2062           // [-256, 256] differently. This should be a rare case so bail out
2063           // rather than trying to handle the difference.
2064           return nullptr;
2065         bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos;
2066         double V4 = V * 4.0;
2067         if (V4 == floor(V4)) {
2068           // Force exact results for quarter-integer inputs.
2069           const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 };
2070           V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3];
2071         } else {
2072           if (IsCos)
2073             V = cos(V * 2.0 * numbers::pi);
2074           else
2075             V = sin(V * 2.0 * numbers::pi);
2076         }
2077         return GetConstantFoldFPValue(V, Ty);
2078     }
2079 
2080     if (!TLI)
2081       return nullptr;
2082 
2083     LibFunc Func = NotLibFunc;
2084     TLI->getLibFunc(Name, Func);
2085     switch (Func) {
2086     default:
2087       break;
2088     case LibFunc_acos:
2089     case LibFunc_acosf:
2090     case LibFunc_acos_finite:
2091     case LibFunc_acosf_finite:
2092       if (TLI->has(Func))
2093         return ConstantFoldFP(acos, V, Ty);
2094       break;
2095     case LibFunc_asin:
2096     case LibFunc_asinf:
2097     case LibFunc_asin_finite:
2098     case LibFunc_asinf_finite:
2099       if (TLI->has(Func))
2100         return ConstantFoldFP(asin, V, Ty);
2101       break;
2102     case LibFunc_atan:
2103     case LibFunc_atanf:
2104       if (TLI->has(Func))
2105         return ConstantFoldFP(atan, V, Ty);
2106       break;
2107     case LibFunc_ceil:
2108     case LibFunc_ceilf:
2109       if (TLI->has(Func)) {
2110         U.roundToIntegral(APFloat::rmTowardPositive);
2111         return ConstantFP::get(Ty->getContext(), U);
2112       }
2113       break;
2114     case LibFunc_cos:
2115     case LibFunc_cosf:
2116       if (TLI->has(Func))
2117         return ConstantFoldFP(cos, V, Ty);
2118       break;
2119     case LibFunc_cosh:
2120     case LibFunc_coshf:
2121     case LibFunc_cosh_finite:
2122     case LibFunc_coshf_finite:
2123       if (TLI->has(Func))
2124         return ConstantFoldFP(cosh, V, Ty);
2125       break;
2126     case LibFunc_exp:
2127     case LibFunc_expf:
2128     case LibFunc_exp_finite:
2129     case LibFunc_expf_finite:
2130       if (TLI->has(Func))
2131         return ConstantFoldFP(exp, V, Ty);
2132       break;
2133     case LibFunc_exp2:
2134     case LibFunc_exp2f:
2135     case LibFunc_exp2_finite:
2136     case LibFunc_exp2f_finite:
2137       if (TLI->has(Func))
2138         // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library.
2139         return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
2140       break;
2141     case LibFunc_fabs:
2142     case LibFunc_fabsf:
2143       if (TLI->has(Func)) {
2144         U.clearSign();
2145         return ConstantFP::get(Ty->getContext(), U);
2146       }
2147       break;
2148     case LibFunc_floor:
2149     case LibFunc_floorf:
2150       if (TLI->has(Func)) {
2151         U.roundToIntegral(APFloat::rmTowardNegative);
2152         return ConstantFP::get(Ty->getContext(), U);
2153       }
2154       break;
2155     case LibFunc_log:
2156     case LibFunc_logf:
2157     case LibFunc_log_finite:
2158     case LibFunc_logf_finite:
2159       if (V > 0.0 && TLI->has(Func))
2160         return ConstantFoldFP(log, V, Ty);
2161       break;
2162     case LibFunc_log2:
2163     case LibFunc_log2f:
2164     case LibFunc_log2_finite:
2165     case LibFunc_log2f_finite:
2166       if (V > 0.0 && TLI->has(Func))
2167         // TODO: What about hosts that lack a C99 library?
2168         return ConstantFoldFP(Log2, V, Ty);
2169       break;
2170     case LibFunc_log10:
2171     case LibFunc_log10f:
2172     case LibFunc_log10_finite:
2173     case LibFunc_log10f_finite:
2174       if (V > 0.0 && TLI->has(Func))
2175         // TODO: What about hosts that lack a C99 library?
2176         return ConstantFoldFP(log10, V, Ty);
2177       break;
2178     case LibFunc_nearbyint:
2179     case LibFunc_nearbyintf:
2180     case LibFunc_rint:
2181     case LibFunc_rintf:
2182       if (TLI->has(Func)) {
2183         U.roundToIntegral(APFloat::rmNearestTiesToEven);
2184         return ConstantFP::get(Ty->getContext(), U);
2185       }
2186       break;
2187     case LibFunc_round:
2188     case LibFunc_roundf:
2189       if (TLI->has(Func)) {
2190         U.roundToIntegral(APFloat::rmNearestTiesToAway);
2191         return ConstantFP::get(Ty->getContext(), U);
2192       }
2193       break;
2194     case LibFunc_sin:
2195     case LibFunc_sinf:
2196       if (TLI->has(Func))
2197         return ConstantFoldFP(sin, V, Ty);
2198       break;
2199     case LibFunc_sinh:
2200     case LibFunc_sinhf:
2201     case LibFunc_sinh_finite:
2202     case LibFunc_sinhf_finite:
2203       if (TLI->has(Func))
2204         return ConstantFoldFP(sinh, V, Ty);
2205       break;
2206     case LibFunc_sqrt:
2207     case LibFunc_sqrtf:
2208       if (V >= 0.0 && TLI->has(Func))
2209         return ConstantFoldFP(sqrt, V, Ty);
2210       break;
2211     case LibFunc_tan:
2212     case LibFunc_tanf:
2213       if (TLI->has(Func))
2214         return ConstantFoldFP(tan, V, Ty);
2215       break;
2216     case LibFunc_tanh:
2217     case LibFunc_tanhf:
2218       if (TLI->has(Func))
2219         return ConstantFoldFP(tanh, V, Ty);
2220       break;
2221     case LibFunc_trunc:
2222     case LibFunc_truncf:
2223       if (TLI->has(Func)) {
2224         U.roundToIntegral(APFloat::rmTowardZero);
2225         return ConstantFP::get(Ty->getContext(), U);
2226       }
2227       break;
2228     }
2229     return nullptr;
2230   }
2231 
2232   if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2233     switch (IntrinsicID) {
2234     case Intrinsic::bswap:
2235       return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
2236     case Intrinsic::ctpop:
2237       return ConstantInt::get(Ty, Op->getValue().countPopulation());
2238     case Intrinsic::bitreverse:
2239       return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
2240     case Intrinsic::convert_from_fp16: {
2241       APFloat Val(APFloat::IEEEhalf(), Op->getValue());
2242 
2243       bool lost = false;
2244       APFloat::opStatus status = Val.convert(
2245           Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
2246 
2247       // Conversion is always precise.
2248       (void)status;
2249       assert(status == APFloat::opOK && !lost &&
2250              "Precision lost during fp16 constfolding");
2251 
2252       return ConstantFP::get(Ty->getContext(), Val);
2253     }
2254     default:
2255       return nullptr;
2256     }
2257   }
2258 
2259   switch (IntrinsicID) {
2260   default: break;
2261   case Intrinsic::vector_reduce_add:
2262   case Intrinsic::vector_reduce_mul:
2263   case Intrinsic::vector_reduce_and:
2264   case Intrinsic::vector_reduce_or:
2265   case Intrinsic::vector_reduce_xor:
2266   case Intrinsic::vector_reduce_smin:
2267   case Intrinsic::vector_reduce_smax:
2268   case Intrinsic::vector_reduce_umin:
2269   case Intrinsic::vector_reduce_umax:
2270     if (Constant *C = constantFoldVectorReduce(IntrinsicID, Operands[0]))
2271       return C;
2272     break;
2273   }
2274 
2275   // Support ConstantVector in case we have an Undef in the top.
2276   if (isa<ConstantVector>(Operands[0]) ||
2277       isa<ConstantDataVector>(Operands[0])) {
2278     auto *Op = cast<Constant>(Operands[0]);
2279     switch (IntrinsicID) {
2280     default: break;
2281     case Intrinsic::x86_sse_cvtss2si:
2282     case Intrinsic::x86_sse_cvtss2si64:
2283     case Intrinsic::x86_sse2_cvtsd2si:
2284     case Intrinsic::x86_sse2_cvtsd2si64:
2285       if (ConstantFP *FPOp =
2286               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2287         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2288                                            /*roundTowardZero=*/false, Ty,
2289                                            /*IsSigned*/true);
2290       break;
2291     case Intrinsic::x86_sse_cvttss2si:
2292     case Intrinsic::x86_sse_cvttss2si64:
2293     case Intrinsic::x86_sse2_cvttsd2si:
2294     case Intrinsic::x86_sse2_cvttsd2si64:
2295       if (ConstantFP *FPOp =
2296               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2297         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2298                                            /*roundTowardZero=*/true, Ty,
2299                                            /*IsSigned*/true);
2300       break;
2301     }
2302   }
2303 
2304   return nullptr;
2305 }
2306 
2307 static Constant *ConstantFoldScalarCall2(StringRef Name,
2308                                          Intrinsic::ID IntrinsicID,
2309                                          Type *Ty,
2310                                          ArrayRef<Constant *> Operands,
2311                                          const TargetLibraryInfo *TLI,
2312                                          const CallBase *Call) {
2313   assert(Operands.size() == 2 && "Wrong number of operands.");
2314 
2315   if (Ty->isFloatingPointTy()) {
2316     // TODO: We should have undef handling for all of the FP intrinsics that
2317     //       are attempted to be folded in this function.
2318     bool IsOp0Undef = isa<UndefValue>(Operands[0]);
2319     bool IsOp1Undef = isa<UndefValue>(Operands[1]);
2320     switch (IntrinsicID) {
2321     case Intrinsic::maxnum:
2322     case Intrinsic::minnum:
2323     case Intrinsic::maximum:
2324     case Intrinsic::minimum:
2325       // If one argument is undef, return the other argument.
2326       if (IsOp0Undef)
2327         return Operands[1];
2328       if (IsOp1Undef)
2329         return Operands[0];
2330       break;
2331     }
2332   }
2333 
2334   if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2335     if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
2336       return nullptr;
2337     double Op1V = getValueAsDouble(Op1);
2338 
2339     if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2340       if (Op2->getType() != Op1->getType())
2341         return nullptr;
2342 
2343       double Op2V = getValueAsDouble(Op2);
2344       if (IntrinsicID == Intrinsic::pow) {
2345         return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2346       }
2347       if (IntrinsicID == Intrinsic::copysign) {
2348         APFloat V1 = Op1->getValueAPF();
2349         const APFloat &V2 = Op2->getValueAPF();
2350         V1.copySign(V2);
2351         return ConstantFP::get(Ty->getContext(), V1);
2352       }
2353 
2354       if (IntrinsicID == Intrinsic::minnum) {
2355         const APFloat &C1 = Op1->getValueAPF();
2356         const APFloat &C2 = Op2->getValueAPF();
2357         return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
2358       }
2359 
2360       if (IntrinsicID == Intrinsic::maxnum) {
2361         const APFloat &C1 = Op1->getValueAPF();
2362         const APFloat &C2 = Op2->getValueAPF();
2363         return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
2364       }
2365 
2366       if (IntrinsicID == Intrinsic::minimum) {
2367         const APFloat &C1 = Op1->getValueAPF();
2368         const APFloat &C2 = Op2->getValueAPF();
2369         return ConstantFP::get(Ty->getContext(), minimum(C1, C2));
2370       }
2371 
2372       if (IntrinsicID == Intrinsic::maximum) {
2373         const APFloat &C1 = Op1->getValueAPF();
2374         const APFloat &C2 = Op2->getValueAPF();
2375         return ConstantFP::get(Ty->getContext(), maximum(C1, C2));
2376       }
2377 
2378       if (IntrinsicID == Intrinsic::amdgcn_fmul_legacy) {
2379         const APFloat &C1 = Op1->getValueAPF();
2380         const APFloat &C2 = Op2->getValueAPF();
2381         // The legacy behaviour is that multiplying +/- 0.0 by anything, even
2382         // NaN or infinity, gives +0.0.
2383         if (C1.isZero() || C2.isZero())
2384           return ConstantFP::getNullValue(Ty);
2385         return ConstantFP::get(Ty->getContext(), C1 * C2);
2386       }
2387 
2388       if (!TLI)
2389         return nullptr;
2390 
2391       LibFunc Func = NotLibFunc;
2392       TLI->getLibFunc(Name, Func);
2393       switch (Func) {
2394       default:
2395         break;
2396       case LibFunc_pow:
2397       case LibFunc_powf:
2398       case LibFunc_pow_finite:
2399       case LibFunc_powf_finite:
2400         if (TLI->has(Func))
2401           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
2402         break;
2403       case LibFunc_fmod:
2404       case LibFunc_fmodf:
2405         if (TLI->has(Func)) {
2406           APFloat V = Op1->getValueAPF();
2407           if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF()))
2408             return ConstantFP::get(Ty->getContext(), V);
2409         }
2410         break;
2411       case LibFunc_remainder:
2412       case LibFunc_remainderf:
2413         if (TLI->has(Func)) {
2414           APFloat V = Op1->getValueAPF();
2415           if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF()))
2416             return ConstantFP::get(Ty->getContext(), V);
2417         }
2418         break;
2419       case LibFunc_atan2:
2420       case LibFunc_atan2f:
2421       case LibFunc_atan2_finite:
2422       case LibFunc_atan2f_finite:
2423         if (TLI->has(Func))
2424           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
2425         break;
2426       }
2427     } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
2428       if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
2429         return ConstantFP::get(Ty->getContext(),
2430                                APFloat((float)std::pow((float)Op1V,
2431                                                (int)Op2C->getZExtValue())));
2432       if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
2433         return ConstantFP::get(Ty->getContext(),
2434                                APFloat((float)std::pow((float)Op1V,
2435                                                (int)Op2C->getZExtValue())));
2436       if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
2437         return ConstantFP::get(Ty->getContext(),
2438                                APFloat((double)std::pow((double)Op1V,
2439                                                  (int)Op2C->getZExtValue())));
2440 
2441       if (IntrinsicID == Intrinsic::amdgcn_ldexp) {
2442         // FIXME: Should flush denorms depending on FP mode, but that's ignored
2443         // everywhere else.
2444 
2445         // scalbn is equivalent to ldexp with float radix 2
2446         APFloat Result = scalbn(Op1->getValueAPF(), Op2C->getSExtValue(),
2447                                 APFloat::rmNearestTiesToEven);
2448         return ConstantFP::get(Ty->getContext(), Result);
2449       }
2450     }
2451     return nullptr;
2452   }
2453 
2454   if (Operands[0]->getType()->isIntegerTy() &&
2455       Operands[1]->getType()->isIntegerTy()) {
2456     const APInt *C0, *C1;
2457     if (!getConstIntOrUndef(Operands[0], C0) ||
2458         !getConstIntOrUndef(Operands[1], C1))
2459       return nullptr;
2460 
2461     unsigned BitWidth = Ty->getScalarSizeInBits();
2462     switch (IntrinsicID) {
2463     default: break;
2464     case Intrinsic::smax:
2465       if (!C0 && !C1)
2466         return UndefValue::get(Ty);
2467       if (!C0 || !C1)
2468         return ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth));
2469       return ConstantInt::get(Ty, C0->sgt(*C1) ? *C0 : *C1);
2470 
2471     case Intrinsic::smin:
2472       if (!C0 && !C1)
2473         return UndefValue::get(Ty);
2474       if (!C0 || !C1)
2475         return ConstantInt::get(Ty, APInt::getSignedMinValue(BitWidth));
2476       return ConstantInt::get(Ty, C0->slt(*C1) ? *C0 : *C1);
2477 
2478     case Intrinsic::umax:
2479       if (!C0 && !C1)
2480         return UndefValue::get(Ty);
2481       if (!C0 || !C1)
2482         return ConstantInt::get(Ty, APInt::getMaxValue(BitWidth));
2483       return ConstantInt::get(Ty, C0->ugt(*C1) ? *C0 : *C1);
2484 
2485     case Intrinsic::umin:
2486       if (!C0 && !C1)
2487         return UndefValue::get(Ty);
2488       if (!C0 || !C1)
2489         return ConstantInt::get(Ty, APInt::getMinValue(BitWidth));
2490       return ConstantInt::get(Ty, C0->ult(*C1) ? *C0 : *C1);
2491 
2492     case Intrinsic::usub_with_overflow:
2493     case Intrinsic::ssub_with_overflow:
2494       // X - undef -> { 0, false }
2495       // undef - X -> { 0, false }
2496       if (!C0 || !C1)
2497         return Constant::getNullValue(Ty);
2498       LLVM_FALLTHROUGH;
2499     case Intrinsic::uadd_with_overflow:
2500     case Intrinsic::sadd_with_overflow:
2501       // X + undef -> { -1, false }
2502       // undef + x -> { -1, false }
2503       if (!C0 || !C1) {
2504         return ConstantStruct::get(
2505             cast<StructType>(Ty),
2506             {Constant::getAllOnesValue(Ty->getStructElementType(0)),
2507              Constant::getNullValue(Ty->getStructElementType(1))});
2508       }
2509       LLVM_FALLTHROUGH;
2510     case Intrinsic::smul_with_overflow:
2511     case Intrinsic::umul_with_overflow: {
2512       // undef * X -> { 0, false }
2513       // X * undef -> { 0, false }
2514       if (!C0 || !C1)
2515         return Constant::getNullValue(Ty);
2516 
2517       APInt Res;
2518       bool Overflow;
2519       switch (IntrinsicID) {
2520       default: llvm_unreachable("Invalid case");
2521       case Intrinsic::sadd_with_overflow:
2522         Res = C0->sadd_ov(*C1, Overflow);
2523         break;
2524       case Intrinsic::uadd_with_overflow:
2525         Res = C0->uadd_ov(*C1, Overflow);
2526         break;
2527       case Intrinsic::ssub_with_overflow:
2528         Res = C0->ssub_ov(*C1, Overflow);
2529         break;
2530       case Intrinsic::usub_with_overflow:
2531         Res = C0->usub_ov(*C1, Overflow);
2532         break;
2533       case Intrinsic::smul_with_overflow:
2534         Res = C0->smul_ov(*C1, Overflow);
2535         break;
2536       case Intrinsic::umul_with_overflow:
2537         Res = C0->umul_ov(*C1, Overflow);
2538         break;
2539       }
2540       Constant *Ops[] = {
2541         ConstantInt::get(Ty->getContext(), Res),
2542         ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
2543       };
2544       return ConstantStruct::get(cast<StructType>(Ty), Ops);
2545     }
2546     case Intrinsic::uadd_sat:
2547     case Intrinsic::sadd_sat:
2548       if (!C0 && !C1)
2549         return UndefValue::get(Ty);
2550       if (!C0 || !C1)
2551         return Constant::getAllOnesValue(Ty);
2552       if (IntrinsicID == Intrinsic::uadd_sat)
2553         return ConstantInt::get(Ty, C0->uadd_sat(*C1));
2554       else
2555         return ConstantInt::get(Ty, C0->sadd_sat(*C1));
2556     case Intrinsic::usub_sat:
2557     case Intrinsic::ssub_sat:
2558       if (!C0 && !C1)
2559         return UndefValue::get(Ty);
2560       if (!C0 || !C1)
2561         return Constant::getNullValue(Ty);
2562       if (IntrinsicID == Intrinsic::usub_sat)
2563         return ConstantInt::get(Ty, C0->usub_sat(*C1));
2564       else
2565         return ConstantInt::get(Ty, C0->ssub_sat(*C1));
2566     case Intrinsic::cttz:
2567     case Intrinsic::ctlz:
2568       assert(C1 && "Must be constant int");
2569 
2570       // cttz(0, 1) and ctlz(0, 1) are undef.
2571       if (C1->isOneValue() && (!C0 || C0->isNullValue()))
2572         return UndefValue::get(Ty);
2573       if (!C0)
2574         return Constant::getNullValue(Ty);
2575       if (IntrinsicID == Intrinsic::cttz)
2576         return ConstantInt::get(Ty, C0->countTrailingZeros());
2577       else
2578         return ConstantInt::get(Ty, C0->countLeadingZeros());
2579 
2580     case Intrinsic::abs:
2581       // Undef or minimum val operand with poison min --> undef
2582       assert(C1 && "Must be constant int");
2583       if (C1->isOneValue() && (!C0 || C0->isMinSignedValue()))
2584         return UndefValue::get(Ty);
2585 
2586       // Undef operand with no poison min --> 0 (sign bit must be clear)
2587       if (C1->isNullValue() && !C0)
2588         return Constant::getNullValue(Ty);
2589 
2590       return ConstantInt::get(Ty, C0->abs());
2591     }
2592 
2593     return nullptr;
2594   }
2595 
2596   // Support ConstantVector in case we have an Undef in the top.
2597   if ((isa<ConstantVector>(Operands[0]) ||
2598        isa<ConstantDataVector>(Operands[0])) &&
2599       // Check for default rounding mode.
2600       // FIXME: Support other rounding modes?
2601       isa<ConstantInt>(Operands[1]) &&
2602       cast<ConstantInt>(Operands[1])->getValue() == 4) {
2603     auto *Op = cast<Constant>(Operands[0]);
2604     switch (IntrinsicID) {
2605     default: break;
2606     case Intrinsic::x86_avx512_vcvtss2si32:
2607     case Intrinsic::x86_avx512_vcvtss2si64:
2608     case Intrinsic::x86_avx512_vcvtsd2si32:
2609     case Intrinsic::x86_avx512_vcvtsd2si64:
2610       if (ConstantFP *FPOp =
2611               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2612         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2613                                            /*roundTowardZero=*/false, Ty,
2614                                            /*IsSigned*/true);
2615       break;
2616     case Intrinsic::x86_avx512_vcvtss2usi32:
2617     case Intrinsic::x86_avx512_vcvtss2usi64:
2618     case Intrinsic::x86_avx512_vcvtsd2usi32:
2619     case Intrinsic::x86_avx512_vcvtsd2usi64:
2620       if (ConstantFP *FPOp =
2621               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2622         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2623                                            /*roundTowardZero=*/false, Ty,
2624                                            /*IsSigned*/false);
2625       break;
2626     case Intrinsic::x86_avx512_cvttss2si:
2627     case Intrinsic::x86_avx512_cvttss2si64:
2628     case Intrinsic::x86_avx512_cvttsd2si:
2629     case Intrinsic::x86_avx512_cvttsd2si64:
2630       if (ConstantFP *FPOp =
2631               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2632         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2633                                            /*roundTowardZero=*/true, Ty,
2634                                            /*IsSigned*/true);
2635       break;
2636     case Intrinsic::x86_avx512_cvttss2usi:
2637     case Intrinsic::x86_avx512_cvttss2usi64:
2638     case Intrinsic::x86_avx512_cvttsd2usi:
2639     case Intrinsic::x86_avx512_cvttsd2usi64:
2640       if (ConstantFP *FPOp =
2641               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
2642         return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
2643                                            /*roundTowardZero=*/true, Ty,
2644                                            /*IsSigned*/false);
2645       break;
2646     }
2647   }
2648   return nullptr;
2649 }
2650 
2651 static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID,
2652                                                const APFloat &S0,
2653                                                const APFloat &S1,
2654                                                const APFloat &S2) {
2655   unsigned ID;
2656   const fltSemantics &Sem = S0.getSemantics();
2657   APFloat MA(Sem), SC(Sem), TC(Sem);
2658   if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) {
2659     if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) {
2660       // S2 < 0
2661       ID = 5;
2662       SC = -S0;
2663     } else {
2664       ID = 4;
2665       SC = S0;
2666     }
2667     MA = S2;
2668     TC = -S1;
2669   } else if (abs(S1) >= abs(S0)) {
2670     if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) {
2671       // S1 < 0
2672       ID = 3;
2673       TC = -S2;
2674     } else {
2675       ID = 2;
2676       TC = S2;
2677     }
2678     MA = S1;
2679     SC = S0;
2680   } else {
2681     if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) {
2682       // S0 < 0
2683       ID = 1;
2684       SC = S2;
2685     } else {
2686       ID = 0;
2687       SC = -S2;
2688     }
2689     MA = S0;
2690     TC = -S1;
2691   }
2692   switch (IntrinsicID) {
2693   default:
2694     llvm_unreachable("unhandled amdgcn cube intrinsic");
2695   case Intrinsic::amdgcn_cubeid:
2696     return APFloat(Sem, ID);
2697   case Intrinsic::amdgcn_cubema:
2698     return MA + MA;
2699   case Intrinsic::amdgcn_cubesc:
2700     return SC;
2701   case Intrinsic::amdgcn_cubetc:
2702     return TC;
2703   }
2704 }
2705 
2706 static Constant *ConstantFoldAMDGCNPermIntrinsic(ArrayRef<Constant *> Operands,
2707                                                  Type *Ty) {
2708   const APInt *C0, *C1, *C2;
2709   if (!getConstIntOrUndef(Operands[0], C0) ||
2710       !getConstIntOrUndef(Operands[1], C1) ||
2711       !getConstIntOrUndef(Operands[2], C2))
2712     return nullptr;
2713 
2714   if (!C2)
2715     return UndefValue::get(Ty);
2716 
2717   APInt Val(32, 0);
2718   unsigned NumUndefBytes = 0;
2719   for (unsigned I = 0; I < 32; I += 8) {
2720     unsigned Sel = C2->extractBitsAsZExtValue(8, I);
2721     unsigned B = 0;
2722 
2723     if (Sel >= 13)
2724       B = 0xff;
2725     else if (Sel == 12)
2726       B = 0x00;
2727     else {
2728       const APInt *Src = ((Sel & 10) == 10 || (Sel & 12) == 4) ? C0 : C1;
2729       if (!Src)
2730         ++NumUndefBytes;
2731       else if (Sel < 8)
2732         B = Src->extractBitsAsZExtValue(8, (Sel & 3) * 8);
2733       else
2734         B = Src->extractBitsAsZExtValue(1, (Sel & 1) ? 31 : 15) * 0xff;
2735     }
2736 
2737     Val.insertBits(B, I, 8);
2738   }
2739 
2740   if (NumUndefBytes == 4)
2741     return UndefValue::get(Ty);
2742 
2743   return ConstantInt::get(Ty, Val);
2744 }
2745 
2746 static Constant *ConstantFoldScalarCall3(StringRef Name,
2747                                          Intrinsic::ID IntrinsicID,
2748                                          Type *Ty,
2749                                          ArrayRef<Constant *> Operands,
2750                                          const TargetLibraryInfo *TLI,
2751                                          const CallBase *Call) {
2752   assert(Operands.size() == 3 && "Wrong number of operands.");
2753 
2754   if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
2755     if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
2756       if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
2757         switch (IntrinsicID) {
2758         default: break;
2759         case Intrinsic::amdgcn_fma_legacy: {
2760           const APFloat &C1 = Op1->getValueAPF();
2761           const APFloat &C2 = Op2->getValueAPF();
2762           // The legacy behaviour is that multiplying +/- 0.0 by anything, even
2763           // NaN or infinity, gives +0.0.
2764           if (C1.isZero() || C2.isZero()) {
2765             const APFloat &C3 = Op3->getValueAPF();
2766             // It's tempting to just return C3 here, but that would give the
2767             // wrong result if C3 was -0.0.
2768             return ConstantFP::get(Ty->getContext(), APFloat(0.0f) + C3);
2769           }
2770           LLVM_FALLTHROUGH;
2771         }
2772         case Intrinsic::fma:
2773         case Intrinsic::fmuladd: {
2774           APFloat V = Op1->getValueAPF();
2775           V.fusedMultiplyAdd(Op2->getValueAPF(), Op3->getValueAPF(),
2776                              APFloat::rmNearestTiesToEven);
2777           return ConstantFP::get(Ty->getContext(), V);
2778         }
2779         case Intrinsic::amdgcn_cubeid:
2780         case Intrinsic::amdgcn_cubema:
2781         case Intrinsic::amdgcn_cubesc:
2782         case Intrinsic::amdgcn_cubetc: {
2783           APFloat V = ConstantFoldAMDGCNCubeIntrinsic(
2784               IntrinsicID, Op1->getValueAPF(), Op2->getValueAPF(),
2785               Op3->getValueAPF());
2786           return ConstantFP::get(Ty->getContext(), V);
2787         }
2788         }
2789       }
2790     }
2791   }
2792 
2793   if (IntrinsicID == Intrinsic::smul_fix ||
2794       IntrinsicID == Intrinsic::smul_fix_sat) {
2795     // poison * C -> poison
2796     // C * poison -> poison
2797     if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
2798       return PoisonValue::get(Ty);
2799 
2800     const APInt *C0, *C1;
2801     if (!getConstIntOrUndef(Operands[0], C0) ||
2802         !getConstIntOrUndef(Operands[1], C1))
2803       return nullptr;
2804 
2805     // undef * C -> 0
2806     // C * undef -> 0
2807     if (!C0 || !C1)
2808       return Constant::getNullValue(Ty);
2809 
2810     // This code performs rounding towards negative infinity in case the result
2811     // cannot be represented exactly for the given scale. Targets that do care
2812     // about rounding should use a target hook for specifying how rounding
2813     // should be done, and provide their own folding to be consistent with
2814     // rounding. This is the same approach as used by
2815     // DAGTypeLegalizer::ExpandIntRes_MULFIX.
2816     unsigned Scale = cast<ConstantInt>(Operands[2])->getZExtValue();
2817     unsigned Width = C0->getBitWidth();
2818     assert(Scale < Width && "Illegal scale.");
2819     unsigned ExtendedWidth = Width * 2;
2820     APInt Product = (C0->sextOrSelf(ExtendedWidth) *
2821                      C1->sextOrSelf(ExtendedWidth)).ashr(Scale);
2822     if (IntrinsicID == Intrinsic::smul_fix_sat) {
2823       APInt Max = APInt::getSignedMaxValue(Width).sextOrSelf(ExtendedWidth);
2824       APInt Min = APInt::getSignedMinValue(Width).sextOrSelf(ExtendedWidth);
2825       Product = APIntOps::smin(Product, Max);
2826       Product = APIntOps::smax(Product, Min);
2827     }
2828     return ConstantInt::get(Ty->getContext(), Product.sextOrTrunc(Width));
2829   }
2830 
2831   if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) {
2832     const APInt *C0, *C1, *C2;
2833     if (!getConstIntOrUndef(Operands[0], C0) ||
2834         !getConstIntOrUndef(Operands[1], C1) ||
2835         !getConstIntOrUndef(Operands[2], C2))
2836       return nullptr;
2837 
2838     bool IsRight = IntrinsicID == Intrinsic::fshr;
2839     if (!C2)
2840       return Operands[IsRight ? 1 : 0];
2841     if (!C0 && !C1)
2842       return UndefValue::get(Ty);
2843 
2844     // The shift amount is interpreted as modulo the bitwidth. If the shift
2845     // amount is effectively 0, avoid UB due to oversized inverse shift below.
2846     unsigned BitWidth = C2->getBitWidth();
2847     unsigned ShAmt = C2->urem(BitWidth);
2848     if (!ShAmt)
2849       return Operands[IsRight ? 1 : 0];
2850 
2851     // (C0 << ShlAmt) | (C1 >> LshrAmt)
2852     unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt;
2853     unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt;
2854     if (!C0)
2855       return ConstantInt::get(Ty, C1->lshr(LshrAmt));
2856     if (!C1)
2857       return ConstantInt::get(Ty, C0->shl(ShlAmt));
2858     return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt));
2859   }
2860 
2861   if (IntrinsicID == Intrinsic::amdgcn_perm)
2862     return ConstantFoldAMDGCNPermIntrinsic(Operands, Ty);
2863 
2864   return nullptr;
2865 }
2866 
2867 static Constant *ConstantFoldScalarCall(StringRef Name,
2868                                         Intrinsic::ID IntrinsicID,
2869                                         Type *Ty,
2870                                         ArrayRef<Constant *> Operands,
2871                                         const TargetLibraryInfo *TLI,
2872                                         const CallBase *Call) {
2873   if (Operands.size() == 1)
2874     return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call);
2875 
2876   if (Operands.size() == 2)
2877     return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call);
2878 
2879   if (Operands.size() == 3)
2880     return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call);
2881 
2882   return nullptr;
2883 }
2884 
2885 static Constant *ConstantFoldFixedVectorCall(
2886     StringRef Name, Intrinsic::ID IntrinsicID, FixedVectorType *FVTy,
2887     ArrayRef<Constant *> Operands, const DataLayout &DL,
2888     const TargetLibraryInfo *TLI, const CallBase *Call) {
2889   SmallVector<Constant *, 4> Result(FVTy->getNumElements());
2890   SmallVector<Constant *, 4> Lane(Operands.size());
2891   Type *Ty = FVTy->getElementType();
2892 
2893   switch (IntrinsicID) {
2894   case Intrinsic::masked_load: {
2895     auto *SrcPtr = Operands[0];
2896     auto *Mask = Operands[2];
2897     auto *Passthru = Operands[3];
2898 
2899     Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL);
2900 
2901     SmallVector<Constant *, 32> NewElements;
2902     for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
2903       auto *MaskElt = Mask->getAggregateElement(I);
2904       if (!MaskElt)
2905         break;
2906       auto *PassthruElt = Passthru->getAggregateElement(I);
2907       auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2908       if (isa<UndefValue>(MaskElt)) {
2909         if (PassthruElt)
2910           NewElements.push_back(PassthruElt);
2911         else if (VecElt)
2912           NewElements.push_back(VecElt);
2913         else
2914           return nullptr;
2915       }
2916       if (MaskElt->isNullValue()) {
2917         if (!PassthruElt)
2918           return nullptr;
2919         NewElements.push_back(PassthruElt);
2920       } else if (MaskElt->isOneValue()) {
2921         if (!VecElt)
2922           return nullptr;
2923         NewElements.push_back(VecElt);
2924       } else {
2925         return nullptr;
2926       }
2927     }
2928     if (NewElements.size() != FVTy->getNumElements())
2929       return nullptr;
2930     return ConstantVector::get(NewElements);
2931   }
2932   case Intrinsic::arm_mve_vctp8:
2933   case Intrinsic::arm_mve_vctp16:
2934   case Intrinsic::arm_mve_vctp32:
2935   case Intrinsic::arm_mve_vctp64: {
2936     if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
2937       unsigned Lanes = FVTy->getNumElements();
2938       uint64_t Limit = Op->getZExtValue();
2939       // vctp64 are currently modelled as returning a v4i1, not a v2i1. Make
2940       // sure we get the limit right in that case and set all relevant lanes.
2941       if (IntrinsicID == Intrinsic::arm_mve_vctp64)
2942         Limit *= 2;
2943 
2944       SmallVector<Constant *, 16> NCs;
2945       for (unsigned i = 0; i < Lanes; i++) {
2946         if (i < Limit)
2947           NCs.push_back(ConstantInt::getTrue(Ty));
2948         else
2949           NCs.push_back(ConstantInt::getFalse(Ty));
2950       }
2951       return ConstantVector::get(NCs);
2952     }
2953     break;
2954   }
2955   case Intrinsic::get_active_lane_mask: {
2956     auto *Op0 = dyn_cast<ConstantInt>(Operands[0]);
2957     auto *Op1 = dyn_cast<ConstantInt>(Operands[1]);
2958     if (Op0 && Op1) {
2959       unsigned Lanes = FVTy->getNumElements();
2960       uint64_t Base = Op0->getZExtValue();
2961       uint64_t Limit = Op1->getZExtValue();
2962 
2963       SmallVector<Constant *, 16> NCs;
2964       for (unsigned i = 0; i < Lanes; i++) {
2965         if (Base + i < Limit)
2966           NCs.push_back(ConstantInt::getTrue(Ty));
2967         else
2968           NCs.push_back(ConstantInt::getFalse(Ty));
2969       }
2970       return ConstantVector::get(NCs);
2971     }
2972     break;
2973   }
2974   default:
2975     break;
2976   }
2977 
2978   for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) {
2979     // Gather a column of constants.
2980     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
2981       // Some intrinsics use a scalar type for certain arguments.
2982       if (hasVectorInstrinsicScalarOpd(IntrinsicID, J)) {
2983         Lane[J] = Operands[J];
2984         continue;
2985       }
2986 
2987       Constant *Agg = Operands[J]->getAggregateElement(I);
2988       if (!Agg)
2989         return nullptr;
2990 
2991       Lane[J] = Agg;
2992     }
2993 
2994     // Use the regular scalar folding to simplify this column.
2995     Constant *Folded =
2996         ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call);
2997     if (!Folded)
2998       return nullptr;
2999     Result[I] = Folded;
3000   }
3001 
3002   return ConstantVector::get(Result);
3003 }
3004 
3005 static Constant *ConstantFoldScalableVectorCall(
3006     StringRef Name, Intrinsic::ID IntrinsicID, ScalableVectorType *SVTy,
3007     ArrayRef<Constant *> Operands, const DataLayout &DL,
3008     const TargetLibraryInfo *TLI, const CallBase *Call) {
3009   switch (IntrinsicID) {
3010   case Intrinsic::aarch64_sve_convert_from_svbool: {
3011     auto *Src = dyn_cast<Constant>(Operands[0]);
3012     if (!Src || !Src->isNullValue())
3013       break;
3014 
3015     return ConstantInt::getFalse(SVTy);
3016   }
3017   default:
3018     break;
3019   }
3020   return nullptr;
3021 }
3022 
3023 } // end anonymous namespace
3024 
3025 Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F,
3026                                  ArrayRef<Constant *> Operands,
3027                                  const TargetLibraryInfo *TLI) {
3028   if (Call->isNoBuiltin())
3029     return nullptr;
3030   if (!F->hasName())
3031     return nullptr;
3032   StringRef Name = F->getName();
3033 
3034   Type *Ty = F->getReturnType();
3035 
3036   if (auto *FVTy = dyn_cast<FixedVectorType>(Ty))
3037     return ConstantFoldFixedVectorCall(
3038         Name, F->getIntrinsicID(), FVTy, Operands,
3039         F->getParent()->getDataLayout(), TLI, Call);
3040 
3041   if (auto *SVTy = dyn_cast<ScalableVectorType>(Ty))
3042     return ConstantFoldScalableVectorCall(
3043         Name, F->getIntrinsicID(), SVTy, Operands,
3044         F->getParent()->getDataLayout(), TLI, Call);
3045 
3046   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI,
3047                                 Call);
3048 }
3049 
3050 bool llvm::isMathLibCallNoop(const CallBase *Call,
3051                              const TargetLibraryInfo *TLI) {
3052   // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
3053   // (and to some extent ConstantFoldScalarCall).
3054   if (Call->isNoBuiltin() || Call->isStrictFP())
3055     return false;
3056   Function *F = Call->getCalledFunction();
3057   if (!F)
3058     return false;
3059 
3060   LibFunc Func;
3061   if (!TLI || !TLI->getLibFunc(*F, Func))
3062     return false;
3063 
3064   if (Call->getNumArgOperands() == 1) {
3065     if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) {
3066       const APFloat &Op = OpC->getValueAPF();
3067       switch (Func) {
3068       case LibFunc_logl:
3069       case LibFunc_log:
3070       case LibFunc_logf:
3071       case LibFunc_log2l:
3072       case LibFunc_log2:
3073       case LibFunc_log2f:
3074       case LibFunc_log10l:
3075       case LibFunc_log10:
3076       case LibFunc_log10f:
3077         return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
3078 
3079       case LibFunc_expl:
3080       case LibFunc_exp:
3081       case LibFunc_expf:
3082         // FIXME: These boundaries are slightly conservative.
3083         if (OpC->getType()->isDoubleTy())
3084           return !(Op < APFloat(-745.0) || Op > APFloat(709.0));
3085         if (OpC->getType()->isFloatTy())
3086           return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f));
3087         break;
3088 
3089       case LibFunc_exp2l:
3090       case LibFunc_exp2:
3091       case LibFunc_exp2f:
3092         // FIXME: These boundaries are slightly conservative.
3093         if (OpC->getType()->isDoubleTy())
3094           return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0));
3095         if (OpC->getType()->isFloatTy())
3096           return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f));
3097         break;
3098 
3099       case LibFunc_sinl:
3100       case LibFunc_sin:
3101       case LibFunc_sinf:
3102       case LibFunc_cosl:
3103       case LibFunc_cos:
3104       case LibFunc_cosf:
3105         return !Op.isInfinity();
3106 
3107       case LibFunc_tanl:
3108       case LibFunc_tan:
3109       case LibFunc_tanf: {
3110         // FIXME: Stop using the host math library.
3111         // FIXME: The computation isn't done in the right precision.
3112         Type *Ty = OpC->getType();
3113         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
3114           double OpV = getValueAsDouble(OpC);
3115           return ConstantFoldFP(tan, OpV, Ty) != nullptr;
3116         }
3117         break;
3118       }
3119 
3120       case LibFunc_asinl:
3121       case LibFunc_asin:
3122       case LibFunc_asinf:
3123       case LibFunc_acosl:
3124       case LibFunc_acos:
3125       case LibFunc_acosf:
3126         return !(Op < APFloat(Op.getSemantics(), "-1") ||
3127                  Op > APFloat(Op.getSemantics(), "1"));
3128 
3129       case LibFunc_sinh:
3130       case LibFunc_cosh:
3131       case LibFunc_sinhf:
3132       case LibFunc_coshf:
3133       case LibFunc_sinhl:
3134       case LibFunc_coshl:
3135         // FIXME: These boundaries are slightly conservative.
3136         if (OpC->getType()->isDoubleTy())
3137           return !(Op < APFloat(-710.0) || Op > APFloat(710.0));
3138         if (OpC->getType()->isFloatTy())
3139           return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f));
3140         break;
3141 
3142       case LibFunc_sqrtl:
3143       case LibFunc_sqrt:
3144       case LibFunc_sqrtf:
3145         return Op.isNaN() || Op.isZero() || !Op.isNegative();
3146 
3147       // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
3148       // maybe others?
3149       default:
3150         break;
3151       }
3152     }
3153   }
3154 
3155   if (Call->getNumArgOperands() == 2) {
3156     ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0));
3157     ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1));
3158     if (Op0C && Op1C) {
3159       const APFloat &Op0 = Op0C->getValueAPF();
3160       const APFloat &Op1 = Op1C->getValueAPF();
3161 
3162       switch (Func) {
3163       case LibFunc_powl:
3164       case LibFunc_pow:
3165       case LibFunc_powf: {
3166         // FIXME: Stop using the host math library.
3167         // FIXME: The computation isn't done in the right precision.
3168         Type *Ty = Op0C->getType();
3169         if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
3170           if (Ty == Op1C->getType()) {
3171             double Op0V = getValueAsDouble(Op0C);
3172             double Op1V = getValueAsDouble(Op1C);
3173             return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
3174           }
3175         }
3176         break;
3177       }
3178 
3179       case LibFunc_fmodl:
3180       case LibFunc_fmod:
3181       case LibFunc_fmodf:
3182       case LibFunc_remainderl:
3183       case LibFunc_remainder:
3184       case LibFunc_remainderf:
3185         return Op0.isNaN() || Op1.isNaN() ||
3186                (!Op0.isInfinity() && !Op1.isZero());
3187 
3188       default:
3189         break;
3190       }
3191     }
3192   }
3193 
3194   return false;
3195 }
3196 
3197 void TargetFolder::anchor() {}
3198