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