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