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