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