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