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