OSDN Git Service

Formatting.
[android-x86/external-llvm.git] / lib / Analysis / ConstantFolding.cpp
1 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines routines for folding instructions into constants.
11 //
12 // Also, to supplement the basic IR ConstantExpr simplifications,
13 // this file defines some additional folding routines that can make use of
14 // DataLayout information. These functions cannot go in IR due to library
15 // dependency issues.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FEnv.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetLibraryInfo.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 /// DataLayout.  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 DataLayout &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 IR 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, IR 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, IR 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 IR to do the conversion now that #elts line up.
145     C = ConstantExpr::getBitCast(C, SrcIVTy);
146     // If IR 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                                        APInt &Offset, const DataLayout &TD) {
222   // Trivial case, constant is the global.
223   if ((GV = dyn_cast<GlobalValue>(C))) {
224     Offset.clearAllBits();
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 (GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
239     // If the base isn't a global+constant, we aren't either.
240     if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
241       return false;
242
243     // Otherwise, add any offset that our operands provide.
244     return GEP->accumulateConstantOffset(TD, Offset);
245   }
246
247   return false;
248 }
249
250 /// ReadDataFromGlobal - Recursive helper to read bits out of global.  C is the
251 /// constant being copied out of. ByteOffset is an offset into C.  CurPtr is the
252 /// pointer to copy results into and BytesLeft is the number of bytes left in
253 /// the CurPtr buffer.  TD is the target data.
254 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
255                                unsigned char *CurPtr, unsigned BytesLeft,
256                                const DataLayout &TD) {
257   assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
258          "Out of range access");
259
260   // If this element is zero or undefined, we can just return since *CurPtr is
261   // zero initialized.
262   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
263     return true;
264
265   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
266     if (CI->getBitWidth() > 64 ||
267         (CI->getBitWidth() & 7) != 0)
268       return false;
269
270     uint64_t Val = CI->getZExtValue();
271     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
272
273     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
274       int n = ByteOffset;
275       if (!TD.isLittleEndian())
276         n = IntBytes - n - 1;
277       CurPtr[i] = (unsigned char)(Val >> (n * 8));
278       ++ByteOffset;
279     }
280     return true;
281   }
282
283   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
284     if (CFP->getType()->isDoubleTy()) {
285       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
286       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
287     }
288     if (CFP->getType()->isFloatTy()){
289       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
290       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
291     }
292     if (CFP->getType()->isHalfTy()){
293       C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
294       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
295     }
296     return false;
297   }
298
299   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
300     const StructLayout *SL = TD.getStructLayout(CS->getType());
301     unsigned Index = SL->getElementContainingOffset(ByteOffset);
302     uint64_t CurEltOffset = SL->getElementOffset(Index);
303     ByteOffset -= CurEltOffset;
304
305     while (1) {
306       // If the element access is to the element itself and not to tail padding,
307       // read the bytes from the element.
308       uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
309
310       if (ByteOffset < EltSize &&
311           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
312                               BytesLeft, TD))
313         return false;
314
315       ++Index;
316
317       // Check to see if we read from the last struct element, if so we're done.
318       if (Index == CS->getType()->getNumElements())
319         return true;
320
321       // If we read all of the bytes we needed from this element we're done.
322       uint64_t NextEltOffset = SL->getElementOffset(Index);
323
324       if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
325         return true;
326
327       // Move to the next element of the struct.
328       CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
329       BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
330       ByteOffset = 0;
331       CurEltOffset = NextEltOffset;
332     }
333     // not reached.
334   }
335
336   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
337       isa<ConstantDataSequential>(C)) {
338     Type *EltTy = cast<SequentialType>(C->getType())->getElementType();
339     uint64_t EltSize = TD.getTypeAllocSize(EltTy);
340     uint64_t Index = ByteOffset / EltSize;
341     uint64_t Offset = ByteOffset - Index * EltSize;
342     uint64_t NumElts;
343     if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
344       NumElts = AT->getNumElements();
345     else
346       NumElts = cast<VectorType>(C->getType())->getNumElements();
347
348     for (; Index != NumElts; ++Index) {
349       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
350                               BytesLeft, TD))
351         return false;
352
353       uint64_t BytesWritten = EltSize - Offset;
354       assert(BytesWritten <= EltSize && "Not indexing into this element?");
355       if (BytesWritten >= BytesLeft)
356         return true;
357
358       Offset = 0;
359       BytesLeft -= BytesWritten;
360       CurPtr += BytesWritten;
361     }
362     return true;
363   }
364
365   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
366     if (CE->getOpcode() == Instruction::IntToPtr &&
367         CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getContext()))
368       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
369                                 BytesLeft, TD);
370   }
371
372   // Otherwise, unknown initializer type.
373   return false;
374 }
375
376 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
377                                                  const DataLayout &TD) {
378   Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
379   IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
380
381   // If this isn't an integer load we can't fold it directly.
382   if (!IntType) {
383     // If this is a float/double load, we can try folding it as an int32/64 load
384     // and then bitcast the result.  This can be useful for union cases.  Note
385     // that address spaces don't matter here since we're not going to result in
386     // an actual new load.
387     Type *MapTy;
388     if (LoadTy->isHalfTy())
389       MapTy = Type::getInt16PtrTy(C->getContext());
390     else if (LoadTy->isFloatTy())
391       MapTy = Type::getInt32PtrTy(C->getContext());
392     else if (LoadTy->isDoubleTy())
393       MapTy = Type::getInt64PtrTy(C->getContext());
394     else if (LoadTy->isVectorTy()) {
395       MapTy = IntegerType::get(C->getContext(),
396                                TD.getTypeAllocSizeInBits(LoadTy));
397       MapTy = PointerType::getUnqual(MapTy);
398     } else
399       return 0;
400
401     C = FoldBitCast(C, MapTy, TD);
402     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
403       return FoldBitCast(Res, LoadTy, TD);
404     return 0;
405   }
406
407   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
408   if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
409
410   GlobalValue *GVal;
411   APInt Offset(TD.getPointerSizeInBits(), 0);
412   if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
413     return 0;
414
415   GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
416   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
417       !GV->getInitializer()->getType()->isSized())
418     return 0;
419
420   // If we're loading off the beginning of the global, some bytes may be valid,
421   // but we don't try to handle this.
422   if (Offset.isNegative()) return 0;
423
424   // If we're not accessing anything in this constant, the result is undefined.
425   if (Offset.getZExtValue() >=
426       TD.getTypeAllocSize(GV->getInitializer()->getType()))
427     return UndefValue::get(IntType);
428
429   unsigned char RawBytes[32] = {0};
430   if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
431                           BytesLoaded, TD))
432     return 0;
433
434   APInt ResultVal = APInt(IntType->getBitWidth(), 0);
435   if (TD.isLittleEndian()) {
436     ResultVal = RawBytes[BytesLoaded - 1];
437     for (unsigned i = 1; i != BytesLoaded; ++i) {
438       ResultVal <<= 8;
439       ResultVal |= RawBytes[BytesLoaded-1-i];
440     }
441   } else {
442     ResultVal = RawBytes[0];
443     for (unsigned i = 1; i != BytesLoaded; ++i) {
444       ResultVal <<= 8;
445       ResultVal |= RawBytes[i];
446     }
447   }
448
449   return ConstantInt::get(IntType->getContext(), ResultVal);
450 }
451
452 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
453 /// produce if it is constant and determinable.  If this is not determinable,
454 /// return null.
455 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
456                                              const DataLayout *TD) {
457   // First, try the easy cases:
458   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
459     if (GV->isConstant() && GV->hasDefinitiveInitializer())
460       return GV->getInitializer();
461
462   // If the loaded value isn't a constant expr, we can't handle it.
463   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
464   if (!CE) return 0;
465
466   if (CE->getOpcode() == Instruction::GetElementPtr) {
467     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
468       if (GV->isConstant() && GV->hasDefinitiveInitializer())
469         if (Constant *V =
470              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
471           return V;
472   }
473
474   // Instead of loading constant c string, use corresponding integer value
475   // directly if string length is small enough.
476   StringRef Str;
477   if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
478     unsigned StrLen = Str.size();
479     Type *Ty = cast<PointerType>(CE->getType())->getElementType();
480     unsigned NumBits = Ty->getPrimitiveSizeInBits();
481     // Replace load with immediate integer if the result is an integer or fp
482     // value.
483     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
484         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
485       APInt StrVal(NumBits, 0);
486       APInt SingleChar(NumBits, 0);
487       if (TD->isLittleEndian()) {
488         for (signed i = StrLen-1; i >= 0; i--) {
489           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
490           StrVal = (StrVal << 8) | SingleChar;
491         }
492       } else {
493         for (unsigned i = 0; i < StrLen; i++) {
494           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
495           StrVal = (StrVal << 8) | SingleChar;
496         }
497         // Append NULL at the end.
498         SingleChar = 0;
499         StrVal = (StrVal << 8) | SingleChar;
500       }
501
502       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
503       if (Ty->isFloatingPointTy())
504         Res = ConstantExpr::getBitCast(Res, Ty);
505       return Res;
506     }
507   }
508
509   // If this load comes from anywhere in a constant global, and if the global
510   // is all undef or zero, we know what it loads.
511   if (GlobalVariable *GV =
512         dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
513     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
514       Type *ResTy = cast<PointerType>(C->getType())->getElementType();
515       if (GV->getInitializer()->isNullValue())
516         return Constant::getNullValue(ResTy);
517       if (isa<UndefValue>(GV->getInitializer()))
518         return UndefValue::get(ResTy);
519     }
520   }
521
522   // Try hard to fold loads from bitcasted strange and non-type-safe things.
523   if (TD)
524     return FoldReinterpretLoadFromConstPtr(CE, *TD);
525   return 0;
526 }
527
528 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
529   if (LI->isVolatile()) return 0;
530
531   if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
532     return ConstantFoldLoadFromConstPtr(C, TD);
533
534   return 0;
535 }
536
537 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
538 /// Attempt to symbolically evaluate the result of a binary operator merging
539 /// these together.  If target data info is available, it is provided as DL,
540 /// otherwise DL is null.
541 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
542                                            Constant *Op1, const DataLayout *DL){
543   // SROA
544
545   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
546   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
547   // bits.
548
549
550   if (Opc == Instruction::And && DL) {
551     unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType());
552     APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
553     APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
554     ComputeMaskedBits(Op0, KnownZero0, KnownOne0, DL);
555     ComputeMaskedBits(Op1, KnownZero1, KnownOne1, DL);
556     if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
557       // All the bits of Op0 that the 'and' could be masking are already zero.
558       return Op0;
559     }
560     if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
561       // All the bits of Op1 that the 'and' could be masking are already zero.
562       return Op1;
563     }
564
565     APInt KnownZero = KnownZero0 | KnownZero1;
566     APInt KnownOne = KnownOne0 & KnownOne1;
567     if ((KnownZero | KnownOne).isAllOnesValue()) {
568       return ConstantInt::get(Op0->getType(), KnownOne);
569     }
570   }
571
572   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
573   // constant.  This happens frequently when iterating over a global array.
574   if (Opc == Instruction::Sub && DL) {
575     GlobalValue *GV1, *GV2;
576     unsigned PtrSize = DL->getPointerSizeInBits();
577     unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
578     APInt Offs1(PtrSize, 0), Offs2(PtrSize, 0);
579
580     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
581       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
582           GV1 == GV2) {
583         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
584         // PtrToInt may change the bitwidth so we have convert to the right size
585         // first.
586         return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
587                                                 Offs2.zextOrTrunc(OpSize));
588       }
589   }
590
591   return 0;
592 }
593
594 /// CastGEPIndices - If array indices are not pointer-sized integers,
595 /// explicitly cast them so that they aren't implicitly casted by the
596 /// getelementptr.
597 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
598                                 Type *ResultTy, const DataLayout *TD,
599                                 const TargetLibraryInfo *TLI) {
600   if (!TD) return 0;
601   Type *IntPtrTy = TD->getIntPtrType(ResultTy->getContext());
602
603   bool Any = false;
604   SmallVector<Constant*, 32> NewIdxs;
605   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
606     if ((i == 1 ||
607          !isa<StructType>(GetElementPtrInst::getIndexedType(Ops[0]->getType(),
608                                                         Ops.slice(1, i-1)))) &&
609         Ops[i]->getType() != IntPtrTy) {
610       Any = true;
611       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
612                                                                       true,
613                                                                       IntPtrTy,
614                                                                       true),
615                                               Ops[i], IntPtrTy));
616     } else
617       NewIdxs.push_back(Ops[i]);
618   }
619   if (!Any) return 0;
620
621   Constant *C =
622     ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
623   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
624     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
625       C = Folded;
626   return C;
627 }
628
629 /// Strip the pointer casts, but preserve the address space information.
630 static Constant* StripPtrCastKeepAS(Constant* Ptr) {
631   assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
632   PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
633   Ptr = cast<Constant>(Ptr->stripPointerCasts());
634   PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
635
636   // Preserve the address space number of the pointer.
637   if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
638     NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
639       OldPtrTy->getAddressSpace());
640     Ptr = ConstantExpr::getBitCast(Ptr, NewPtrTy);
641   }
642   return Ptr;
643 }
644
645 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
646 /// constant expression, do so.
647 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
648                                          Type *ResultTy, const DataLayout *TD,
649                                          const TargetLibraryInfo *TLI) {
650   Constant *Ptr = Ops[0];
651   if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized() ||
652       !Ptr->getType()->isPointerTy())
653     return 0;
654
655   Type *IntPtrTy = TD->getIntPtrType(Ptr->getContext());
656
657   // If this is a constant expr gep that is effectively computing an
658   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
659   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
660     if (!isa<ConstantInt>(Ops[i])) {
661
662       // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
663       // "inttoptr (sub (ptrtoint Ptr), V)"
664       if (Ops.size() == 2 &&
665           cast<PointerType>(ResultTy)->getElementType()->isIntegerTy(8)) {
666         ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
667         assert((CE == 0 || CE->getType() == IntPtrTy) &&
668                "CastGEPIndices didn't canonicalize index types!");
669         if (CE && CE->getOpcode() == Instruction::Sub &&
670             CE->getOperand(0)->isNullValue()) {
671           Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
672           Res = ConstantExpr::getSub(Res, CE->getOperand(1));
673           Res = ConstantExpr::getIntToPtr(Res, ResultTy);
674           if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
675             Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
676           return Res;
677         }
678       }
679       return 0;
680     }
681
682   unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
683   APInt Offset =
684     APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
685                                          makeArrayRef((Value *const*)
686                                                         Ops.data() + 1,
687                                                       Ops.size() - 1)));
688   Ptr = StripPtrCastKeepAS(Ptr);
689
690   // If this is a GEP of a GEP, fold it all into a single GEP.
691   while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
692     SmallVector<Value *, 4> NestedOps(GEP->op_begin()+1, GEP->op_end());
693
694     // Do not try the incorporate the sub-GEP if some index is not a number.
695     bool AllConstantInt = true;
696     for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
697       if (!isa<ConstantInt>(NestedOps[i])) {
698         AllConstantInt = false;
699         break;
700       }
701     if (!AllConstantInt)
702       break;
703
704     Ptr = cast<Constant>(GEP->getOperand(0));
705     Offset += APInt(BitWidth,
706                     TD->getIndexedOffset(Ptr->getType(), NestedOps));
707     Ptr = StripPtrCastKeepAS(Ptr);
708   }
709
710   // If the base value for this address is a literal integer value, fold the
711   // getelementptr to the resulting integer value casted to the pointer type.
712   APInt BasePtr(BitWidth, 0);
713   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
714     if (CE->getOpcode() == Instruction::IntToPtr)
715       if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
716         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
717   if (Ptr->isNullValue() || BasePtr != 0) {
718     Constant *C = ConstantInt::get(Ptr->getContext(), Offset+BasePtr);
719     return ConstantExpr::getIntToPtr(C, ResultTy);
720   }
721
722   // Otherwise form a regular getelementptr. Recompute the indices so that
723   // we eliminate over-indexing of the notional static type array bounds.
724   // This makes it easy to determine if the getelementptr is "inbounds".
725   // Also, this helps GlobalOpt do SROA on GlobalVariables.
726   Type *Ty = Ptr->getType();
727   assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
728   SmallVector<Constant*, 32> NewIdxs;
729   do {
730     if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
731       if (ATy->isPointerTy()) {
732         // The only pointer indexing we'll do is on the first index of the GEP.
733         if (!NewIdxs.empty())
734           break;
735
736         // Only handle pointers to sized types, not pointers to functions.
737         if (!ATy->getElementType()->isSized())
738           return 0;
739       }
740
741       // Determine which element of the array the offset points into.
742       APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
743       IntegerType *IntPtrTy = TD->getIntPtrType(Ty->getContext());
744       if (ElemSize == 0)
745         // The element size is 0. This may be [0 x Ty]*, so just use a zero
746         // index for this level and proceed to the next level to see if it can
747         // accommodate the offset.
748         NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
749       else {
750         // The element size is non-zero divide the offset by the element
751         // size (rounding down), to compute the index at this level.
752         APInt NewIdx = Offset.udiv(ElemSize);
753         Offset -= NewIdx * ElemSize;
754         NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
755       }
756       Ty = ATy->getElementType();
757     } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
758       // If we end up with an offset that isn't valid for this struct type, we
759       // can't re-form this GEP in a regular form, so bail out. The pointer
760       // operand likely went through casts that are necessary to make the GEP
761       // sensible.
762       const StructLayout &SL = *TD->getStructLayout(STy);
763       if (Offset.uge(SL.getSizeInBytes()))
764         break;
765
766       // Determine which field of the struct the offset points into. The
767       // getZExtValue is fine as we've already ensured that the offset is
768       // within the range representable by the StructLayout API.
769       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
770       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
771                                          ElIdx));
772       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
773       Ty = STy->getTypeAtIndex(ElIdx);
774     } else {
775       // We've reached some non-indexable type.
776       break;
777     }
778   } while (Ty != cast<PointerType>(ResultTy)->getElementType());
779
780   // If we haven't used up the entire offset by descending the static
781   // type, then the offset is pointing into the middle of an indivisible
782   // member, so we can't simplify it.
783   if (Offset != 0)
784     return 0;
785
786   // Create a GEP.
787   Constant *C =
788     ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
789   assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
790          "Computed GetElementPtr has unexpected type!");
791
792   // If we ended up indexing a member with a type that doesn't match
793   // the type of what the original indices indexed, add a cast.
794   if (Ty != cast<PointerType>(ResultTy)->getElementType())
795     C = FoldBitCast(C, ResultTy, *TD);
796
797   return C;
798 }
799
800
801
802 //===----------------------------------------------------------------------===//
803 // Constant Folding public APIs
804 //===----------------------------------------------------------------------===//
805
806 /// ConstantFoldInstruction - Try to constant fold the specified instruction.
807 /// If successful, the constant result is returned, if not, null is returned.
808 /// Note that this fails if not all of the operands are constant.  Otherwise,
809 /// this function can only fail when attempting to fold instructions like loads
810 /// and stores, which have no constant expression form.
811 Constant *llvm::ConstantFoldInstruction(Instruction *I,
812                                         const DataLayout *TD,
813                                         const TargetLibraryInfo *TLI) {
814   // Handle PHI nodes quickly here...
815   if (PHINode *PN = dyn_cast<PHINode>(I)) {
816     Constant *CommonValue = 0;
817
818     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
819       Value *Incoming = PN->getIncomingValue(i);
820       // If the incoming value is undef then skip it.  Note that while we could
821       // skip the value if it is equal to the phi node itself we choose not to
822       // because that would break the rule that constant folding only applies if
823       // all operands are constants.
824       if (isa<UndefValue>(Incoming))
825         continue;
826       // If the incoming value is not a constant, then give up.
827       Constant *C = dyn_cast<Constant>(Incoming);
828       if (!C)
829         return 0;
830       // Fold the PHI's operands.
831       if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
832         C = ConstantFoldConstantExpression(NewC, TD, TLI);
833       // If the incoming value is a different constant to
834       // the one we saw previously, then give up.
835       if (CommonValue && C != CommonValue)
836         return 0;
837       CommonValue = C;
838     }
839
840
841     // If we reach here, all incoming values are the same constant or undef.
842     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
843   }
844
845   // Scan the operand list, checking to see if they are all constants, if so,
846   // hand off to ConstantFoldInstOperands.
847   SmallVector<Constant*, 8> Ops;
848   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
849     Constant *Op = dyn_cast<Constant>(*i);
850     if (!Op)
851       return 0;  // All operands not constant!
852
853     // Fold the Instruction's operands.
854     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
855       Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
856
857     Ops.push_back(Op);
858   }
859
860   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
861     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
862                                            TD, TLI);
863
864   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
865     return ConstantFoldLoadInst(LI, TD);
866
867   if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I))
868     return ConstantExpr::getInsertValue(
869                                 cast<Constant>(IVI->getAggregateOperand()),
870                                 cast<Constant>(IVI->getInsertedValueOperand()),
871                                 IVI->getIndices());
872
873   if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I))
874     return ConstantExpr::getExtractValue(
875                                     cast<Constant>(EVI->getAggregateOperand()),
876                                     EVI->getIndices());
877
878   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
879 }
880
881 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
882 /// using the specified DataLayout.  If successful, the constant result is
883 /// result is returned, if not, null is returned.
884 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
885                                                const DataLayout *TD,
886                                                const TargetLibraryInfo *TLI) {
887   SmallVector<Constant*, 8> Ops;
888   for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end();
889        i != e; ++i) {
890     Constant *NewC = cast<Constant>(*i);
891     // Recursively fold the ConstantExpr's operands.
892     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC))
893       NewC = ConstantFoldConstantExpression(NewCE, TD, TLI);
894     Ops.push_back(NewC);
895   }
896
897   if (CE->isCompare())
898     return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
899                                            TD, TLI);
900   return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
901 }
902
903 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
904 /// specified opcode and operands.  If successful, the constant result is
905 /// returned, if not, null is returned.  Note that this function can fail when
906 /// attempting to fold instructions like loads and stores, which have no
907 /// constant expression form.
908 ///
909 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
910 /// information, due to only being passed an opcode and operands. Constant
911 /// folding using this function strips this information.
912 ///
913 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
914                                          ArrayRef<Constant *> Ops,
915                                          const DataLayout *TD,
916                                          const TargetLibraryInfo *TLI) {
917   // Handle easy binops first.
918   if (Instruction::isBinaryOp(Opcode)) {
919     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
920       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
921         return C;
922
923     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
924   }
925
926   switch (Opcode) {
927   default: return 0;
928   case Instruction::ICmp:
929   case Instruction::FCmp: llvm_unreachable("Invalid for compares");
930   case Instruction::Call:
931     if (Function *F = dyn_cast<Function>(Ops.back()))
932       if (canConstantFoldCallTo(F))
933         return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
934     return 0;
935   case Instruction::PtrToInt:
936     // If the input is a inttoptr, eliminate the pair.  This requires knowing
937     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
938     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
939       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
940         Constant *Input = CE->getOperand(0);
941         unsigned InWidth = Input->getType()->getScalarSizeInBits();
942         if (TD->getPointerSizeInBits() < InWidth) {
943           Constant *Mask =
944             ConstantInt::get(CE->getContext(), APInt::getLowBitsSet(InWidth,
945                                                   TD->getPointerSizeInBits()));
946           Input = ConstantExpr::getAnd(Input, Mask);
947         }
948         // Do a zext or trunc to get to the dest size.
949         return ConstantExpr::getIntegerCast(Input, DestTy, false);
950       }
951     }
952     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
953   case Instruction::IntToPtr:
954     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
955     // the int size is >= the ptr size.  This requires knowing the width of a
956     // pointer, so it can't be done in ConstantExpr::getCast.
957     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
958       if (TD &&
959           TD->getPointerSizeInBits() <= CE->getType()->getScalarSizeInBits() &&
960           CE->getOpcode() == Instruction::PtrToInt)
961         return FoldBitCast(CE->getOperand(0), DestTy, *TD);
962
963     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
964   case Instruction::Trunc:
965   case Instruction::ZExt:
966   case Instruction::SExt:
967   case Instruction::FPTrunc:
968   case Instruction::FPExt:
969   case Instruction::UIToFP:
970   case Instruction::SIToFP:
971   case Instruction::FPToUI:
972   case Instruction::FPToSI:
973       return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
974   case Instruction::BitCast:
975     if (TD)
976       return FoldBitCast(Ops[0], DestTy, *TD);
977     return ConstantExpr::getBitCast(Ops[0], DestTy);
978   case Instruction::Select:
979     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
980   case Instruction::ExtractElement:
981     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
982   case Instruction::InsertElement:
983     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
984   case Instruction::ShuffleVector:
985     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
986   case Instruction::GetElementPtr:
987     if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
988       return C;
989     if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
990       return C;
991
992     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
993   }
994 }
995
996 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
997 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
998 /// returns a constant expression of the specified operands.
999 ///
1000 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
1001                                                 Constant *Ops0, Constant *Ops1,
1002                                                 const DataLayout *TD,
1003                                                 const TargetLibraryInfo *TLI) {
1004   // fold: icmp (inttoptr x), null         -> icmp x, 0
1005   // fold: icmp (ptrtoint x), 0            -> icmp x, null
1006   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
1007   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1008   //
1009   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
1010   // around to know if bit truncation is happening.
1011   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1012     if (TD && Ops1->isNullValue()) {
1013       Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
1014       if (CE0->getOpcode() == Instruction::IntToPtr) {
1015         // Convert the integer value to the right size to ensure we get the
1016         // proper extension or truncation.
1017         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1018                                                    IntPtrTy, false);
1019         Constant *Null = Constant::getNullValue(C->getType());
1020         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1021       }
1022
1023       // Only do this transformation if the int is intptrty in size, otherwise
1024       // there is a truncation or extension that we aren't modeling.
1025       if (CE0->getOpcode() == Instruction::PtrToInt &&
1026           CE0->getType() == IntPtrTy) {
1027         Constant *C = CE0->getOperand(0);
1028         Constant *Null = Constant::getNullValue(C->getType());
1029         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1030       }
1031     }
1032
1033     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
1034       if (TD && CE0->getOpcode() == CE1->getOpcode()) {
1035         Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
1036
1037         if (CE0->getOpcode() == Instruction::IntToPtr) {
1038           // Convert the integer value to the right size to ensure we get the
1039           // proper extension or truncation.
1040           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
1041                                                       IntPtrTy, false);
1042           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
1043                                                       IntPtrTy, false);
1044           return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
1045         }
1046
1047         // Only do this transformation if the int is intptrty in size, otherwise
1048         // there is a truncation or extension that we aren't modeling.
1049         if ((CE0->getOpcode() == Instruction::PtrToInt &&
1050              CE0->getType() == IntPtrTy &&
1051              CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()))
1052           return ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0),
1053                                                  CE1->getOperand(0), TD, TLI);
1054       }
1055     }
1056
1057     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1058     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1059     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1060         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
1061       Constant *LHS =
1062         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
1063                                         TD, TLI);
1064       Constant *RHS =
1065         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
1066                                         TD, TLI);
1067       unsigned OpC =
1068         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1069       Constant *Ops[] = { LHS, RHS };
1070       return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
1071     }
1072   }
1073
1074   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
1075 }
1076
1077
1078 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
1079 /// getelementptr constantexpr, return the constant value being addressed by the
1080 /// constant expression, or null if something is funny and we can't decide.
1081 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
1082                                                        ConstantExpr *CE) {
1083   if (!CE->getOperand(1)->isNullValue())
1084     return 0;  // Do not allow stepping over the value!
1085
1086   // Loop over all of the operands, tracking down which value we are
1087   // addressing.
1088   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1089     C = C->getAggregateElement(CE->getOperand(i));
1090     if (C == 0) return 0;
1091   }
1092   return C;
1093 }
1094
1095 /// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
1096 /// indices (with an *implied* zero pointer index that is not in the list),
1097 /// return the constant value being addressed by a virtual load, or null if
1098 /// something is funny and we can't decide.
1099 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1100                                                   ArrayRef<Constant*> Indices) {
1101   // Loop over all of the operands, tracking down which value we are
1102   // addressing.
1103   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
1104     C = C->getAggregateElement(Indices[i]);
1105     if (C == 0) return 0;
1106   }
1107   return C;
1108 }
1109
1110
1111 //===----------------------------------------------------------------------===//
1112 //  Constant Folding for Calls
1113 //
1114
1115 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
1116 /// the specified function.
1117 bool
1118 llvm::canConstantFoldCallTo(const Function *F) {
1119   switch (F->getIntrinsicID()) {
1120   case Intrinsic::fabs:
1121   case Intrinsic::log:
1122   case Intrinsic::log2:
1123   case Intrinsic::log10:
1124   case Intrinsic::exp:
1125   case Intrinsic::exp2:
1126   case Intrinsic::floor:
1127   case Intrinsic::sqrt:
1128   case Intrinsic::pow:
1129   case Intrinsic::powi:
1130   case Intrinsic::bswap:
1131   case Intrinsic::ctpop:
1132   case Intrinsic::ctlz:
1133   case Intrinsic::cttz:
1134   case Intrinsic::sadd_with_overflow:
1135   case Intrinsic::uadd_with_overflow:
1136   case Intrinsic::ssub_with_overflow:
1137   case Intrinsic::usub_with_overflow:
1138   case Intrinsic::smul_with_overflow:
1139   case Intrinsic::umul_with_overflow:
1140   case Intrinsic::convert_from_fp16:
1141   case Intrinsic::convert_to_fp16:
1142   case Intrinsic::x86_sse_cvtss2si:
1143   case Intrinsic::x86_sse_cvtss2si64:
1144   case Intrinsic::x86_sse_cvttss2si:
1145   case Intrinsic::x86_sse_cvttss2si64:
1146   case Intrinsic::x86_sse2_cvtsd2si:
1147   case Intrinsic::x86_sse2_cvtsd2si64:
1148   case Intrinsic::x86_sse2_cvttsd2si:
1149   case Intrinsic::x86_sse2_cvttsd2si64:
1150     return true;
1151   default:
1152     return false;
1153   case 0: break;
1154   }
1155
1156   if (!F->hasName()) return false;
1157   StringRef Name = F->getName();
1158
1159   // In these cases, the check of the length is required.  We don't want to
1160   // return true for a name like "cos\0blah" which strcmp would return equal to
1161   // "cos", but has length 8.
1162   switch (Name[0]) {
1163   default: return false;
1164   case 'a':
1165     return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
1166   case 'c':
1167     return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
1168   case 'e':
1169     return Name == "exp" || Name == "exp2";
1170   case 'f':
1171     return Name == "fabs" || Name == "fmod" || Name == "floor";
1172   case 'l':
1173     return Name == "log" || Name == "log10";
1174   case 'p':
1175     return Name == "pow";
1176   case 's':
1177     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1178       Name == "sinf" || Name == "sqrtf";
1179   case 't':
1180     return Name == "tan" || Name == "tanh";
1181   }
1182 }
1183
1184 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1185                                 Type *Ty) {
1186   sys::llvm_fenv_clearexcept();
1187   V = NativeFP(V);
1188   if (sys::llvm_fenv_testexcept()) {
1189     sys::llvm_fenv_clearexcept();
1190     return 0;
1191   }
1192
1193   if (Ty->isHalfTy()) {
1194     APFloat APF(V);
1195     bool unused;
1196     APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1197     return ConstantFP::get(Ty->getContext(), APF);
1198   }
1199   if (Ty->isFloatTy())
1200     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1201   if (Ty->isDoubleTy())
1202     return ConstantFP::get(Ty->getContext(), APFloat(V));
1203   llvm_unreachable("Can only constant fold half/float/double");
1204 }
1205
1206 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
1207                                       double V, double W, Type *Ty) {
1208   sys::llvm_fenv_clearexcept();
1209   V = NativeFP(V, W);
1210   if (sys::llvm_fenv_testexcept()) {
1211     sys::llvm_fenv_clearexcept();
1212     return 0;
1213   }
1214
1215   if (Ty->isHalfTy()) {
1216     APFloat APF(V);
1217     bool unused;
1218     APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1219     return ConstantFP::get(Ty->getContext(), APF);
1220   }
1221   if (Ty->isFloatTy())
1222     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
1223   if (Ty->isDoubleTy())
1224     return ConstantFP::get(Ty->getContext(), APFloat(V));
1225   llvm_unreachable("Can only constant fold half/float/double");
1226 }
1227
1228 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1229 /// conversion of a constant floating point. If roundTowardZero is false, the
1230 /// default IEEE rounding is used (toward nearest, ties to even). This matches
1231 /// the behavior of the non-truncating SSE instructions in the default rounding
1232 /// mode. The desired integer type Ty is used to select how many bits are
1233 /// available for the result. Returns null if the conversion cannot be
1234 /// performed, otherwise returns the Constant value resulting from the
1235 /// conversion.
1236 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1237                                           bool roundTowardZero, Type *Ty) {
1238   // All of these conversion intrinsics form an integer of at most 64bits.
1239   unsigned ResultWidth = cast<IntegerType>(Ty)->getBitWidth();
1240   assert(ResultWidth <= 64 &&
1241          "Can only constant fold conversions to 64 and 32 bit ints");
1242
1243   uint64_t UIntVal;
1244   bool isExact = false;
1245   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1246                                               : APFloat::rmNearestTiesToEven;
1247   APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1248                                                   /*isSigned=*/true, mode,
1249                                                   &isExact);
1250   if (status != APFloat::opOK && status != APFloat::opInexact)
1251     return 0;
1252   return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1253 }
1254
1255 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
1256 /// with the specified arguments, returning null if unsuccessful.
1257 Constant *
1258 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1259                        const TargetLibraryInfo *TLI) {
1260   if (!F->hasName()) return 0;
1261   StringRef Name = F->getName();
1262
1263   Type *Ty = F->getReturnType();
1264   if (Operands.size() == 1) {
1265     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
1266       if (F->getIntrinsicID() == Intrinsic::convert_to_fp16) {
1267         APFloat Val(Op->getValueAPF());
1268
1269         bool lost = false;
1270         Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1271
1272         return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
1273       }
1274       if (!TLI)
1275         return 0;
1276
1277       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1278         return 0;
1279
1280       /// We only fold functions with finite arguments. Folding NaN and inf is
1281       /// likely to be aborted with an exception anyway, and some host libms
1282       /// have known errors raising exceptions.
1283       if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1284         return 0;
1285
1286       /// Currently APFloat versions of these functions do not exist, so we use
1287       /// the host native double versions.  Float versions are not called
1288       /// directly but for all these it is true (float)(f((double)arg)) ==
1289       /// f(arg).  Long double not supported yet.
1290       double V;
1291       if (Ty->isFloatTy())
1292         V = Op->getValueAPF().convertToFloat();
1293       else if (Ty->isDoubleTy())
1294         V = Op->getValueAPF().convertToDouble();
1295       else {
1296         bool unused;
1297         APFloat APF = Op->getValueAPF();
1298         APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1299         V = APF.convertToDouble();
1300       }
1301
1302       switch (F->getIntrinsicID()) {
1303         default: break;
1304         case Intrinsic::fabs:
1305           return ConstantFoldFP(fabs, V, Ty);
1306 #if HAVE_LOG2
1307         case Intrinsic::log2:
1308           return ConstantFoldFP(log2, V, Ty);
1309 #endif
1310 #if HAVE_LOG
1311         case Intrinsic::log:
1312           return ConstantFoldFP(log, V, Ty);
1313 #endif
1314 #if HAVE_LOG10
1315         case Intrinsic::log10:
1316           return ConstantFoldFP(log10, V, Ty);
1317 #endif
1318 #if HAVE_EXP
1319         case Intrinsic::exp:
1320           return ConstantFoldFP(exp, V, Ty);
1321 #endif
1322 #if HAVE_EXP2
1323         case Intrinsic::exp2:
1324           return ConstantFoldFP(exp2, V, Ty);
1325 #endif
1326         case Intrinsic::floor:
1327           return ConstantFoldFP(floor, V, Ty);
1328       }
1329
1330       switch (Name[0]) {
1331       case 'a':
1332         if (Name == "acos" && TLI->has(LibFunc::acos))
1333           return ConstantFoldFP(acos, V, Ty);
1334         else if (Name == "asin" && TLI->has(LibFunc::asin))
1335           return ConstantFoldFP(asin, V, Ty);
1336         else if (Name == "atan" && TLI->has(LibFunc::atan))
1337           return ConstantFoldFP(atan, V, Ty);
1338         break;
1339       case 'c':
1340         if (Name == "ceil" && TLI->has(LibFunc::ceil))
1341           return ConstantFoldFP(ceil, V, Ty);
1342         else if (Name == "cos" && TLI->has(LibFunc::cos))
1343           return ConstantFoldFP(cos, V, Ty);
1344         else if (Name == "cosh" && TLI->has(LibFunc::cosh))
1345           return ConstantFoldFP(cosh, V, Ty);
1346         else if (Name == "cosf" && TLI->has(LibFunc::cosf))
1347           return ConstantFoldFP(cos, V, Ty);
1348         break;
1349       case 'e':
1350         if (Name == "exp" && TLI->has(LibFunc::exp))
1351           return ConstantFoldFP(exp, V, Ty);
1352
1353         if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
1354           // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1355           // C99 library.
1356           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1357         }
1358         break;
1359       case 'f':
1360         if (Name == "fabs" && TLI->has(LibFunc::fabs))
1361           return ConstantFoldFP(fabs, V, Ty);
1362         else if (Name == "floor" && TLI->has(LibFunc::floor))
1363           return ConstantFoldFP(floor, V, Ty);
1364         break;
1365       case 'l':
1366         if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
1367           return ConstantFoldFP(log, V, Ty);
1368         else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
1369           return ConstantFoldFP(log10, V, Ty);
1370         else if (F->getIntrinsicID() == Intrinsic::sqrt &&
1371                  (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
1372           if (V >= -0.0)
1373             return ConstantFoldFP(sqrt, V, Ty);
1374           else // Undefined
1375             return Constant::getNullValue(Ty);
1376         }
1377         break;
1378       case 's':
1379         if (Name == "sin" && TLI->has(LibFunc::sin))
1380           return ConstantFoldFP(sin, V, Ty);
1381         else if (Name == "sinh" && TLI->has(LibFunc::sinh))
1382           return ConstantFoldFP(sinh, V, Ty);
1383         else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
1384           return ConstantFoldFP(sqrt, V, Ty);
1385         else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
1386           return ConstantFoldFP(sqrt, V, Ty);
1387         else if (Name == "sinf" && TLI->has(LibFunc::sinf))
1388           return ConstantFoldFP(sin, V, Ty);
1389         break;
1390       case 't':
1391         if (Name == "tan" && TLI->has(LibFunc::tan))
1392           return ConstantFoldFP(tan, V, Ty);
1393         else if (Name == "tanh" && TLI->has(LibFunc::tanh))
1394           return ConstantFoldFP(tanh, V, Ty);
1395         break;
1396       default:
1397         break;
1398       }
1399       return 0;
1400     }
1401
1402     if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
1403       switch (F->getIntrinsicID()) {
1404       case Intrinsic::bswap:
1405         return ConstantInt::get(F->getContext(), Op->getValue().byteSwap());
1406       case Intrinsic::ctpop:
1407         return ConstantInt::get(Ty, Op->getValue().countPopulation());
1408       case Intrinsic::convert_from_fp16: {
1409         APFloat Val(APFloat::IEEEhalf, Op->getValue());
1410
1411         bool lost = false;
1412         APFloat::opStatus status =
1413           Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1414
1415         // Conversion is always precise.
1416         (void)status;
1417         assert(status == APFloat::opOK && !lost &&
1418                "Precision lost during fp16 constfolding");
1419
1420         return ConstantFP::get(F->getContext(), Val);
1421       }
1422       default:
1423         return 0;
1424       }
1425     }
1426
1427     // Support ConstantVector in case we have an Undef in the top.
1428     if (isa<ConstantVector>(Operands[0]) ||
1429         isa<ConstantDataVector>(Operands[0])) {
1430       Constant *Op = cast<Constant>(Operands[0]);
1431       switch (F->getIntrinsicID()) {
1432       default: break;
1433       case Intrinsic::x86_sse_cvtss2si:
1434       case Intrinsic::x86_sse_cvtss2si64:
1435       case Intrinsic::x86_sse2_cvtsd2si:
1436       case Intrinsic::x86_sse2_cvtsd2si64:
1437         if (ConstantFP *FPOp =
1438               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1439           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1440                                           /*roundTowardZero=*/false, Ty);
1441       case Intrinsic::x86_sse_cvttss2si:
1442       case Intrinsic::x86_sse_cvttss2si64:
1443       case Intrinsic::x86_sse2_cvttsd2si:
1444       case Intrinsic::x86_sse2_cvttsd2si64:
1445         if (ConstantFP *FPOp =
1446               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1447           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1448                                           /*roundTowardZero=*/true, Ty);
1449       }
1450     }
1451
1452     if (isa<UndefValue>(Operands[0])) {
1453       if (F->getIntrinsicID() == Intrinsic::bswap)
1454         return Operands[0];
1455       return 0;
1456     }
1457
1458     return 0;
1459   }
1460
1461   if (Operands.size() == 2) {
1462     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1463       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
1464         return 0;
1465       double Op1V;
1466       if (Ty->isFloatTy())
1467         Op1V = Op1->getValueAPF().convertToFloat();
1468       else if (Ty->isDoubleTy())
1469         Op1V = Op1->getValueAPF().convertToDouble();
1470       else {
1471         bool unused;
1472         APFloat APF = Op1->getValueAPF();
1473         APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1474         Op1V = APF.convertToDouble();
1475       }
1476
1477       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1478         if (Op2->getType() != Op1->getType())
1479           return 0;
1480
1481         double Op2V;
1482         if (Ty->isFloatTy())
1483           Op2V = Op2->getValueAPF().convertToFloat();
1484         else if (Ty->isDoubleTy())
1485           Op2V = Op2->getValueAPF().convertToDouble();
1486         else {
1487           bool unused;
1488           APFloat APF = Op2->getValueAPF();
1489           APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1490           Op2V = APF.convertToDouble();
1491         }
1492
1493         if (F->getIntrinsicID() == Intrinsic::pow) {
1494           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1495         }
1496         if (!TLI)
1497           return 0;
1498         if (Name == "pow" && TLI->has(LibFunc::pow))
1499           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1500         if (Name == "fmod" && TLI->has(LibFunc::fmod))
1501           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
1502         if (Name == "atan2" && TLI->has(LibFunc::atan2))
1503           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
1504       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
1505         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isHalfTy())
1506           return ConstantFP::get(F->getContext(),
1507                                  APFloat((float)std::pow((float)Op1V,
1508                                                  (int)Op2C->getZExtValue())));
1509         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isFloatTy())
1510           return ConstantFP::get(F->getContext(),
1511                                  APFloat((float)std::pow((float)Op1V,
1512                                                  (int)Op2C->getZExtValue())));
1513         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isDoubleTy())
1514           return ConstantFP::get(F->getContext(),
1515                                  APFloat((double)std::pow((double)Op1V,
1516                                                    (int)Op2C->getZExtValue())));
1517       }
1518       return 0;
1519     }
1520
1521     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1522       if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1523         switch (F->getIntrinsicID()) {
1524         default: break;
1525         case Intrinsic::sadd_with_overflow:
1526         case Intrinsic::uadd_with_overflow:
1527         case Intrinsic::ssub_with_overflow:
1528         case Intrinsic::usub_with_overflow:
1529         case Intrinsic::smul_with_overflow:
1530         case Intrinsic::umul_with_overflow: {
1531           APInt Res;
1532           bool Overflow;
1533           switch (F->getIntrinsicID()) {
1534           default: llvm_unreachable("Invalid case");
1535           case Intrinsic::sadd_with_overflow:
1536             Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1537             break;
1538           case Intrinsic::uadd_with_overflow:
1539             Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1540             break;
1541           case Intrinsic::ssub_with_overflow:
1542             Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1543             break;
1544           case Intrinsic::usub_with_overflow:
1545             Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1546             break;
1547           case Intrinsic::smul_with_overflow:
1548             Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1549             break;
1550           case Intrinsic::umul_with_overflow:
1551             Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1552             break;
1553           }
1554           Constant *Ops[] = {
1555             ConstantInt::get(F->getContext(), Res),
1556             ConstantInt::get(Type::getInt1Ty(F->getContext()), Overflow)
1557           };
1558           return ConstantStruct::get(cast<StructType>(F->getReturnType()), Ops);
1559         }
1560         case Intrinsic::cttz:
1561           if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1562             return UndefValue::get(Ty);
1563           return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1564         case Intrinsic::ctlz:
1565           if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1566             return UndefValue::get(Ty);
1567           return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
1568         }
1569       }
1570
1571       return 0;
1572     }
1573     return 0;
1574   }
1575   return 0;
1576 }