1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines routines for folding instructions into constants.
11 //
12 // Also, to supplement the basic IR ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // DataLayout information. These functions cannot go in IR due to library
15 // dependency issues.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GetElementPtrTypeIterator.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include <cassert>
38 #include <cerrno>
39 #include <cfenv>
40 #include <cmath>
41 #include <limits>
42 
43 using namespace llvm;
44 
45 namespace {
46 
47 //===----------------------------------------------------------------------===//
48 // Constant Folding internal helper functions
49 //===----------------------------------------------------------------------===//
50 
51 /// Constant fold bitcast, symbolically evaluating it with DataLayout.
52 /// This always returns a non-null constant, but it may be a
53 /// ConstantExpr if unfoldable.
54 Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
55   // Catch the obvious splat cases.
56   if (C->isNullValue() && !DestTy->isX86_MMXTy())
57     return Constant::getNullValue(DestTy);
58   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
59       !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
60     return Constant::getAllOnesValue(DestTy);
61 
62   // Handle a vector->integer cast.
63   if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
64     VectorType *VTy = dyn_cast<VectorType>(C->getType());
65     if (!VTy)
66       return ConstantExpr::getBitCast(C, DestTy);
67 
68     unsigned NumSrcElts = VTy->getNumElements();
69     Type *SrcEltTy = VTy->getElementType();
70 
71     // If the vector is a vector of floating point, convert it to vector of int
72     // to simplify things.
73     if (SrcEltTy->isFloatingPointTy()) {
74       unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
75       Type *SrcIVTy =
76         VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
77       // Ask IR to do the conversion now that #elts line up.
78       C = ConstantExpr::getBitCast(C, SrcIVTy);
79     }
80 
81     ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
82     if (!CDV)
83       return ConstantExpr::getBitCast(C, DestTy);
84 
85     // Now that we know that the input value is a vector of integers, just shift
86     // and insert them into our result.
87     unsigned BitShift = DL.getTypeAllocSizeInBits(SrcEltTy);
88     APInt Result(IT->getBitWidth(), 0);
89     for (unsigned i = 0; i != NumSrcElts; ++i) {
90       Result <<= BitShift;
91       if (DL.isLittleEndian())
92         Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
93       else
94         Result |= CDV->getElementAsInteger(i);
95     }
96 
97     return ConstantInt::get(IT, Result);
98   }
99 
100   // The code below only handles casts to vectors currently.
101   VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
102   if (!DestVTy)
103     return ConstantExpr::getBitCast(C, DestTy);
104 
105   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
106   // vector so the code below can handle it uniformly.
107   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
108     Constant *Ops = C; // don't take the address of C!
109     return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
110   }
111 
112   // If this is a bitcast from constant vector -> vector, fold it.
113   if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
114     return ConstantExpr::getBitCast(C, DestTy);
115 
116   // If the element types match, IR can fold it.
117   unsigned NumDstElt = DestVTy->getNumElements();
118   unsigned NumSrcElt = C->getType()->getVectorNumElements();
119   if (NumDstElt == NumSrcElt)
120     return ConstantExpr::getBitCast(C, DestTy);
121 
122   Type *SrcEltTy = C->getType()->getVectorElementType();
123   Type *DstEltTy = DestVTy->getElementType();
124 
125   // Otherwise, we're changing the number of elements in a vector, which
126   // requires endianness information to do the right thing.  For example,
127   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
128   // folds to (little endian):
129   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
130   // and to (big endian):
131   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
132 
133   // First thing is first.  We only want to think about integer here, so if
134   // we have something in FP form, recast it as integer.
135   if (DstEltTy->isFloatingPointTy()) {
136     // Fold to an vector of integers with same size as our FP type.
137     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
138     Type *DestIVTy =
139       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
140     // Recursively handle this integer conversion, if possible.
141     C = FoldBitCast(C, DestIVTy, DL);
142 
143     // Finally, IR can handle this now that #elts line up.
144     return ConstantExpr::getBitCast(C, DestTy);
145   }
146 
147   // Okay, we know the destination is integer, if the input is FP, convert
148   // it to integer first.
149   if (SrcEltTy->isFloatingPointTy()) {
150     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
151     Type *SrcIVTy =
152       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
153     // Ask IR to do the conversion now that #elts line up.
154     C = ConstantExpr::getBitCast(C, SrcIVTy);
155     // If IR wasn't able to fold it, bail out.
156     if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
157         !isa<ConstantDataVector>(C))
158       return C;
159   }
160 
161   // Now we know that the input and output vectors are both integer vectors
162   // of the same size, and that their #elements is not the same.  Do the
163   // conversion here, which depends on whether the input or output has
164   // more elements.
165   bool isLittleEndian = DL.isLittleEndian();
166 
167   SmallVector<Constant*, 32> Result;
168   if (NumDstElt < NumSrcElt) {
169     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
170     Constant *Zero = Constant::getNullValue(DstEltTy);
171     unsigned Ratio = NumSrcElt/NumDstElt;
172     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
173     unsigned SrcElt = 0;
174     for (unsigned i = 0; i != NumDstElt; ++i) {
175       // Build each element of the result.
176       Constant *Elt = Zero;
177       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
178       for (unsigned j = 0; j != Ratio; ++j) {
179         Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
180         if (!Src)  // Reject constantexpr elements.
181           return ConstantExpr::getBitCast(C, DestTy);
182 
183         // Zero extend the element to the right size.
184         Src = ConstantExpr::getZExt(Src, Elt->getType());
185 
186         // Shift it to the right place, depending on endianness.
187         Src = ConstantExpr::getShl(Src,
188                                    ConstantInt::get(Src->getType(), ShiftAmt));
189         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
190 
191         // Mix it in.
192         Elt = ConstantExpr::getOr(Elt, Src);
193       }
194       Result.push_back(Elt);
195     }
196     return ConstantVector::get(Result);
197   }
198 
199   // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
200   unsigned Ratio = NumDstElt/NumSrcElt;
201   unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
202 
203   // Loop over each source value, expanding into multiple results.
204   for (unsigned i = 0; i != NumSrcElt; ++i) {
205     Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
206     if (!Src)  // Reject constantexpr elements.
207       return ConstantExpr::getBitCast(C, DestTy);
208 
209     unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
210     for (unsigned j = 0; j != Ratio; ++j) {
211       // Shift the piece of the value into the right place, depending on
212       // endianness.
213       Constant *Elt = ConstantExpr::getLShr(Src,
214                                   ConstantInt::get(Src->getType(), ShiftAmt));
215       ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
216 
217       // Truncate the element to an integer with the same pointer size and
218       // convert the element back to a pointer using a inttoptr.
219       if (DstEltTy->isPointerTy()) {
220         IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
221         Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
222         Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
223         continue;
224       }
225 
226       // Truncate and remember this piece.
227       Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
228     }
229   }
230 
231   return ConstantVector::get(Result);
232 }
233 
234 /// If this constant is a constant offset from a global, return the global and
235 /// the constant. Because of constantexprs, this function is recursive.
236 bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset,
237                                 const DataLayout &DL) {
238   // Trivial case, constant is the global.
239   if ((GV = dyn_cast<GlobalValue>(C))) {
240     unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
241     Offset = APInt(BitWidth, 0);
242     return true;
243   }
244 
245   // Otherwise, if this isn't a constant expr, bail out.
246   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
247   if (!CE) return false;
248 
249   // Look through ptr->int and ptr->ptr casts.
250   if (CE->getOpcode() == Instruction::PtrToInt ||
251       CE->getOpcode() == Instruction::BitCast)
252     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
253 
254   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
255   GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
256   if (!GEP)
257     return false;
258 
259   unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
260   APInt TmpOffset(BitWidth, 0);
261 
262   // If the base isn't a global+constant, we aren't either.
263   if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
264     return false;
265 
266   // Otherwise, add any offset that our operands provide.
267   if (!GEP->accumulateConstantOffset(DL, TmpOffset))
268     return false;
269 
270   Offset = TmpOffset;
271   return true;
272 }
273 
274 /// Recursive helper to read bits out of global. C is the constant being copied
275 /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
276 /// results into and BytesLeft is the number of bytes left in
277 /// the CurPtr buffer. DL is the DataLayout.
278 bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
279                         unsigned BytesLeft, const DataLayout &DL) {
280   assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
281          "Out of range access");
282 
283   // If this element is zero or undefined, we can just return since *CurPtr is
284   // zero initialized.
285   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
286     return true;
287 
288   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
289     if (CI->getBitWidth() > 64 ||
290         (CI->getBitWidth() & 7) != 0)
291       return false;
292 
293     uint64_t Val = CI->getZExtValue();
294     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
295 
296     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
297       int n = ByteOffset;
298       if (!DL.isLittleEndian())
299         n = IntBytes - n - 1;
300       CurPtr[i] = (unsigned char)(Val >> (n * 8));
301       ++ByteOffset;
302     }
303     return true;
304   }
305 
306   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
307     if (CFP->getType()->isDoubleTy()) {
308       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
309       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
310     }
311     if (CFP->getType()->isFloatTy()){
312       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
313       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
314     }
315     if (CFP->getType()->isHalfTy()){
316       C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
317       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
318     }
319     return false;
320   }
321 
322   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
323     const StructLayout *SL = DL.getStructLayout(CS->getType());
324     unsigned Index = SL->getElementContainingOffset(ByteOffset);
325     uint64_t CurEltOffset = SL->getElementOffset(Index);
326     ByteOffset -= CurEltOffset;
327 
328     while (1) {
329       // If the element access is to the element itself and not to tail padding,
330       // read the bytes from the element.
331       uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
332 
333       if (ByteOffset < EltSize &&
334           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
335                               BytesLeft, DL))
336         return false;
337 
338       ++Index;
339 
340       // Check to see if we read from the last struct element, if so we're done.
341       if (Index == CS->getType()->getNumElements())
342         return true;
343 
344       // If we read all of the bytes we needed from this element we're done.
345       uint64_t NextEltOffset = SL->getElementOffset(Index);
346 
347       if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
348         return true;
349 
350       // Move to the next element of the struct.
351       CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
352       BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
353       ByteOffset = 0;
354       CurEltOffset = NextEltOffset;
355     }
356     // not reached.
357   }
358 
359   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
360       isa<ConstantDataSequential>(C)) {
361     Type *EltTy = C->getType()->getSequentialElementType();
362     uint64_t EltSize = DL.getTypeAllocSize(EltTy);
363     uint64_t Index = ByteOffset / EltSize;
364     uint64_t Offset = ByteOffset - Index * EltSize;
365     uint64_t NumElts;
366     if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
367       NumElts = AT->getNumElements();
368     else
369       NumElts = C->getType()->getVectorNumElements();
370 
371     for (; Index != NumElts; ++Index) {
372       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
373                               BytesLeft, DL))
374         return false;
375 
376       uint64_t BytesWritten = EltSize - Offset;
377       assert(BytesWritten <= EltSize && "Not indexing into this element?");
378       if (BytesWritten >= BytesLeft)
379         return true;
380 
381       Offset = 0;
382       BytesLeft -= BytesWritten;
383       CurPtr += BytesWritten;
384     }
385     return true;
386   }
387 
388   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
389     if (CE->getOpcode() == Instruction::IntToPtr &&
390         CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
391       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
392                                 BytesLeft, DL);
393     }
394   }
395 
396   // Otherwise, unknown initializer type.
397   return false;
398 }
399 
400 Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
401                                           const DataLayout &DL) {
402   PointerType *PTy = cast<PointerType>(C->getType());
403   IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
404 
405   // If this isn't an integer load we can't fold it directly.
406   if (!IntType) {
407     unsigned AS = PTy->getAddressSpace();
408 
409     // If this is a float/double load, we can try folding it as an int32/64 load
410     // and then bitcast the result.  This can be useful for union cases.  Note
411     // that address spaces don't matter here since we're not going to result in
412     // an actual new load.
413     Type *MapTy;
414     if (LoadTy->isHalfTy())
415       MapTy = Type::getInt16Ty(C->getContext());
416     else if (LoadTy->isFloatTy())
417       MapTy = Type::getInt32Ty(C->getContext());
418     else if (LoadTy->isDoubleTy())
419       MapTy = Type::getInt64Ty(C->getContext());
420     else if (LoadTy->isVectorTy()) {
421       MapTy = PointerType::getIntNTy(C->getContext(),
422                                      DL.getTypeAllocSizeInBits(LoadTy));
423     } else
424       return nullptr;
425 
426     C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
427     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
428       return FoldBitCast(Res, LoadTy, DL);
429     return nullptr;
430   }
431 
432   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
433   if (BytesLoaded > 32 || BytesLoaded == 0)
434     return nullptr;
435 
436   GlobalValue *GVal;
437   APInt Offset;
438   if (!IsConstantOffsetFromGlobal(C, GVal, Offset, DL))
439     return nullptr;
440 
441   GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
442   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
443       !GV->getInitializer()->getType()->isSized())
444     return nullptr;
445 
446   // If we're loading off the beginning of the global, some bytes may be valid,
447   // but we don't try to handle this.
448   if (Offset.isNegative())
449     return nullptr;
450 
451   // If we're not accessing anything in this constant, the result is undefined.
452   if (Offset.getZExtValue() >=
453       DL.getTypeAllocSize(GV->getInitializer()->getType()))
454     return UndefValue::get(IntType);
455 
456   unsigned char RawBytes[32] = {0};
457   if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
458                           BytesLoaded, DL))
459     return nullptr;
460 
461   APInt ResultVal = APInt(IntType->getBitWidth(), 0);
462   if (DL.isLittleEndian()) {
463     ResultVal = RawBytes[BytesLoaded - 1];
464     for (unsigned i = 1; i != BytesLoaded; ++i) {
465       ResultVal <<= 8;
466       ResultVal |= RawBytes[BytesLoaded - 1 - i];
467     }
468   } else {
469     ResultVal = RawBytes[0];
470     for (unsigned i = 1; i != BytesLoaded; ++i) {
471       ResultVal <<= 8;
472       ResultVal |= RawBytes[i];
473     }
474   }
475 
476   return ConstantInt::get(IntType->getContext(), ResultVal);
477 }
478 
479 Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE, Type *DestTy,
480                                          const DataLayout &DL) {
481   auto *SrcPtr = CE->getOperand(0);
482   auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
483   if (!SrcPtrTy)
484     return nullptr;
485   Type *SrcTy = SrcPtrTy->getPointerElementType();
486 
487   Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
488   if (!C)
489     return nullptr;
490 
491   do {
492     Type *SrcTy = C->getType();
493 
494     // If the type sizes are the same and a cast is legal, just directly
495     // cast the constant.
496     if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
497       Instruction::CastOps Cast = Instruction::BitCast;
498       // If we are going from a pointer to int or vice versa, we spell the cast
499       // differently.
500       if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
501         Cast = Instruction::IntToPtr;
502       else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
503         Cast = Instruction::PtrToInt;
504 
505       if (CastInst::castIsValid(Cast, C, DestTy))
506         return ConstantExpr::getCast(Cast, C, DestTy);
507     }
508 
509     // If this isn't an aggregate type, there is nothing we can do to drill down
510     // and find a bitcastable constant.
511     if (!SrcTy->isAggregateType())
512       return nullptr;
513 
514     // We're simulating a load through a pointer that was bitcast to point to
515     // a different type, so we can try to walk down through the initial
516     // elements of an aggregate to see if some part of th e aggregate is
517     // castable to implement the "load" semantic model.
518     C = C->getAggregateElement(0u);
519   } while (C);
520 
521   return nullptr;
522 }
523 
524 } // end anonymous namespace
525 
526 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
527                                              const DataLayout &DL) {
528   // First, try the easy cases:
529   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
530     if (GV->isConstant() && GV->hasDefinitiveInitializer())
531       return GV->getInitializer();
532 
533   if (auto *GA = dyn_cast<GlobalAlias>(C))
534     if (GA->getAliasee() && !GA->isInterposable())
535       return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
536 
537   // If the loaded value isn't a constant expr, we can't handle it.
538   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
539   if (!CE)
540     return nullptr;
541 
542   if (CE->getOpcode() == Instruction::GetElementPtr) {
543     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
544       if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
545         if (Constant *V =
546              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
547           return V;
548       }
549     }
550   }
551 
552   if (CE->getOpcode() == Instruction::BitCast)
553     if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL))
554       return LoadedC;
555 
556   // Instead of loading constant c string, use corresponding integer value
557   // directly if string length is small enough.
558   StringRef Str;
559   if (getConstantStringInfo(CE, Str) && !Str.empty()) {
560     unsigned StrLen = Str.size();
561     unsigned NumBits = Ty->getPrimitiveSizeInBits();
562     // Replace load with immediate integer if the result is an integer or fp
563     // value.
564     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
565         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
566       APInt StrVal(NumBits, 0);
567       APInt SingleChar(NumBits, 0);
568       if (DL.isLittleEndian()) {
569         for (signed i = StrLen-1; i >= 0; i--) {
570           SingleChar = (uint64_t) Str[i] &
571             std::numeric_limits<unsigned char>::max();
572           StrVal = (StrVal << 8) | SingleChar;
573         }
574       } else {
575         for (unsigned i = 0; i < StrLen; i++) {
576           SingleChar = (uint64_t) Str[i] &
577             std::numeric_limits<unsigned char>::max();
578           StrVal = (StrVal << 8) | SingleChar;
579         }
580         // Append NULL at the end.
581         SingleChar = 0;
582         StrVal = (StrVal << 8) | SingleChar;
583       }
584 
585       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
586       if (Ty->isFloatingPointTy())
587         Res = ConstantExpr::getBitCast(Res, Ty);
588       return Res;
589     }
590   }
591 
592   // If this load comes from anywhere in a constant global, and if the global
593   // is all undef or zero, we know what it loads.
594   if (GlobalVariable *GV =
595           dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
596     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
597       if (GV->getInitializer()->isNullValue())
598         return Constant::getNullValue(Ty);
599       if (isa<UndefValue>(GV->getInitializer()))
600         return UndefValue::get(Ty);
601     }
602   }
603 
604   // Try hard to fold loads from bitcasted strange and non-type-safe things.
605   return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
606 }
607 
608 namespace {
609 
610 Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
611   if (LI->isVolatile()) return nullptr;
612 
613   if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
614     return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
615 
616   return nullptr;
617 }
618 
619 /// One of Op0/Op1 is a constant expression.
620 /// Attempt to symbolically evaluate the result of a binary operator merging
621 /// these together.  If target data info is available, it is provided as DL,
622 /// otherwise DL is null.
623 Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
624                                     const DataLayout &DL) {
625   // SROA
626 
627   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
628   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
629   // bits.
630 
631   if (Opc == Instruction::And) {
632     unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
633     APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
634     APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
635     computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
636     computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
637     if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
638       // All the bits of Op0 that the 'and' could be masking are already zero.
639       return Op0;
640     }
641     if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
642       // All the bits of Op1 that the 'and' could be masking are already zero.
643       return Op1;
644     }
645 
646     APInt KnownZero = KnownZero0 | KnownZero1;
647     APInt KnownOne = KnownOne0 & KnownOne1;
648     if ((KnownZero | KnownOne).isAllOnesValue()) {
649       return ConstantInt::get(Op0->getType(), KnownOne);
650     }
651   }
652 
653   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
654   // constant.  This happens frequently when iterating over a global array.
655   if (Opc == Instruction::Sub) {
656     GlobalValue *GV1, *GV2;
657     APInt Offs1, Offs2;
658 
659     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
660       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
661         unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
662 
663         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
664         // PtrToInt may change the bitwidth so we have convert to the right size
665         // first.
666         return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
667                                                 Offs2.zextOrTrunc(OpSize));
668       }
669   }
670 
671   return nullptr;
672 }
673 
674 /// If array indices are not pointer-sized integers, explicitly cast them so
675 /// that they aren't implicitly casted by the getelementptr.
676 Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
677                          Type *ResultTy, const DataLayout &DL,
678                          const TargetLibraryInfo *TLI) {
679   Type *IntPtrTy = DL.getIntPtrType(ResultTy);
680 
681   bool Any = false;
682   SmallVector<Constant*, 32> NewIdxs;
683   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
684     if ((i == 1 ||
685          !isa<StructType>(GetElementPtrInst::getIndexedType(SrcElemTy,
686              Ops.slice(1, i - 1)))) &&
687         Ops[i]->getType() != IntPtrTy) {
688       Any = true;
689       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
690                                                                       true,
691                                                                       IntPtrTy,
692                                                                       true),
693                                               Ops[i], IntPtrTy));
694     } else
695       NewIdxs.push_back(Ops[i]);
696   }
697 
698   if (!Any)
699     return nullptr;
700 
701   Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ops[0], NewIdxs);
702   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
703     if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
704       C = Folded;
705   }
706 
707   return C;
708 }
709 
710 /// Strip the pointer casts, but preserve the address space information.
711 Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
712   assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
713   PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
714   Ptr = Ptr->stripPointerCasts();
715   PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
716 
717   ElemTy = NewPtrTy->getPointerElementType();
718 
719   // Preserve the address space number of the pointer.
720   if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
721     NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
722     Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
723   }
724   return Ptr;
725 }
726 
727 /// If we can symbolically evaluate the GEP constant expression, do so.
728 Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
729                                   ArrayRef<Constant *> Ops,
730                                   const DataLayout &DL,
731                                   const TargetLibraryInfo *TLI) {
732   Type *SrcElemTy = GEP->getSourceElementType();
733   Type *ResElemTy = GEP->getResultElementType();
734   Type *ResTy = GEP->getType();
735   if (!SrcElemTy->isSized())
736     return nullptr;
737 
738   if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, DL, TLI))
739     return C;
740 
741   Constant *Ptr = Ops[0];
742   if (!Ptr->getType()->isPointerTy())
743     return nullptr;
744 
745   Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
746 
747   // If this is a constant expr gep that is effectively computing an
748   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
749   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
750     if (!isa<ConstantInt>(Ops[i])) {
751 
752       // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
753       // "inttoptr (sub (ptrtoint Ptr), V)"
754       if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
755         ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
756         assert((!CE || CE->getType() == IntPtrTy) &&
757                "CastGEPIndices didn't canonicalize index types!");
758         if (CE && CE->getOpcode() == Instruction::Sub &&
759             CE->getOperand(0)->isNullValue()) {
760           Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
761           Res = ConstantExpr::getSub(Res, CE->getOperand(1));
762           Res = ConstantExpr::getIntToPtr(Res, ResTy);
763           if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
764             Res = ConstantFoldConstantExpression(ResCE, DL, TLI);
765           return Res;
766         }
767       }
768       return nullptr;
769     }
770 
771   unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
772   APInt Offset =
773       APInt(BitWidth,
774             DL.getIndexedOffsetInType(
775                 SrcElemTy,
776                 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
777   Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
778 
779   // If this is a GEP of a GEP, fold it all into a single GEP.
780   while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
781     SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
782 
783     // Do not try the incorporate the sub-GEP if some index is not a number.
784     bool AllConstantInt = true;
785     for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
786       if (!isa<ConstantInt>(NestedOps[i])) {
787         AllConstantInt = false;
788         break;
789       }
790     if (!AllConstantInt)
791       break;
792 
793     Ptr = cast<Constant>(GEP->getOperand(0));
794     SrcElemTy = GEP->getSourceElementType();
795     Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
796     Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
797   }
798 
799   // If the base value for this address is a literal integer value, fold the
800   // getelementptr to the resulting integer value casted to the pointer type.
801   APInt BasePtr(BitWidth, 0);
802   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
803     if (CE->getOpcode() == Instruction::IntToPtr) {
804       if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
805         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
806     }
807   }
808 
809   if (Ptr->isNullValue() || BasePtr != 0) {
810     Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
811     return ConstantExpr::getIntToPtr(C, ResTy);
812   }
813 
814   // Otherwise form a regular getelementptr. Recompute the indices so that
815   // we eliminate over-indexing of the notional static type array bounds.
816   // This makes it easy to determine if the getelementptr is "inbounds".
817   // Also, this helps GlobalOpt do SROA on GlobalVariables.
818   Type *Ty = Ptr->getType();
819   assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
820   SmallVector<Constant *, 32> NewIdxs;
821 
822   do {
823     if (!Ty->isStructTy()) {
824       if (Ty->isPointerTy()) {
825         // The only pointer indexing we'll do is on the first index of the GEP.
826         if (!NewIdxs.empty())
827           break;
828 
829         Ty = SrcElemTy;
830 
831         // Only handle pointers to sized types, not pointers to functions.
832         if (!Ty->isSized())
833           return nullptr;
834       } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
835         Ty = ATy->getElementType();
836       } else {
837         // We've reached some non-indexable type.
838         break;
839       }
840 
841       // Determine which element of the array the offset points into.
842       APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
843       if (ElemSize == 0)
844         // The element size is 0. This may be [0 x Ty]*, so just use a zero
845         // index for this level and proceed to the next level to see if it can
846         // accommodate the offset.
847         NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
848       else {
849         // The element size is non-zero divide the offset by the element
850         // size (rounding down), to compute the index at this level.
851         APInt NewIdx = Offset.udiv(ElemSize);
852         Offset -= NewIdx * ElemSize;
853         NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
854       }
855     } else {
856       StructType *STy = cast<StructType>(Ty);
857       // If we end up with an offset that isn't valid for this struct type, we
858       // can't re-form this GEP in a regular form, so bail out. The pointer
859       // operand likely went through casts that are necessary to make the GEP
860       // sensible.
861       const StructLayout &SL = *DL.getStructLayout(STy);
862       if (Offset.uge(SL.getSizeInBytes()))
863         break;
864 
865       // Determine which field of the struct the offset points into. The
866       // getZExtValue is fine as we've already ensured that the offset is
867       // within the range representable by the StructLayout API.
868       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
869       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
870                                          ElIdx));
871       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
872       Ty = STy->getTypeAtIndex(ElIdx);
873     }
874   } while (Ty != ResElemTy);
875 
876   // If we haven't used up the entire offset by descending the static
877   // type, then the offset is pointing into the middle of an indivisible
878   // member, so we can't simplify it.
879   if (Offset != 0)
880     return nullptr;
881 
882   // Create a GEP.
883   Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs);
884   assert(C->getType()->getPointerElementType() == Ty &&
885          "Computed GetElementPtr has unexpected type!");
886 
887   // If we ended up indexing a member with a type that doesn't match
888   // the type of what the original indices indexed, add a cast.
889   if (Ty != ResElemTy)
890     C = FoldBitCast(C, ResTy, DL);
891 
892   return C;
893 }
894 
895 /// Attempt to constant fold an instruction with the
896 /// specified opcode and operands.  If successful, the constant result is
897 /// returned, if not, null is returned.  Note that this function can fail when
898 /// attempting to fold instructions like loads and stores, which have no
899 /// constant expression form.
900 ///
901 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
902 /// information, due to only being passed an opcode and operands. Constant
903 /// folding using this function strips this information.
904 ///
905 Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, Type *DestTy,
906                                        unsigned Opcode,
907                                        ArrayRef<Constant *> Ops,
908                                        const DataLayout &DL,
909                                        const TargetLibraryInfo *TLI) {
910   // Handle easy binops first.
911   if (Instruction::isBinaryOp(Opcode))
912     return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
913 
914   if (Instruction::isCast(Opcode))
915     return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
916 
917   if(auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
918     if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
919       return C;
920 
921     return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(),
922                                           Ops[0], Ops.slice(1));
923   }
924 
925   switch (Opcode) {
926   default: return nullptr;
927   case Instruction::ICmp:
928   case Instruction::FCmp: llvm_unreachable("Invalid for compares");
929   case Instruction::Call:
930     if (Function *F = dyn_cast<Function>(Ops.back()))
931       if (canConstantFoldCallTo(F))
932         return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
933     return nullptr;
934   case Instruction::Select:
935     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
936   case Instruction::ExtractElement:
937     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
938   case Instruction::InsertElement:
939     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
940   case Instruction::ShuffleVector:
941     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
942   }
943 }
944 
945 } // end anonymous namespace
946 
947 //===----------------------------------------------------------------------===//
948 // Constant Folding public APIs
949 //===----------------------------------------------------------------------===//
950 
951 Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
952                                         const TargetLibraryInfo *TLI) {
953   // Handle PHI nodes quickly here...
954   if (PHINode *PN = dyn_cast<PHINode>(I)) {
955     Constant *CommonValue = nullptr;
956 
957     for (Value *Incoming : PN->incoming_values()) {
958       // If the incoming value is undef then skip it.  Note that while we could
959       // skip the value if it is equal to the phi node itself we choose not to
960       // because that would break the rule that constant folding only applies if
961       // all operands are constants.
962       if (isa<UndefValue>(Incoming))
963         continue;
964       // If the incoming value is not a constant, then give up.
965       Constant *C = dyn_cast<Constant>(Incoming);
966       if (!C)
967         return nullptr;
968       // Fold the PHI's operands.
969       if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
970         C = ConstantFoldConstantExpression(NewC, DL, TLI);
971       // If the incoming value is a different constant to
972       // the one we saw previously, then give up.
973       if (CommonValue && C != CommonValue)
974         return nullptr;
975       CommonValue = C;
976     }
977 
978 
979     // If we reach here, all incoming values are the same constant or undef.
980     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
981   }
982 
983   // Scan the operand list, checking to see if they are all constants, if so,
984   // hand off to ConstantFoldInstOperandsImpl.
985   if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
986     return nullptr;
987 
988   SmallVector<Constant *, 8> Ops;
989   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
990     Constant *Op = cast<Constant>(*i);
991     // Fold the Instruction's operands.
992     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
993       Op = ConstantFoldConstantExpression(NewCE, DL, TLI);
994 
995     Ops.push_back(Op);
996   }
997 
998   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
999     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
1000                                            DL, TLI);
1001 
1002   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
1003     return ConstantFoldLoadInst(LI, DL);
1004 
1005   if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
1006     return ConstantExpr::getInsertValue(
1007                                 cast<Constant>(IVI->getAggregateOperand()),
1008                                 cast<Constant>(IVI->getInsertedValueOperand()),
1009                                 IVI->getIndices());
1010   }
1011 
1012   if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
1013     return ConstantExpr::getExtractValue(
1014                                     cast<Constant>(EVI->getAggregateOperand()),
1015                                     EVI->getIndices());
1016   }
1017 
1018   return ConstantFoldInstOperands(I, Ops, DL, TLI);
1019 }
1020 
1021 namespace {
1022 
1023 Constant *
1024 ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout &DL,
1025                                    const TargetLibraryInfo *TLI,
1026                                    SmallPtrSetImpl<ConstantExpr *> &FoldedOps) {
1027   SmallVector<Constant *, 8> Ops;
1028   for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
1029        ++i) {
1030     Constant *NewC = cast<Constant>(*i);
1031     // Recursively fold the ConstantExpr's operands. If we have already folded
1032     // a ConstantExpr, we don't have to process it again.
1033     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
1034       if (FoldedOps.insert(NewCE).second)
1035         NewC = ConstantFoldConstantExpressionImpl(NewCE, DL, TLI, FoldedOps);
1036     }
1037     Ops.push_back(NewC);
1038   }
1039 
1040   if (CE->isCompare())
1041     return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1042                                            DL, TLI);
1043 
1044   return ConstantFoldInstOperandsImpl(CE, CE->getType(), CE->getOpcode(), Ops,
1045                                       DL, TLI);
1046 }
1047 
1048 } // end anonymous namespace
1049 
1050 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
1051                                                const DataLayout &DL,
1052                                                const TargetLibraryInfo *TLI) {
1053   SmallPtrSet<ConstantExpr *, 4> FoldedOps;
1054   return ConstantFoldConstantExpressionImpl(CE, DL, TLI, FoldedOps);
1055 }
1056 
1057 Constant *llvm::ConstantFoldInstOperands(Instruction *I,
1058                                          ArrayRef<Constant *> Ops,
1059                                          const DataLayout &DL,
1060                                          const TargetLibraryInfo *TLI) {
1061   return ConstantFoldInstOperandsImpl(I, I->getType(), I->getOpcode(), Ops, DL,
1062                                       TLI);
1063 }
1064 
1065 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
1066                                          ArrayRef<Constant *> Ops,
1067                                          const DataLayout &DL,
1068                                          const TargetLibraryInfo *TLI) {
1069   assert(Opcode != Instruction::GetElementPtr && "Invalid for GEPs");
1070   return ConstantFoldInstOperandsImpl(nullptr, DestTy, Opcode, Ops, DL, TLI);
1071 }
1072 
1073 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1074                                                 Constant *Ops0, Constant *Ops1,
1075                                                 const DataLayout &DL,
1076                                                 const TargetLibraryInfo *TLI) {
1077   // fold: icmp (inttoptr x), null         -> icmp x, 0
1078   // fold: icmp (ptrtoint x), 0            -> icmp x, null
1079   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1080   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1081   //
1082   // FIXME: The following comment is out of data and the DataLayout is here now.
1083   // ConstantExpr::getCompare cannot do this, because it doesn't have DL
1084   // around to know if bit truncation is happening.
1085   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1086     if (Ops1->isNullValue()) {
1087       if (CE0->getOpcode() == Instruction::IntToPtr) {
1088         Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1089         // Convert the integer value to the right size to ensure we get the
1090         // proper extension or truncation.
1091         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1092                                                    IntPtrTy, false);
1093         Constant *Null = Constant::getNullValue(C->getType());
1094         return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1095       }
1096 
1097       // Only do this transformation if the int is intptrty in size, otherwise
1098       // there is a truncation or extension that we aren't modeling.
1099       if (CE0->getOpcode() == Instruction::PtrToInt) {
1100         Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1101         if (CE0->getType() == IntPtrTy) {
1102           Constant *C = CE0->getOperand(0);
1103           Constant *Null = Constant::getNullValue(C->getType());
1104           return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
1105         }
1106       }
1107     }
1108 
1109     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1110       if (CE0->getOpcode() == CE1->getOpcode()) {
1111         if (CE0->getOpcode() == Instruction::IntToPtr) {
1112           Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
1113 
1114           // Convert the integer value to the right size to ensure we get the
1115           // proper extension or truncation.
1116           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1117                                                       IntPtrTy, false);
1118           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1119                                                       IntPtrTy, false);
1120           return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
1121         }
1122 
1123         // Only do this transformation if the int is intptrty in size, otherwise
1124         // there is a truncation or extension that we aren't modeling.
1125         if (CE0->getOpcode() == Instruction::PtrToInt) {
1126           Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
1127           if (CE0->getType() == IntPtrTy &&
1128               CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1129             return ConstantFoldCompareInstOperands(
1130                 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
1131           }
1132         }
1133       }
1134     }
1135 
1136     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1137     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1138     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1139         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1140       Constant *LHS = ConstantFoldCompareInstOperands(
1141           Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1142       Constant *RHS = ConstantFoldCompareInstOperands(
1143           Predicate, CE0->getOperand(1), Ops1, DL, TLI);
1144       unsigned OpC =
1145         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1146       return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
1147     }
1148   }
1149 
1150   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1151 }
1152 
1153 Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1154                                              Constant *RHS,
1155                                              const DataLayout &DL) {
1156   assert(Instruction::isBinaryOp(Opcode));
1157   if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1158     if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1159       return C;
1160 
1161   return ConstantExpr::get(Opcode, LHS, RHS);
1162 }
1163 
1164 Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1165                                         Type *DestTy, const DataLayout &DL) {
1166   assert(Instruction::isCast(Opcode));
1167   switch (Opcode) {
1168   default:
1169     llvm_unreachable("Missing case");
1170   case Instruction::PtrToInt:
1171     // If the input is a inttoptr, eliminate the pair.  This requires knowing
1172     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1173     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1174       if (CE->getOpcode() == Instruction::IntToPtr) {
1175         Constant *Input = CE->getOperand(0);
1176         unsigned InWidth = Input->getType()->getScalarSizeInBits();
1177         unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1178         if (PtrWidth < InWidth) {
1179           Constant *Mask =
1180             ConstantInt::get(CE->getContext(),
1181                              APInt::getLowBitsSet(InWidth, PtrWidth));
1182           Input = ConstantExpr::getAnd(Input, Mask);
1183         }
1184         // Do a zext or trunc to get to the dest size.
1185         return ConstantExpr::getIntegerCast(Input, DestTy, false);
1186       }
1187     }
1188     return ConstantExpr::getCast(Opcode, C, DestTy);
1189   case Instruction::IntToPtr:
1190     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1191     // the int size is >= the ptr size and the address spaces are the same.
1192     // This requires knowing the width of a pointer, so it can't be done in
1193     // ConstantExpr::getCast.
1194     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1195       if (CE->getOpcode() == Instruction::PtrToInt) {
1196         Constant *SrcPtr = CE->getOperand(0);
1197         unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1198         unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1199 
1200         if (MidIntSize >= SrcPtrSize) {
1201           unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1202           if (SrcAS == DestTy->getPointerAddressSpace())
1203             return FoldBitCast(CE->getOperand(0), DestTy, DL);
1204         }
1205       }
1206     }
1207 
1208     return ConstantExpr::getCast(Opcode, C, DestTy);
1209   case Instruction::Trunc:
1210   case Instruction::ZExt:
1211   case Instruction::SExt:
1212   case Instruction::FPTrunc:
1213   case Instruction::FPExt:
1214   case Instruction::UIToFP:
1215   case Instruction::SIToFP:
1216   case Instruction::FPToUI:
1217   case Instruction::FPToSI:
1218   case Instruction::AddrSpaceCast:
1219       return ConstantExpr::getCast(Opcode, C, DestTy);
1220   case Instruction::BitCast:
1221     return FoldBitCast(C, DestTy, DL);
1222   }
1223 }
1224 
1225 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1226                                                        ConstantExpr *CE) {
1227   if (!CE->getOperand(1)->isNullValue())
1228     return nullptr;  // Do not allow stepping over the value!
1229 
1230   // Loop over all of the operands, tracking down which value we are
1231   // addressing.
1232   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1233     C = C->getAggregateElement(CE->getOperand(i));
1234     if (!C)
1235       return nullptr;
1236   }
1237   return C;
1238 }
1239 
1240 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1241                                                   ArrayRef<Constant*> Indices) {
1242   // Loop over all of the operands, tracking down which value we are
1243   // addressing.
1244   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1245     C = C->getAggregateElement(Indices[i]);
1246     if (!C)
1247       return nullptr;
1248   }
1249   return C;
1250 }
1251 
1252 //===----------------------------------------------------------------------===//
1253 //  Constant Folding for Calls
1254 //
1255 
1256 bool llvm::canConstantFoldCallTo(const Function *F) {
1257   switch (F->getIntrinsicID()) {
1258   case Intrinsic::fabs:
1259   case Intrinsic::minnum:
1260   case Intrinsic::maxnum:
1261   case Intrinsic::log:
1262   case Intrinsic::log2:
1263   case Intrinsic::log10:
1264   case Intrinsic::exp:
1265   case Intrinsic::exp2:
1266   case Intrinsic::floor:
1267   case Intrinsic::ceil:
1268   case Intrinsic::sqrt:
1269   case Intrinsic::sin:
1270   case Intrinsic::cos:
1271   case Intrinsic::trunc:
1272   case Intrinsic::rint:
1273   case Intrinsic::nearbyint:
1274   case Intrinsic::pow:
1275   case Intrinsic::powi:
1276   case Intrinsic::bswap:
1277   case Intrinsic::ctpop:
1278   case Intrinsic::ctlz:
1279   case Intrinsic::cttz:
1280   case Intrinsic::fma:
1281   case Intrinsic::fmuladd:
1282   case Intrinsic::copysign:
1283   case Intrinsic::round:
1284   case Intrinsic::sadd_with_overflow:
1285   case Intrinsic::uadd_with_overflow:
1286   case Intrinsic::ssub_with_overflow:
1287   case Intrinsic::usub_with_overflow:
1288   case Intrinsic::smul_with_overflow:
1289   case Intrinsic::umul_with_overflow:
1290   case Intrinsic::convert_from_fp16:
1291   case Intrinsic::convert_to_fp16:
1292   case Intrinsic::bitreverse:
1293   case Intrinsic::x86_sse_cvtss2si:
1294   case Intrinsic::x86_sse_cvtss2si64:
1295   case Intrinsic::x86_sse_cvttss2si:
1296   case Intrinsic::x86_sse_cvttss2si64:
1297   case Intrinsic::x86_sse2_cvtsd2si:
1298   case Intrinsic::x86_sse2_cvtsd2si64:
1299   case Intrinsic::x86_sse2_cvttsd2si:
1300   case Intrinsic::x86_sse2_cvttsd2si64:
1301     return true;
1302   default:
1303     return false;
1304   case 0: break;
1305   }
1306 
1307   if (!F->hasName())
1308     return false;
1309   StringRef Name = F->getName();
1310 
1311   // In these cases, the check of the length is required.  We don't want to
1312   // return true for a name like "cos\0blah" which strcmp would return equal to
1313   // "cos", but has length 8.
1314   switch (Name[0]) {
1315   default:
1316     return false;
1317   case 'a':
1318     return Name == "acos" || Name == "asin" || Name == "atan" ||
1319            Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1320            Name == "atanf" || Name == "atan2f";
1321   case 'c':
1322     return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1323            Name == "ceilf" || Name == "cosf" || Name == "coshf";
1324   case 'e':
1325     return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
1326   case 'f':
1327     return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1328            Name == "fabsf" || Name == "floorf" || Name == "fmodf";
1329   case 'l':
1330     return Name == "log" || Name == "log10" || Name == "logf" ||
1331            Name == "log10f";
1332   case 'p':
1333     return Name == "pow" || Name == "powf";
1334   case 's':
1335     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1336            Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
1337   case 't':
1338     return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
1339   }
1340 }
1341 
1342 namespace {
1343 
1344 Constant *GetConstantFoldFPValue(double V, Type *Ty) {
1345   if (Ty->isHalfTy()) {
1346     APFloat APF(V);
1347     bool unused;
1348     APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1349     return ConstantFP::get(Ty->getContext(), APF);
1350   }
1351   if (Ty->isFloatTy())
1352     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1353   if (Ty->isDoubleTy())
1354     return ConstantFP::get(Ty->getContext(), APFloat(V));
1355   llvm_unreachable("Can only constant fold half/float/double");
1356 }
1357 
1358 /// Clear the floating-point exception state.
1359 inline void llvm_fenv_clearexcept() {
1360 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
1361   feclearexcept(FE_ALL_EXCEPT);
1362 #endif
1363   errno = 0;
1364 }
1365 
1366 /// Test if a floating-point exception was raised.
1367 inline bool llvm_fenv_testexcept() {
1368   int errno_val = errno;
1369   if (errno_val == ERANGE || errno_val == EDOM)
1370     return true;
1371 #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
1372   if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1373     return true;
1374 #endif
1375   return false;
1376 }
1377 
1378 Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
1379   llvm_fenv_clearexcept();
1380   V = NativeFP(V);
1381   if (llvm_fenv_testexcept()) {
1382     llvm_fenv_clearexcept();
1383     return nullptr;
1384   }
1385 
1386   return GetConstantFoldFPValue(V, Ty);
1387 }
1388 
1389 Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1390                                double W, Type *Ty) {
1391   llvm_fenv_clearexcept();
1392   V = NativeFP(V, W);
1393   if (llvm_fenv_testexcept()) {
1394     llvm_fenv_clearexcept();
1395     return nullptr;
1396   }
1397 
1398   return GetConstantFoldFPValue(V, Ty);
1399 }
1400 
1401 /// Attempt to fold an SSE floating point to integer conversion of a constant
1402 /// floating point. If roundTowardZero is false, the default IEEE rounding is
1403 /// used (toward nearest, ties to even). This matches the behavior of the
1404 /// non-truncating SSE instructions in the default rounding mode. The desired
1405 /// integer type Ty is used to select how many bits are available for the
1406 /// result. Returns null if the conversion cannot be performed, otherwise
1407 /// returns the Constant value resulting from the conversion.
1408 Constant *ConstantFoldConvertToInt(const APFloat &Val, bool roundTowardZero,
1409                                    Type *Ty) {
1410   // All of these conversion intrinsics form an integer of at most 64bits.
1411   unsigned ResultWidth = Ty->getIntegerBitWidth();
1412   assert(ResultWidth <= 64 &&
1413          "Can only constant fold conversions to 64 and 32 bit ints");
1414 
1415   uint64_t UIntVal;
1416   bool isExact = false;
1417   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1418                                               : APFloat::rmNearestTiesToEven;
1419   APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1420                                                   /*isSigned=*/true, mode,
1421                                                   &isExact);
1422   if (status != APFloat::opOK && status != APFloat::opInexact)
1423     return nullptr;
1424   return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1425 }
1426 
1427 double getValueAsDouble(ConstantFP *Op) {
1428   Type *Ty = Op->getType();
1429 
1430   if (Ty->isFloatTy())
1431     return Op->getValueAPF().convertToFloat();
1432 
1433   if (Ty->isDoubleTy())
1434     return Op->getValueAPF().convertToDouble();
1435 
1436   bool unused;
1437   APFloat APF = Op->getValueAPF();
1438   APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1439   return APF.convertToDouble();
1440 }
1441 
1442 Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1443                                  ArrayRef<Constant *> Operands,
1444                                  const TargetLibraryInfo *TLI) {
1445   if (Operands.size() == 1) {
1446     if (isa<UndefValue>(Operands[0])) {
1447       // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN
1448       if (IntrinsicID == Intrinsic::cos)
1449         return Constant::getNullValue(Ty);
1450     }
1451     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1452       if (IntrinsicID == Intrinsic::convert_to_fp16) {
1453         APFloat Val(Op->getValueAPF());
1454 
1455         bool lost = false;
1456         Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1457 
1458         return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
1459       }
1460 
1461       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1462         return nullptr;
1463 
1464       if (IntrinsicID == Intrinsic::round) {
1465         APFloat V = Op->getValueAPF();
1466         V.roundToIntegral(APFloat::rmNearestTiesToAway);
1467         return ConstantFP::get(Ty->getContext(), V);
1468       }
1469 
1470       if (IntrinsicID == Intrinsic::floor) {
1471         APFloat V = Op->getValueAPF();
1472         V.roundToIntegral(APFloat::rmTowardNegative);
1473         return ConstantFP::get(Ty->getContext(), V);
1474       }
1475 
1476       if (IntrinsicID == Intrinsic::ceil) {
1477         APFloat V = Op->getValueAPF();
1478         V.roundToIntegral(APFloat::rmTowardPositive);
1479         return ConstantFP::get(Ty->getContext(), V);
1480       }
1481 
1482       if (IntrinsicID == Intrinsic::trunc) {
1483         APFloat V = Op->getValueAPF();
1484         V.roundToIntegral(APFloat::rmTowardZero);
1485         return ConstantFP::get(Ty->getContext(), V);
1486       }
1487 
1488       if (IntrinsicID == Intrinsic::rint) {
1489         APFloat V = Op->getValueAPF();
1490         V.roundToIntegral(APFloat::rmNearestTiesToEven);
1491         return ConstantFP::get(Ty->getContext(), V);
1492       }
1493 
1494       if (IntrinsicID == Intrinsic::nearbyint) {
1495         APFloat V = Op->getValueAPF();
1496         V.roundToIntegral(APFloat::rmNearestTiesToEven);
1497         return ConstantFP::get(Ty->getContext(), V);
1498       }
1499 
1500       /// We only fold functions with finite arguments. Folding NaN and inf is
1501       /// likely to be aborted with an exception anyway, and some host libms
1502       /// have known errors raising exceptions.
1503       if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1504         return nullptr;
1505 
1506       /// Currently APFloat versions of these functions do not exist, so we use
1507       /// the host native double versions.  Float versions are not called
1508       /// directly but for all these it is true (float)(f((double)arg)) ==
1509       /// f(arg).  Long double not supported yet.
1510       double V = getValueAsDouble(Op);
1511 
1512       switch (IntrinsicID) {
1513         default: break;
1514         case Intrinsic::fabs:
1515           return ConstantFoldFP(fabs, V, Ty);
1516         case Intrinsic::log2:
1517           return ConstantFoldFP(Log2, V, Ty);
1518         case Intrinsic::log:
1519           return ConstantFoldFP(log, V, Ty);
1520         case Intrinsic::log10:
1521           return ConstantFoldFP(log10, V, Ty);
1522         case Intrinsic::exp:
1523           return ConstantFoldFP(exp, V, Ty);
1524         case Intrinsic::exp2:
1525           return ConstantFoldFP(exp2, V, Ty);
1526         case Intrinsic::sin:
1527           return ConstantFoldFP(sin, V, Ty);
1528         case Intrinsic::cos:
1529           return ConstantFoldFP(cos, V, Ty);
1530       }
1531 
1532       if (!TLI)
1533         return nullptr;
1534 
1535       switch (Name[0]) {
1536       case 'a':
1537         if ((Name == "acos" && TLI->has(LibFunc::acos)) ||
1538             (Name == "acosf" && TLI->has(LibFunc::acosf)))
1539           return ConstantFoldFP(acos, V, Ty);
1540         else if ((Name == "asin" && TLI->has(LibFunc::asin)) ||
1541                  (Name == "asinf" && TLI->has(LibFunc::asinf)))
1542           return ConstantFoldFP(asin, V, Ty);
1543         else if ((Name == "atan" && TLI->has(LibFunc::atan)) ||
1544                  (Name == "atanf" && TLI->has(LibFunc::atanf)))
1545           return ConstantFoldFP(atan, V, Ty);
1546         break;
1547       case 'c':
1548         if ((Name == "ceil" && TLI->has(LibFunc::ceil)) ||
1549             (Name == "ceilf" && TLI->has(LibFunc::ceilf)))
1550           return ConstantFoldFP(ceil, V, Ty);
1551         else if ((Name == "cos" && TLI->has(LibFunc::cos)) ||
1552                  (Name == "cosf" && TLI->has(LibFunc::cosf)))
1553           return ConstantFoldFP(cos, V, Ty);
1554         else if ((Name == "cosh" && TLI->has(LibFunc::cosh)) ||
1555                  (Name == "coshf" && TLI->has(LibFunc::coshf)))
1556           return ConstantFoldFP(cosh, V, Ty);
1557         break;
1558       case 'e':
1559         if ((Name == "exp" && TLI->has(LibFunc::exp)) ||
1560             (Name == "expf" && TLI->has(LibFunc::expf)))
1561           return ConstantFoldFP(exp, V, Ty);
1562         if ((Name == "exp2" && TLI->has(LibFunc::exp2)) ||
1563             (Name == "exp2f" && TLI->has(LibFunc::exp2f)))
1564           // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1565           // C99 library.
1566           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1567         break;
1568       case 'f':
1569         if ((Name == "fabs" && TLI->has(LibFunc::fabs)) ||
1570             (Name == "fabsf" && TLI->has(LibFunc::fabsf)))
1571           return ConstantFoldFP(fabs, V, Ty);
1572         else if ((Name == "floor" && TLI->has(LibFunc::floor)) ||
1573                  (Name == "floorf" && TLI->has(LibFunc::floorf)))
1574           return ConstantFoldFP(floor, V, Ty);
1575         break;
1576       case 'l':
1577         if ((Name == "log" && V > 0 && TLI->has(LibFunc::log)) ||
1578             (Name == "logf" && V > 0 && TLI->has(LibFunc::logf)))
1579           return ConstantFoldFP(log, V, Ty);
1580         else if ((Name == "log10" && V > 0 && TLI->has(LibFunc::log10)) ||
1581                  (Name == "log10f" && V > 0 && TLI->has(LibFunc::log10f)))
1582           return ConstantFoldFP(log10, V, Ty);
1583         else if (IntrinsicID == Intrinsic::sqrt &&
1584                  (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
1585           if (V >= -0.0)
1586             return ConstantFoldFP(sqrt, V, Ty);
1587           else {
1588             // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
1589             // all guarantee or favor returning NaN - the square root of a
1590             // negative number is not defined for the LLVM sqrt intrinsic.
1591             // This is because the intrinsic should only be emitted in place of
1592             // libm's sqrt function when using "no-nans-fp-math".
1593             return UndefValue::get(Ty);
1594           }
1595         }
1596         break;
1597       case 's':
1598         if ((Name == "sin" && TLI->has(LibFunc::sin)) ||
1599             (Name == "sinf" && TLI->has(LibFunc::sinf)))
1600           return ConstantFoldFP(sin, V, Ty);
1601         else if ((Name == "sinh" && TLI->has(LibFunc::sinh)) ||
1602                  (Name == "sinhf" && TLI->has(LibFunc::sinhf)))
1603           return ConstantFoldFP(sinh, V, Ty);
1604         else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt)) ||
1605                  (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf)))
1606           return ConstantFoldFP(sqrt, V, Ty);
1607         break;
1608       case 't':
1609         if ((Name == "tan" && TLI->has(LibFunc::tan)) ||
1610             (Name == "tanf" && TLI->has(LibFunc::tanf)))
1611           return ConstantFoldFP(tan, V, Ty);
1612         else if ((Name == "tanh" && TLI->has(LibFunc::tanh)) ||
1613                  (Name == "tanhf" && TLI->has(LibFunc::tanhf)))
1614           return ConstantFoldFP(tanh, V, Ty);
1615         break;
1616       default:
1617         break;
1618       }
1619       return nullptr;
1620     }
1621 
1622     if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1623       switch (IntrinsicID) {
1624       case Intrinsic::bswap:
1625         return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
1626       case Intrinsic::ctpop:
1627         return ConstantInt::get(Ty, Op->getValue().countPopulation());
1628       case Intrinsic::bitreverse:
1629         return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
1630       case Intrinsic::convert_from_fp16: {
1631         APFloat Val(APFloat::IEEEhalf, Op->getValue());
1632 
1633         bool lost = false;
1634         APFloat::opStatus status = Val.convert(
1635             Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
1636 
1637         // Conversion is always precise.
1638         (void)status;
1639         assert(status == APFloat::opOK && !lost &&
1640                "Precision lost during fp16 constfolding");
1641 
1642         return ConstantFP::get(Ty->getContext(), Val);
1643       }
1644       default:
1645         return nullptr;
1646       }
1647     }
1648 
1649     // Support ConstantVector in case we have an Undef in the top.
1650     if (isa<ConstantVector>(Operands[0]) ||
1651         isa<ConstantDataVector>(Operands[0])) {
1652       Constant *Op = cast<Constant>(Operands[0]);
1653       switch (IntrinsicID) {
1654       default: break;
1655       case Intrinsic::x86_sse_cvtss2si:
1656       case Intrinsic::x86_sse_cvtss2si64:
1657       case Intrinsic::x86_sse2_cvtsd2si:
1658       case Intrinsic::x86_sse2_cvtsd2si64:
1659         if (ConstantFP *FPOp =
1660               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1661           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1662                                           /*roundTowardZero=*/false, Ty);
1663       case Intrinsic::x86_sse_cvttss2si:
1664       case Intrinsic::x86_sse_cvttss2si64:
1665       case Intrinsic::x86_sse2_cvttsd2si:
1666       case Intrinsic::x86_sse2_cvttsd2si64:
1667         if (ConstantFP *FPOp =
1668               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1669           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1670                                           /*roundTowardZero=*/true, Ty);
1671       }
1672     }
1673 
1674     if (isa<UndefValue>(Operands[0])) {
1675       if (IntrinsicID == Intrinsic::bswap)
1676         return Operands[0];
1677       return nullptr;
1678     }
1679 
1680     return nullptr;
1681   }
1682 
1683   if (Operands.size() == 2) {
1684     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1685       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1686         return nullptr;
1687       double Op1V = getValueAsDouble(Op1);
1688 
1689       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1690         if (Op2->getType() != Op1->getType())
1691           return nullptr;
1692 
1693         double Op2V = getValueAsDouble(Op2);
1694         if (IntrinsicID == Intrinsic::pow) {
1695           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1696         }
1697         if (IntrinsicID == Intrinsic::copysign) {
1698           APFloat V1 = Op1->getValueAPF();
1699           const APFloat &V2 = Op2->getValueAPF();
1700           V1.copySign(V2);
1701           return ConstantFP::get(Ty->getContext(), V1);
1702         }
1703 
1704         if (IntrinsicID == Intrinsic::minnum) {
1705           const APFloat &C1 = Op1->getValueAPF();
1706           const APFloat &C2 = Op2->getValueAPF();
1707           return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1708         }
1709 
1710         if (IntrinsicID == Intrinsic::maxnum) {
1711           const APFloat &C1 = Op1->getValueAPF();
1712           const APFloat &C2 = Op2->getValueAPF();
1713           return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1714         }
1715 
1716         if (!TLI)
1717           return nullptr;
1718         if ((Name == "pow" && TLI->has(LibFunc::pow)) ||
1719             (Name == "powf" && TLI->has(LibFunc::powf)))
1720           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1721         if ((Name == "fmod" && TLI->has(LibFunc::fmod)) ||
1722             (Name == "fmodf" && TLI->has(LibFunc::fmodf)))
1723           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1724         if ((Name == "atan2" && TLI->has(LibFunc::atan2)) ||
1725             (Name == "atan2f" && TLI->has(LibFunc::atan2f)))
1726           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1727       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1728         if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1729           return ConstantFP::get(Ty->getContext(),
1730                                  APFloat((float)std::pow((float)Op1V,
1731                                                  (int)Op2C->getZExtValue())));
1732         if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1733           return ConstantFP::get(Ty->getContext(),
1734                                  APFloat((float)std::pow((float)Op1V,
1735                                                  (int)Op2C->getZExtValue())));
1736         if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1737           return ConstantFP::get(Ty->getContext(),
1738                                  APFloat((double)std::pow((double)Op1V,
1739                                                    (int)Op2C->getZExtValue())));
1740       }
1741       return nullptr;
1742     }
1743 
1744     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1745       if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1746         switch (IntrinsicID) {
1747         default: break;
1748         case Intrinsic::sadd_with_overflow:
1749         case Intrinsic::uadd_with_overflow:
1750         case Intrinsic::ssub_with_overflow:
1751         case Intrinsic::usub_with_overflow:
1752         case Intrinsic::smul_with_overflow:
1753         case Intrinsic::umul_with_overflow: {
1754           APInt Res;
1755           bool Overflow;
1756           switch (IntrinsicID) {
1757           default: llvm_unreachable("Invalid case");
1758           case Intrinsic::sadd_with_overflow:
1759             Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1760             break;
1761           case Intrinsic::uadd_with_overflow:
1762             Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1763             break;
1764           case Intrinsic::ssub_with_overflow:
1765             Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1766             break;
1767           case Intrinsic::usub_with_overflow:
1768             Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1769             break;
1770           case Intrinsic::smul_with_overflow:
1771             Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1772             break;
1773           case Intrinsic::umul_with_overflow:
1774             Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1775             break;
1776           }
1777           Constant *Ops[] = {
1778             ConstantInt::get(Ty->getContext(), Res),
1779             ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
1780           };
1781           return ConstantStruct::get(cast<StructType>(Ty), Ops);
1782         }
1783         case Intrinsic::cttz:
1784           if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1785             return UndefValue::get(Ty);
1786           return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1787         case Intrinsic::ctlz:
1788           if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1789             return UndefValue::get(Ty);
1790           return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1791         }
1792       }
1793 
1794       return nullptr;
1795     }
1796     return nullptr;
1797   }
1798 
1799   if (Operands.size() != 3)
1800     return nullptr;
1801 
1802   if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1803     if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1804       if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
1805         switch (IntrinsicID) {
1806         default: break;
1807         case Intrinsic::fma:
1808         case Intrinsic::fmuladd: {
1809           APFloat V = Op1->getValueAPF();
1810           APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1811                                                    Op3->getValueAPF(),
1812                                                    APFloat::rmNearestTiesToEven);
1813           if (s != APFloat::opInvalidOp)
1814             return ConstantFP::get(Ty->getContext(), V);
1815 
1816           return nullptr;
1817         }
1818         }
1819       }
1820     }
1821   }
1822 
1823   return nullptr;
1824 }
1825 
1826 Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1827                                  VectorType *VTy, ArrayRef<Constant *> Operands,
1828                                  const TargetLibraryInfo *TLI) {
1829   SmallVector<Constant *, 4> Result(VTy->getNumElements());
1830   SmallVector<Constant *, 4> Lane(Operands.size());
1831   Type *Ty = VTy->getElementType();
1832 
1833   for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1834     // Gather a column of constants.
1835     for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1836       Constant *Agg = Operands[J]->getAggregateElement(I);
1837       if (!Agg)
1838         return nullptr;
1839 
1840       Lane[J] = Agg;
1841     }
1842 
1843     // Use the regular scalar folding to simplify this column.
1844     Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1845     if (!Folded)
1846       return nullptr;
1847     Result[I] = Folded;
1848   }
1849 
1850   return ConstantVector::get(Result);
1851 }
1852 
1853 } // end anonymous namespace
1854 
1855 Constant *
1856 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1857                        const TargetLibraryInfo *TLI) {
1858   if (!F->hasName())
1859     return nullptr;
1860   StringRef Name = F->getName();
1861 
1862   Type *Ty = F->getReturnType();
1863 
1864   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1865     return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1866 
1867   return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1868 }
1869