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