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