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