progress making the world safe to ConstantDataVector. While
[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 VMCore ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // TargetData information. These functions cannot go in VMCore due to library
15 // dependency issues.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/Operator.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLibraryInfo.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/FEnv.h"
36 #include <cerrno>
37 #include <cmath>
38 using namespace llvm;
39
40 //===----------------------------------------------------------------------===//
41 // Constant Folding internal helper functions
42 //===----------------------------------------------------------------------===//
43
44 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with 
45 /// TargetData.  This always returns a non-null constant, but it may be a
46 /// ConstantExpr if unfoldable.
47 static Constant *FoldBitCast(Constant *C, Type *DestTy,
48                              const TargetData &TD) {
49   // Catch the obvious splat cases.
50   if (C->isNullValue() && !DestTy->isX86_MMXTy())
51     return Constant::getNullValue(DestTy);
52   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
53     return Constant::getAllOnesValue(DestTy);
54
55   // The code below only handles casts to vectors currently.
56   VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
57   if (DestVTy == 0)
58     return ConstantExpr::getBitCast(C, DestTy);
59   
60   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
61   // vector so the code below can handle it uniformly.
62   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
63     Constant *Ops = C; // don't take the address of C!
64     return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
65   }
66   
67   // If this is a bitcast from constant vector -> vector, fold it.
68   // FIXME: Remove ConstantVector support.
69   if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
70     return ConstantExpr::getBitCast(C, DestTy);
71   
72   // If the element types match, VMCore can fold it.
73   unsigned NumDstElt = DestVTy->getNumElements();
74   unsigned NumSrcElt = C->getType()->getVectorNumElements();
75   if (NumDstElt == NumSrcElt)
76     return ConstantExpr::getBitCast(C, DestTy);
77   
78   Type *SrcEltTy = C->getType()->getVectorElementType();
79   Type *DstEltTy = DestVTy->getElementType();
80   
81   // Otherwise, we're changing the number of elements in a vector, which 
82   // requires endianness information to do the right thing.  For example,
83   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
84   // folds to (little endian):
85   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
86   // and to (big endian):
87   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
88   
89   // First thing is first.  We only want to think about integer here, so if
90   // we have something in FP form, recast it as integer.
91   if (DstEltTy->isFloatingPointTy()) {
92     // Fold to an vector of integers with same size as our FP type.
93     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
94     Type *DestIVTy =
95       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
96     // Recursively handle this integer conversion, if possible.
97     C = FoldBitCast(C, DestIVTy, TD);
98     
99     // Finally, VMCore can handle this now that #elts line up.
100     return ConstantExpr::getBitCast(C, DestTy);
101   }
102   
103   // Okay, we know the destination is integer, if the input is FP, convert
104   // it to integer first.
105   if (SrcEltTy->isFloatingPointTy()) {
106     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
107     Type *SrcIVTy =
108       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
109     // Ask VMCore to do the conversion now that #elts line up.
110     C = ConstantExpr::getBitCast(C, SrcIVTy);
111     // If VMCore wasn't able to fold it, bail out.
112     if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
113         !isa<ConstantDataVector>(C))
114       return C;
115   }
116   
117   // Now we know that the input and output vectors are both integer vectors
118   // of the same size, and that their #elements is not the same.  Do the
119   // conversion here, which depends on whether the input or output has
120   // more elements.
121   bool isLittleEndian = TD.isLittleEndian();
122   
123   SmallVector<Constant*, 32> Result;
124   if (NumDstElt < NumSrcElt) {
125     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
126     Constant *Zero = Constant::getNullValue(DstEltTy);
127     unsigned Ratio = NumSrcElt/NumDstElt;
128     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
129     unsigned SrcElt = 0;
130     for (unsigned i = 0; i != NumDstElt; ++i) {
131       // Build each element of the result.
132       Constant *Elt = Zero;
133       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
134       for (unsigned j = 0; j != Ratio; ++j) {
135         Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
136         if (!Src)  // Reject constantexpr elements.
137           return ConstantExpr::getBitCast(C, DestTy);
138         
139         // Zero extend the element to the right size.
140         Src = ConstantExpr::getZExt(Src, Elt->getType());
141         
142         // Shift it to the right place, depending on endianness.
143         Src = ConstantExpr::getShl(Src, 
144                                    ConstantInt::get(Src->getType(), ShiftAmt));
145         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
146         
147         // Mix it in.
148         Elt = ConstantExpr::getOr(Elt, Src);
149       }
150       Result.push_back(Elt);
151     }
152     return ConstantVector::get(Result);
153   }
154   
155   // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
156   unsigned Ratio = NumDstElt/NumSrcElt;
157   unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
158   
159   // Loop over each source value, expanding into multiple results.
160   for (unsigned i = 0; i != NumSrcElt; ++i) {
161     Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
162     if (!Src)  // Reject constantexpr elements.
163       return ConstantExpr::getBitCast(C, DestTy);
164     
165     unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
166     for (unsigned j = 0; j != Ratio; ++j) {
167       // Shift the piece of the value into the right place, depending on
168       // endianness.
169       Constant *Elt = ConstantExpr::getLShr(Src, 
170                                   ConstantInt::get(Src->getType(), ShiftAmt));
171       ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
172       
173       // Truncate and remember this piece.
174       Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
175     }
176   }
177   
178   return ConstantVector::get(Result);
179 }
180
181
182 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
183 /// from a global, return the global and the constant.  Because of
184 /// constantexprs, this function is recursive.
185 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
186                                        int64_t &Offset, const TargetData &TD) {
187   // Trivial case, constant is the global.
188   if ((GV = dyn_cast<GlobalValue>(C))) {
189     Offset = 0;
190     return true;
191   }
192   
193   // Otherwise, if this isn't a constant expr, bail out.
194   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
195   if (!CE) return false;
196   
197   // Look through ptr->int and ptr->ptr casts.
198   if (CE->getOpcode() == Instruction::PtrToInt ||
199       CE->getOpcode() == Instruction::BitCast)
200     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
201   
202   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)    
203   if (CE->getOpcode() == Instruction::GetElementPtr) {
204     // Cannot compute this if the element type of the pointer is missing size
205     // info.
206     if (!cast<PointerType>(CE->getOperand(0)->getType())
207                  ->getElementType()->isSized())
208       return false;
209     
210     // If the base isn't a global+constant, we aren't either.
211     if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
212       return false;
213     
214     // Otherwise, add any offset that our operands provide.
215     gep_type_iterator GTI = gep_type_begin(CE);
216     for (User::const_op_iterator i = CE->op_begin() + 1, e = CE->op_end();
217          i != e; ++i, ++GTI) {
218       ConstantInt *CI = dyn_cast<ConstantInt>(*i);
219       if (!CI) return false;  // Index isn't a simple constant?
220       if (CI->isZero()) continue;  // Not adding anything.
221       
222       if (StructType *ST = dyn_cast<StructType>(*GTI)) {
223         // N = N + Offset
224         Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
225       } else {
226         SequentialType *SQT = cast<SequentialType>(*GTI);
227         Offset += TD.getTypeAllocSize(SQT->getElementType())*CI->getSExtValue();
228       }
229     }
230     return true;
231   }
232   
233   return false;
234 }
235
236 /// ReadDataFromGlobal - Recursive helper to read bits out of global.  C is the
237 /// constant being copied out of. ByteOffset is an offset into C.  CurPtr is the
238 /// pointer to copy results into and BytesLeft is the number of bytes left in
239 /// the CurPtr buffer.  TD is the target data.
240 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
241                                unsigned char *CurPtr, unsigned BytesLeft,
242                                const TargetData &TD) {
243   assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
244          "Out of range access");
245   
246   // If this element is zero or undefined, we can just return since *CurPtr is
247   // zero initialized.
248   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
249     return true;
250   
251   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
252     if (CI->getBitWidth() > 64 ||
253         (CI->getBitWidth() & 7) != 0)
254       return false;
255     
256     uint64_t Val = CI->getZExtValue();
257     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
258     
259     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
260       CurPtr[i] = (unsigned char)(Val >> (ByteOffset * 8));
261       ++ByteOffset;
262     }
263     return true;
264   }
265   
266   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
267     if (CFP->getType()->isDoubleTy()) {
268       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
269       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
270     }
271     if (CFP->getType()->isFloatTy()){
272       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
273       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
274     }
275     return false;
276   }
277   
278   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
279     const StructLayout *SL = TD.getStructLayout(CS->getType());
280     unsigned Index = SL->getElementContainingOffset(ByteOffset);
281     uint64_t CurEltOffset = SL->getElementOffset(Index);
282     ByteOffset -= CurEltOffset;
283     
284     while (1) {
285       // If the element access is to the element itself and not to tail padding,
286       // read the bytes from the element.
287       uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
288
289       if (ByteOffset < EltSize &&
290           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
291                               BytesLeft, TD))
292         return false;
293       
294       ++Index;
295       
296       // Check to see if we read from the last struct element, if so we're done.
297       if (Index == CS->getType()->getNumElements())
298         return true;
299
300       // If we read all of the bytes we needed from this element we're done.
301       uint64_t NextEltOffset = SL->getElementOffset(Index);
302
303       if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
304         return true;
305
306       // Move to the next element of the struct.
307       CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
308       BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
309       ByteOffset = 0;
310       CurEltOffset = NextEltOffset;
311     }
312     // not reached.
313   }
314
315   // FIXME: Remove ConstantVector
316   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
317       isa<ConstantDataSequential>(C)) {
318     Type *EltTy = cast<SequentialType>(C->getType())->getElementType();
319     uint64_t EltSize = TD.getTypeAllocSize(EltTy);
320     uint64_t Index = ByteOffset / EltSize;
321     uint64_t Offset = ByteOffset - Index * EltSize;
322     uint64_t NumElts;
323     if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
324       NumElts = AT->getNumElements();
325     else
326       NumElts = cast<VectorType>(C->getType())->getNumElements();
327     
328     for (; Index != NumElts; ++Index) {
329       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
330                               BytesLeft, TD))
331         return false;
332       if (EltSize >= BytesLeft)
333         return true;
334       
335       Offset = 0;
336       BytesLeft -= EltSize;
337       CurPtr += EltSize;
338     }
339     return true;
340   }
341       
342   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
343     if (CE->getOpcode() == Instruction::IntToPtr &&
344         CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getContext())) 
345       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr, 
346                                 BytesLeft, TD);
347   }
348
349   // Otherwise, unknown initializer type.
350   return false;
351 }
352
353 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
354                                                  const TargetData &TD) {
355   Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
356   IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
357   
358   // If this isn't an integer load we can't fold it directly.
359   if (!IntType) {
360     // If this is a float/double load, we can try folding it as an int32/64 load
361     // and then bitcast the result.  This can be useful for union cases.  Note
362     // that address spaces don't matter here since we're not going to result in
363     // an actual new load.
364     Type *MapTy;
365     if (LoadTy->isFloatTy())
366       MapTy = Type::getInt32PtrTy(C->getContext());
367     else if (LoadTy->isDoubleTy())
368       MapTy = Type::getInt64PtrTy(C->getContext());
369     else if (LoadTy->isVectorTy()) {
370       MapTy = IntegerType::get(C->getContext(),
371                                TD.getTypeAllocSizeInBits(LoadTy));
372       MapTy = PointerType::getUnqual(MapTy);
373     } else
374       return 0;
375
376     C = FoldBitCast(C, MapTy, TD);
377     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
378       return FoldBitCast(Res, LoadTy, TD);
379     return 0;
380   }
381   
382   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
383   if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
384   
385   GlobalValue *GVal;
386   int64_t Offset;
387   if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
388     return 0;
389   
390   GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
391   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
392       !GV->getInitializer()->getType()->isSized())
393     return 0;
394
395   // If we're loading off the beginning of the global, some bytes may be valid,
396   // but we don't try to handle this.
397   if (Offset < 0) return 0;
398   
399   // If we're not accessing anything in this constant, the result is undefined.
400   if (uint64_t(Offset) >= TD.getTypeAllocSize(GV->getInitializer()->getType()))
401     return UndefValue::get(IntType);
402   
403   unsigned char RawBytes[32] = {0};
404   if (!ReadDataFromGlobal(GV->getInitializer(), Offset, RawBytes,
405                           BytesLoaded, TD))
406     return 0;
407
408   APInt ResultVal = APInt(IntType->getBitWidth(), RawBytes[BytesLoaded-1]);
409   for (unsigned i = 1; i != BytesLoaded; ++i) {
410     ResultVal <<= 8;
411     ResultVal |= RawBytes[BytesLoaded-1-i];
412   }
413
414   return ConstantInt::get(IntType->getContext(), ResultVal);
415 }
416
417 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
418 /// produce if it is constant and determinable.  If this is not determinable,
419 /// return null.
420 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
421                                              const TargetData *TD) {
422   // First, try the easy cases:
423   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
424     if (GV->isConstant() && GV->hasDefinitiveInitializer())
425       return GV->getInitializer();
426
427   // If the loaded value isn't a constant expr, we can't handle it.
428   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
429   if (!CE) return 0;
430   
431   if (CE->getOpcode() == Instruction::GetElementPtr) {
432     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
433       if (GV->isConstant() && GV->hasDefinitiveInitializer())
434         if (Constant *V = 
435              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
436           return V;
437   }
438   
439   // Instead of loading constant c string, use corresponding integer value
440   // directly if string length is small enough.
441   std::string Str;
442   if (TD && GetConstantStringInfo(CE, Str) && !Str.empty()) {
443     unsigned StrLen = Str.length();
444     Type *Ty = cast<PointerType>(CE->getType())->getElementType();
445     unsigned NumBits = Ty->getPrimitiveSizeInBits();
446     // Replace load with immediate integer if the result is an integer or fp
447     // value.
448     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
449         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
450       APInt StrVal(NumBits, 0);
451       APInt SingleChar(NumBits, 0);
452       if (TD->isLittleEndian()) {
453         for (signed i = StrLen-1; i >= 0; i--) {
454           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
455           StrVal = (StrVal << 8) | SingleChar;
456         }
457       } else {
458         for (unsigned i = 0; i < StrLen; i++) {
459           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
460           StrVal = (StrVal << 8) | SingleChar;
461         }
462         // Append NULL at the end.
463         SingleChar = 0;
464         StrVal = (StrVal << 8) | SingleChar;
465       }
466       
467       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
468       if (Ty->isFloatingPointTy())
469         Res = ConstantExpr::getBitCast(Res, Ty);
470       return Res;
471     }
472   }
473   
474   // If this load comes from anywhere in a constant global, and if the global
475   // is all undef or zero, we know what it loads.
476   if (GlobalVariable *GV =
477         dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
478     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
479       Type *ResTy = cast<PointerType>(C->getType())->getElementType();
480       if (GV->getInitializer()->isNullValue())
481         return Constant::getNullValue(ResTy);
482       if (isa<UndefValue>(GV->getInitializer()))
483         return UndefValue::get(ResTy);
484     }
485   }
486   
487   // Try hard to fold loads from bitcasted strange and non-type-safe things.  We
488   // currently don't do any of this for big endian systems.  It can be
489   // generalized in the future if someone is interested.
490   if (TD && TD->isLittleEndian())
491     return FoldReinterpretLoadFromConstPtr(CE, *TD);
492   return 0;
493 }
494
495 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const TargetData *TD){
496   if (LI->isVolatile()) return 0;
497   
498   if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
499     return ConstantFoldLoadFromConstPtr(C, TD);
500
501   return 0;
502 }
503
504 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
505 /// Attempt to symbolically evaluate the result of a binary operator merging
506 /// these together.  If target data info is available, it is provided as TD, 
507 /// otherwise TD is null.
508 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
509                                            Constant *Op1, const TargetData *TD){
510   // SROA
511   
512   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
513   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
514   // bits.
515   
516   
517   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
518   // constant.  This happens frequently when iterating over a global array.
519   if (Opc == Instruction::Sub && TD) {
520     GlobalValue *GV1, *GV2;
521     int64_t Offs1, Offs2;
522     
523     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
524       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
525           GV1 == GV2) {
526         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
527         return ConstantInt::get(Op0->getType(), Offs1-Offs2);
528       }
529   }
530     
531   return 0;
532 }
533
534 /// CastGEPIndices - If array indices are not pointer-sized integers,
535 /// explicitly cast them so that they aren't implicitly casted by the
536 /// getelementptr.
537 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
538                                 Type *ResultTy, const TargetData *TD,
539                                 const TargetLibraryInfo *TLI) {
540   if (!TD) return 0;
541   Type *IntPtrTy = TD->getIntPtrType(ResultTy->getContext());
542
543   bool Any = false;
544   SmallVector<Constant*, 32> NewIdxs;
545   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
546     if ((i == 1 ||
547          !isa<StructType>(GetElementPtrInst::getIndexedType(Ops[0]->getType(),
548                                                         Ops.slice(1, i-1)))) &&
549         Ops[i]->getType() != IntPtrTy) {
550       Any = true;
551       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
552                                                                       true,
553                                                                       IntPtrTy,
554                                                                       true),
555                                               Ops[i], IntPtrTy));
556     } else
557       NewIdxs.push_back(Ops[i]);
558   }
559   if (!Any) return 0;
560
561   Constant *C =
562     ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
563   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
564     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
565       C = Folded;
566   return C;
567 }
568
569 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
570 /// constant expression, do so.
571 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
572                                          Type *ResultTy, const TargetData *TD,
573                                          const TargetLibraryInfo *TLI) {
574   Constant *Ptr = Ops[0];
575   if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized() ||
576       !Ptr->getType()->isPointerTy())
577     return 0;
578   
579   Type *IntPtrTy = TD->getIntPtrType(Ptr->getContext());
580
581   // If this is a constant expr gep that is effectively computing an
582   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
583   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
584     if (!isa<ConstantInt>(Ops[i])) {
585       
586       // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
587       // "inttoptr (sub (ptrtoint Ptr), V)"
588       if (Ops.size() == 2 &&
589           cast<PointerType>(ResultTy)->getElementType()->isIntegerTy(8)) {
590         ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
591         assert((CE == 0 || CE->getType() == IntPtrTy) &&
592                "CastGEPIndices didn't canonicalize index types!");
593         if (CE && CE->getOpcode() == Instruction::Sub &&
594             CE->getOperand(0)->isNullValue()) {
595           Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
596           Res = ConstantExpr::getSub(Res, CE->getOperand(1));
597           Res = ConstantExpr::getIntToPtr(Res, ResultTy);
598           if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
599             Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
600           return Res;
601         }
602       }
603       return 0;
604     }
605   
606   unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
607   APInt Offset =
608     APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
609                                          makeArrayRef((Value **)Ops.data() + 1,
610                                                       Ops.size() - 1)));
611   Ptr = cast<Constant>(Ptr->stripPointerCasts());
612
613   // If this is a GEP of a GEP, fold it all into a single GEP.
614   while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
615     SmallVector<Value *, 4> NestedOps(GEP->op_begin()+1, GEP->op_end());
616
617     // Do not try the incorporate the sub-GEP if some index is not a number.
618     bool AllConstantInt = true;
619     for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
620       if (!isa<ConstantInt>(NestedOps[i])) {
621         AllConstantInt = false;
622         break;
623       }
624     if (!AllConstantInt)
625       break;
626
627     Ptr = cast<Constant>(GEP->getOperand(0));
628     Offset += APInt(BitWidth,
629                     TD->getIndexedOffset(Ptr->getType(), NestedOps));
630     Ptr = cast<Constant>(Ptr->stripPointerCasts());
631   }
632
633   // If the base value for this address is a literal integer value, fold the
634   // getelementptr to the resulting integer value casted to the pointer type.
635   APInt BasePtr(BitWidth, 0);
636   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
637     if (CE->getOpcode() == Instruction::IntToPtr)
638       if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
639         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
640   if (Ptr->isNullValue() || BasePtr != 0) {
641     Constant *C = ConstantInt::get(Ptr->getContext(), Offset+BasePtr);
642     return ConstantExpr::getIntToPtr(C, ResultTy);
643   }
644
645   // Otherwise form a regular getelementptr. Recompute the indices so that
646   // we eliminate over-indexing of the notional static type array bounds.
647   // This makes it easy to determine if the getelementptr is "inbounds".
648   // Also, this helps GlobalOpt do SROA on GlobalVariables.
649   Type *Ty = Ptr->getType();
650   SmallVector<Constant*, 32> NewIdxs;
651   do {
652     if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
653       if (ATy->isPointerTy()) {
654         // The only pointer indexing we'll do is on the first index of the GEP.
655         if (!NewIdxs.empty())
656           break;
657        
658         // Only handle pointers to sized types, not pointers to functions.
659         if (!ATy->getElementType()->isSized())
660           return 0;
661       }
662         
663       // Determine which element of the array the offset points into.
664       APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
665       IntegerType *IntPtrTy = TD->getIntPtrType(Ty->getContext());
666       if (ElemSize == 0)
667         // The element size is 0. This may be [0 x Ty]*, so just use a zero
668         // index for this level and proceed to the next level to see if it can
669         // accommodate the offset.
670         NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
671       else {
672         // The element size is non-zero divide the offset by the element
673         // size (rounding down), to compute the index at this level.
674         APInt NewIdx = Offset.udiv(ElemSize);
675         Offset -= NewIdx * ElemSize;
676         NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
677       }
678       Ty = ATy->getElementType();
679     } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
680       // Determine which field of the struct the offset points into. The
681       // getZExtValue is at least as safe as the StructLayout API because we
682       // know the offset is within the struct at this point.
683       const StructLayout &SL = *TD->getStructLayout(STy);
684       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
685       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
686                                          ElIdx));
687       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
688       Ty = STy->getTypeAtIndex(ElIdx);
689     } else {
690       // We've reached some non-indexable type.
691       break;
692     }
693   } while (Ty != cast<PointerType>(ResultTy)->getElementType());
694
695   // If we haven't used up the entire offset by descending the static
696   // type, then the offset is pointing into the middle of an indivisible
697   // member, so we can't simplify it.
698   if (Offset != 0)
699     return 0;
700
701   // Create a GEP.
702   Constant *C =
703     ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
704   assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
705          "Computed GetElementPtr has unexpected type!");
706
707   // If we ended up indexing a member with a type that doesn't match
708   // the type of what the original indices indexed, add a cast.
709   if (Ty != cast<PointerType>(ResultTy)->getElementType())
710     C = FoldBitCast(C, ResultTy, *TD);
711
712   return C;
713 }
714
715
716
717 //===----------------------------------------------------------------------===//
718 // Constant Folding public APIs
719 //===----------------------------------------------------------------------===//
720
721 /// ConstantFoldInstruction - Try to constant fold the specified instruction.
722 /// If successful, the constant result is returned, if not, null is returned.
723 /// Note that this fails if not all of the operands are constant.  Otherwise,
724 /// this function can only fail when attempting to fold instructions like loads
725 /// and stores, which have no constant expression form.
726 Constant *llvm::ConstantFoldInstruction(Instruction *I,
727                                         const TargetData *TD,
728                                         const TargetLibraryInfo *TLI) {
729   // Handle PHI nodes quickly here...
730   if (PHINode *PN = dyn_cast<PHINode>(I)) {
731     Constant *CommonValue = 0;
732
733     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
734       Value *Incoming = PN->getIncomingValue(i);
735       // If the incoming value is undef then skip it.  Note that while we could
736       // skip the value if it is equal to the phi node itself we choose not to
737       // because that would break the rule that constant folding only applies if
738       // all operands are constants.
739       if (isa<UndefValue>(Incoming))
740         continue;
741       // If the incoming value is not a constant, or is a different constant to
742       // the one we saw previously, then give up.
743       Constant *C = dyn_cast<Constant>(Incoming);
744       if (!C || (CommonValue && C != CommonValue))
745         return 0;
746       CommonValue = C;
747     }
748
749     // If we reach here, all incoming values are the same constant or undef.
750     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
751   }
752
753   // Scan the operand list, checking to see if they are all constants, if so,
754   // hand off to ConstantFoldInstOperands.
755   SmallVector<Constant*, 8> Ops;
756   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
757     if (Constant *Op = dyn_cast<Constant>(*i))
758       Ops.push_back(Op);
759     else
760       return 0;  // All operands not constant!
761
762   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
763     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
764                                            TD, TLI);
765   
766   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
767     return ConstantFoldLoadInst(LI, TD);
768
769   if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I))
770     return ConstantExpr::getInsertValue(
771                                 cast<Constant>(IVI->getAggregateOperand()),
772                                 cast<Constant>(IVI->getInsertedValueOperand()),
773                                 IVI->getIndices());
774
775   if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I))
776     return ConstantExpr::getExtractValue(
777                                     cast<Constant>(EVI->getAggregateOperand()),
778                                     EVI->getIndices());
779
780   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
781 }
782
783 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
784 /// using the specified TargetData.  If successful, the constant result is
785 /// result is returned, if not, null is returned.
786 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
787                                                const TargetData *TD,
788                                                const TargetLibraryInfo *TLI) {
789   SmallVector<Constant*, 8> Ops;
790   for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end();
791        i != e; ++i) {
792     Constant *NewC = cast<Constant>(*i);
793     // Recursively fold the ConstantExpr's operands.
794     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC))
795       NewC = ConstantFoldConstantExpression(NewCE, TD, TLI);
796     Ops.push_back(NewC);
797   }
798
799   if (CE->isCompare())
800     return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
801                                            TD, TLI);
802   return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
803 }
804
805 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
806 /// specified opcode and operands.  If successful, the constant result is
807 /// returned, if not, null is returned.  Note that this function can fail when
808 /// attempting to fold instructions like loads and stores, which have no
809 /// constant expression form.
810 ///
811 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
812 /// information, due to only being passed an opcode and operands. Constant
813 /// folding using this function strips this information.
814 ///
815 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy, 
816                                          ArrayRef<Constant *> Ops,
817                                          const TargetData *TD,
818                                          const TargetLibraryInfo *TLI) {                                         
819   // Handle easy binops first.
820   if (Instruction::isBinaryOp(Opcode)) {
821     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
822       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
823         return C;
824     
825     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
826   }
827   
828   switch (Opcode) {
829   default: return 0;
830   case Instruction::ICmp:
831   case Instruction::FCmp: assert(0 && "Invalid for compares");
832   case Instruction::Call:
833     if (Function *F = dyn_cast<Function>(Ops.back()))
834       if (canConstantFoldCallTo(F))
835         return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
836     return 0;
837   case Instruction::PtrToInt:
838     // If the input is a inttoptr, eliminate the pair.  This requires knowing
839     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
840     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
841       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
842         Constant *Input = CE->getOperand(0);
843         unsigned InWidth = Input->getType()->getScalarSizeInBits();
844         if (TD->getPointerSizeInBits() < InWidth) {
845           Constant *Mask = 
846             ConstantInt::get(CE->getContext(), APInt::getLowBitsSet(InWidth,
847                                                   TD->getPointerSizeInBits()));
848           Input = ConstantExpr::getAnd(Input, Mask);
849         }
850         // Do a zext or trunc to get to the dest size.
851         return ConstantExpr::getIntegerCast(Input, DestTy, false);
852       }
853     }
854     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
855   case Instruction::IntToPtr:
856     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
857     // the int size is >= the ptr size.  This requires knowing the width of a
858     // pointer, so it can't be done in ConstantExpr::getCast.
859     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
860       if (TD &&
861           TD->getPointerSizeInBits() <= CE->getType()->getScalarSizeInBits() &&
862           CE->getOpcode() == Instruction::PtrToInt)
863         return FoldBitCast(CE->getOperand(0), DestTy, *TD);
864
865     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
866   case Instruction::Trunc:
867   case Instruction::ZExt:
868   case Instruction::SExt:
869   case Instruction::FPTrunc:
870   case Instruction::FPExt:
871   case Instruction::UIToFP:
872   case Instruction::SIToFP:
873   case Instruction::FPToUI:
874   case Instruction::FPToSI:
875       return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
876   case Instruction::BitCast:
877     if (TD)
878       return FoldBitCast(Ops[0], DestTy, *TD);
879     return ConstantExpr::getBitCast(Ops[0], DestTy);
880   case Instruction::Select:
881     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
882   case Instruction::ExtractElement:
883     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
884   case Instruction::InsertElement:
885     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
886   case Instruction::ShuffleVector:
887     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
888   case Instruction::GetElementPtr:
889     if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
890       return C;
891     if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
892       return C;
893     
894     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
895   }
896 }
897
898 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
899 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
900 /// returns a constant expression of the specified operands.
901 ///
902 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
903                                                 Constant *Ops0, Constant *Ops1, 
904                                                 const TargetData *TD,
905                                                 const TargetLibraryInfo *TLI) {
906   // fold: icmp (inttoptr x), null         -> icmp x, 0
907   // fold: icmp (ptrtoint x), 0            -> icmp x, null
908   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
909   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
910   //
911   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
912   // around to know if bit truncation is happening.
913   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
914     if (TD && Ops1->isNullValue()) {
915       Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
916       if (CE0->getOpcode() == Instruction::IntToPtr) {
917         // Convert the integer value to the right size to ensure we get the
918         // proper extension or truncation.
919         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
920                                                    IntPtrTy, false);
921         Constant *Null = Constant::getNullValue(C->getType());
922         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
923       }
924       
925       // Only do this transformation if the int is intptrty in size, otherwise
926       // there is a truncation or extension that we aren't modeling.
927       if (CE0->getOpcode() == Instruction::PtrToInt && 
928           CE0->getType() == IntPtrTy) {
929         Constant *C = CE0->getOperand(0);
930         Constant *Null = Constant::getNullValue(C->getType());
931         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
932       }
933     }
934     
935     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
936       if (TD && CE0->getOpcode() == CE1->getOpcode()) {
937         Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
938
939         if (CE0->getOpcode() == Instruction::IntToPtr) {
940           // Convert the integer value to the right size to ensure we get the
941           // proper extension or truncation.
942           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
943                                                       IntPtrTy, false);
944           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
945                                                       IntPtrTy, false);
946           return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
947         }
948
949         // Only do this transformation if the int is intptrty in size, otherwise
950         // there is a truncation or extension that we aren't modeling.
951         if ((CE0->getOpcode() == Instruction::PtrToInt &&
952              CE0->getType() == IntPtrTy &&
953              CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()))
954           return ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0),
955                                                  CE1->getOperand(0), TD, TLI);
956       }
957     }
958     
959     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
960     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
961     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
962         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
963       Constant *LHS = 
964         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
965                                         TD, TLI);
966       Constant *RHS = 
967         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
968                                         TD, TLI);
969       unsigned OpC = 
970         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
971       Constant *Ops[] = { LHS, RHS };
972       return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
973     }
974   }
975   
976   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
977 }
978
979
980 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
981 /// getelementptr constantexpr, return the constant value being addressed by the
982 /// constant expression, or null if something is funny and we can't decide.
983 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, 
984                                                        ConstantExpr *CE) {
985   if (!CE->getOperand(1)->isNullValue())
986     return 0;  // Do not allow stepping over the value!
987
988   // Loop over all of the operands, tracking down which value we are
989   // addressing.
990   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
991     C = C->getAggregateElement(CE->getOperand(i));
992     if (C == 0) return 0;
993   }
994   return C;
995 }
996
997 /// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
998 /// indices (with an *implied* zero pointer index that is not in the list),
999 /// return the constant value being addressed by a virtual load, or null if
1000 /// something is funny and we can't decide.
1001 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1002                                                   ArrayRef<Constant*> Indices) {
1003   // Loop over all of the operands, tracking down which value we are
1004   // addressing.
1005   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1006     C = C->getAggregateElement(Indices[i]);
1007     if (C == 0) return 0;
1008   }
1009   return C;
1010 }
1011
1012
1013 //===----------------------------------------------------------------------===//
1014 //  Constant Folding for Calls
1015 //
1016
1017 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
1018 /// the specified function.
1019 bool
1020 llvm::canConstantFoldCallTo(const Function *F) {
1021   switch (F->getIntrinsicID()) {
1022   case Intrinsic::sqrt:
1023   case Intrinsic::pow:
1024   case Intrinsic::powi:
1025   case Intrinsic::bswap:
1026   case Intrinsic::ctpop:
1027   case Intrinsic::ctlz:
1028   case Intrinsic::cttz:
1029   case Intrinsic::sadd_with_overflow:
1030   case Intrinsic::uadd_with_overflow:
1031   case Intrinsic::ssub_with_overflow:
1032   case Intrinsic::usub_with_overflow:
1033   case Intrinsic::smul_with_overflow:
1034   case Intrinsic::umul_with_overflow:
1035   case Intrinsic::convert_from_fp16:
1036   case Intrinsic::convert_to_fp16:
1037   case Intrinsic::x86_sse_cvtss2si:
1038   case Intrinsic::x86_sse_cvtss2si64:
1039   case Intrinsic::x86_sse_cvttss2si:
1040   case Intrinsic::x86_sse_cvttss2si64:
1041   case Intrinsic::x86_sse2_cvtsd2si:
1042   case Intrinsic::x86_sse2_cvtsd2si64:
1043   case Intrinsic::x86_sse2_cvttsd2si:
1044   case Intrinsic::x86_sse2_cvttsd2si64:
1045     return true;
1046   default:
1047     return false;
1048   case 0: break;
1049   }
1050
1051   if (!F->hasName()) return false;
1052   StringRef Name = F->getName();
1053   
1054   // In these cases, the check of the length is required.  We don't want to
1055   // return true for a name like "cos\0blah" which strcmp would return equal to
1056   // "cos", but has length 8.
1057   switch (Name[0]) {
1058   default: return false;
1059   case 'a':
1060     return Name == "acos" || Name == "asin" || 
1061       Name == "atan" || Name == "atan2";
1062   case 'c':
1063     return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1064   case 'e':
1065     return Name == "exp" || Name == "exp2";
1066   case 'f':
1067     return Name == "fabs" || Name == "fmod" || Name == "floor";
1068   case 'l':
1069     return Name == "log" || Name == "log10";
1070   case 'p':
1071     return Name == "pow";
1072   case 's':
1073     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1074       Name == "sinf" || Name == "sqrtf";
1075   case 't':
1076     return Name == "tan" || Name == "tanh";
1077   }
1078 }
1079
1080 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V, 
1081                                 Type *Ty) {
1082   sys::llvm_fenv_clearexcept();
1083   V = NativeFP(V);
1084   if (sys::llvm_fenv_testexcept()) {
1085     sys::llvm_fenv_clearexcept();
1086     return 0;
1087   }
1088   
1089   if (Ty->isFloatTy())
1090     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1091   if (Ty->isDoubleTy())
1092     return ConstantFP::get(Ty->getContext(), APFloat(V));
1093   llvm_unreachable("Can only constant fold float/double");
1094 }
1095
1096 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1097                                       double V, double W, Type *Ty) {
1098   sys::llvm_fenv_clearexcept();
1099   V = NativeFP(V, W);
1100   if (sys::llvm_fenv_testexcept()) {
1101     sys::llvm_fenv_clearexcept();
1102     return 0;
1103   }
1104   
1105   if (Ty->isFloatTy())
1106     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1107   if (Ty->isDoubleTy())
1108     return ConstantFP::get(Ty->getContext(), APFloat(V));
1109   llvm_unreachable("Can only constant fold float/double");
1110 }
1111
1112 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1113 /// conversion of a constant floating point. If roundTowardZero is false, the
1114 /// default IEEE rounding is used (toward nearest, ties to even). This matches
1115 /// the behavior of the non-truncating SSE instructions in the default rounding
1116 /// mode. The desired integer type Ty is used to select how many bits are
1117 /// available for the result. Returns null if the conversion cannot be
1118 /// performed, otherwise returns the Constant value resulting from the
1119 /// conversion.
1120 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1121                                           bool roundTowardZero, Type *Ty) {
1122   // All of these conversion intrinsics form an integer of at most 64bits.
1123   unsigned ResultWidth = cast<IntegerType>(Ty)->getBitWidth();
1124   assert(ResultWidth <= 64 &&
1125          "Can only constant fold conversions to 64 and 32 bit ints");
1126
1127   uint64_t UIntVal;
1128   bool isExact = false;
1129   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1130                                               : APFloat::rmNearestTiesToEven;
1131   APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1132                                                   /*isSigned=*/true, mode,
1133                                                   &isExact);
1134   if (status != APFloat::opOK && status != APFloat::opInexact)
1135     return 0;
1136   return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1137 }
1138
1139 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
1140 /// with the specified arguments, returning null if unsuccessful.
1141 Constant *
1142 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1143                        const TargetLibraryInfo *TLI) {
1144   if (!F->hasName()) return 0;
1145   StringRef Name = F->getName();
1146
1147   Type *Ty = F->getReturnType();
1148   if (Operands.size() == 1) {
1149     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1150       if (F->getIntrinsicID() == Intrinsic::convert_to_fp16) {
1151         APFloat Val(Op->getValueAPF());
1152
1153         bool lost = false;
1154         Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1155
1156         return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
1157       }
1158       if (!TLI)
1159         return 0;
1160
1161       if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1162         return 0;
1163
1164       /// We only fold functions with finite arguments. Folding NaN and inf is
1165       /// likely to be aborted with an exception anyway, and some host libms
1166       /// have known errors raising exceptions.
1167       if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1168         return 0;
1169
1170       /// Currently APFloat versions of these functions do not exist, so we use
1171       /// the host native double versions.  Float versions are not called
1172       /// directly but for all these it is true (float)(f((double)arg)) ==
1173       /// f(arg).  Long double not supported yet.
1174       double V = Ty->isFloatTy() ? (double)Op->getValueAPF().convertToFloat() :
1175                                      Op->getValueAPF().convertToDouble();
1176       switch (Name[0]) {
1177       case 'a':
1178         if (Name == "acos" && TLI->has(LibFunc::acos))
1179           return ConstantFoldFP(acos, V, Ty);
1180         else if (Name == "asin" && TLI->has(LibFunc::asin))
1181           return ConstantFoldFP(asin, V, Ty);
1182         else if (Name == "atan" && TLI->has(LibFunc::atan))
1183           return ConstantFoldFP(atan, V, Ty);
1184         break;
1185       case 'c':
1186         if (Name == "ceil" && TLI->has(LibFunc::ceil))
1187           return ConstantFoldFP(ceil, V, Ty);
1188         else if (Name == "cos" && TLI->has(LibFunc::cos))
1189           return ConstantFoldFP(cos, V, Ty);
1190         else if (Name == "cosh" && TLI->has(LibFunc::cosh))
1191           return ConstantFoldFP(cosh, V, Ty);
1192         else if (Name == "cosf" && TLI->has(LibFunc::cosf))
1193           return ConstantFoldFP(cos, V, Ty);
1194         break;
1195       case 'e':
1196         if (Name == "exp" && TLI->has(LibFunc::exp))
1197           return ConstantFoldFP(exp, V, Ty);
1198   
1199         if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
1200           // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1201           // C99 library.
1202           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1203         }
1204         break;
1205       case 'f':
1206         if (Name == "fabs" && TLI->has(LibFunc::fabs))
1207           return ConstantFoldFP(fabs, V, Ty);
1208         else if (Name == "floor" && TLI->has(LibFunc::floor))
1209           return ConstantFoldFP(floor, V, Ty);
1210         break;
1211       case 'l':
1212         if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
1213           return ConstantFoldFP(log, V, Ty);
1214         else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
1215           return ConstantFoldFP(log10, V, Ty);
1216         else if (F->getIntrinsicID() == Intrinsic::sqrt &&
1217                  (Ty->isFloatTy() || Ty->isDoubleTy())) {
1218           if (V >= -0.0)
1219             return ConstantFoldFP(sqrt, V, Ty);
1220           else // Undefined
1221             return Constant::getNullValue(Ty);
1222         }
1223         break;
1224       case 's':
1225         if (Name == "sin" && TLI->has(LibFunc::sin))
1226           return ConstantFoldFP(sin, V, Ty);
1227         else if (Name == "sinh" && TLI->has(LibFunc::sinh))
1228           return ConstantFoldFP(sinh, V, Ty);
1229         else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
1230           return ConstantFoldFP(sqrt, V, Ty);
1231         else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
1232           return ConstantFoldFP(sqrt, V, Ty);
1233         else if (Name == "sinf" && TLI->has(LibFunc::sinf))
1234           return ConstantFoldFP(sin, V, Ty);
1235         break;
1236       case 't':
1237         if (Name == "tan" && TLI->has(LibFunc::tan))
1238           return ConstantFoldFP(tan, V, Ty);
1239         else if (Name == "tanh" && TLI->has(LibFunc::tanh))
1240           return ConstantFoldFP(tanh, V, Ty);
1241         break;
1242       default:
1243         break;
1244       }
1245       return 0;
1246     }
1247
1248     if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1249       switch (F->getIntrinsicID()) {
1250       case Intrinsic::bswap:
1251         return ConstantInt::get(F->getContext(), Op->getValue().byteSwap());
1252       case Intrinsic::ctpop:
1253         return ConstantInt::get(Ty, Op->getValue().countPopulation());
1254       case Intrinsic::convert_from_fp16: {
1255         APFloat Val(Op->getValue());
1256
1257         bool lost = false;
1258         APFloat::opStatus status =
1259           Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1260
1261         // Conversion is always precise.
1262         (void)status;
1263         assert(status == APFloat::opOK && !lost &&
1264                "Precision lost during fp16 constfolding");
1265
1266         return ConstantFP::get(F->getContext(), Val);
1267       }
1268       default:
1269         return 0;
1270       }
1271     }
1272
1273     // Support ConstantVector in case we have an Undef in the top.
1274     if (isa<ConstantVector>(Operands[0]) || 
1275         isa<ConstantDataVector>(Operands[0])) {
1276       Constant *Op = cast<Constant>(Operands[0]);
1277       switch (F->getIntrinsicID()) {
1278       default: break;
1279       case Intrinsic::x86_sse_cvtss2si:
1280       case Intrinsic::x86_sse_cvtss2si64:
1281       case Intrinsic::x86_sse2_cvtsd2si:
1282       case Intrinsic::x86_sse2_cvtsd2si64:
1283         if (ConstantFP *FPOp =
1284               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1285           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1286                                           /*roundTowardZero=*/false, Ty);
1287       case Intrinsic::x86_sse_cvttss2si:
1288       case Intrinsic::x86_sse_cvttss2si64:
1289       case Intrinsic::x86_sse2_cvttsd2si:
1290       case Intrinsic::x86_sse2_cvttsd2si64:
1291         if (ConstantFP *FPOp =
1292               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1293           return ConstantFoldConvertToInt(FPOp->getValueAPF(), 
1294                                           /*roundTowardZero=*/true, Ty);
1295       }
1296     }
1297   
1298     if (isa<UndefValue>(Operands[0])) {
1299       if (F->getIntrinsicID() == Intrinsic::bswap)
1300         return Operands[0];
1301       return 0;
1302     }
1303
1304     return 0;
1305   }
1306
1307   if (Operands.size() == 2) {
1308     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1309       if (!Ty->isFloatTy() && !Ty->isDoubleTy())
1310         return 0;
1311       double Op1V = Ty->isFloatTy() ? 
1312                       (double)Op1->getValueAPF().convertToFloat() :
1313                       Op1->getValueAPF().convertToDouble();
1314       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1315         if (Op2->getType() != Op1->getType())
1316           return 0;
1317
1318         double Op2V = Ty->isFloatTy() ? 
1319                       (double)Op2->getValueAPF().convertToFloat():
1320                       Op2->getValueAPF().convertToDouble();
1321
1322         if (F->getIntrinsicID() == Intrinsic::pow) {
1323           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1324         }
1325         if (!TLI)
1326           return 0;
1327         if (Name == "pow" && TLI->has(LibFunc::pow))
1328           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1329         if (Name == "fmod" && TLI->has(LibFunc::fmod))
1330           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1331         if (Name == "atan2" && TLI->has(LibFunc::atan2))
1332           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1333       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1334         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isFloatTy())
1335           return ConstantFP::get(F->getContext(),
1336                                  APFloat((float)std::pow((float)Op1V,
1337                                                  (int)Op2C->getZExtValue())));
1338         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isDoubleTy())
1339           return ConstantFP::get(F->getContext(),
1340                                  APFloat((double)std::pow((double)Op1V,
1341                                                    (int)Op2C->getZExtValue())));
1342       }
1343       return 0;
1344     }
1345     
1346     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1347       if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1348         switch (F->getIntrinsicID()) {
1349         default: break;
1350         case Intrinsic::sadd_with_overflow:
1351         case Intrinsic::uadd_with_overflow:
1352         case Intrinsic::ssub_with_overflow:
1353         case Intrinsic::usub_with_overflow:
1354         case Intrinsic::smul_with_overflow:
1355         case Intrinsic::umul_with_overflow: {
1356           APInt Res;
1357           bool Overflow;
1358           switch (F->getIntrinsicID()) {
1359           default: assert(0 && "Invalid case");
1360           case Intrinsic::sadd_with_overflow:
1361             Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1362             break;
1363           case Intrinsic::uadd_with_overflow:
1364             Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1365             break;
1366           case Intrinsic::ssub_with_overflow:
1367             Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1368             break;
1369           case Intrinsic::usub_with_overflow:
1370             Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1371             break;
1372           case Intrinsic::smul_with_overflow:
1373             Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1374             break;
1375           case Intrinsic::umul_with_overflow:
1376             Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1377             break;
1378           }
1379           Constant *Ops[] = {
1380             ConstantInt::get(F->getContext(), Res),
1381             ConstantInt::get(Type::getInt1Ty(F->getContext()), Overflow)
1382           };
1383           return ConstantStruct::get(cast<StructType>(F->getReturnType()), Ops);
1384         }
1385         case Intrinsic::cttz:
1386           // FIXME: This should check for Op2 == 1, and become unreachable if
1387           // Op1 == 0.
1388           return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1389         case Intrinsic::ctlz:
1390           // FIXME: This should check for Op2 == 1, and become unreachable if
1391           // Op1 == 0.
1392           return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1393         }
1394       }
1395       
1396       return 0;
1397     }
1398     return 0;
1399   }
1400   return 0;
1401 }