LLVM API Documentation

ConstantFolding.cpp
Go to the documentation of this file.
00001 //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines routines for folding instructions into constants.
00011 //
00012 // Also, to supplement the basic IR ConstantExpr simplifications,
00013 // this file defines some additional folding routines that can make use of
00014 // DataLayout information. These functions cannot go in IR due to library
00015 // dependency issues.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/Analysis/ConstantFolding.h"
00020 #include "llvm/ADT/SmallPtrSet.h"
00021 #include "llvm/ADT/SmallVector.h"
00022 #include "llvm/ADT/StringMap.h"
00023 #include "llvm/Analysis/ValueTracking.h"
00024 #include "llvm/IR/Constants.h"
00025 #include "llvm/IR/DataLayout.h"
00026 #include "llvm/IR/DerivedTypes.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/IR/GlobalVariable.h"
00029 #include "llvm/IR/Instructions.h"
00030 #include "llvm/IR/Intrinsics.h"
00031 #include "llvm/IR/Operator.h"
00032 #include "llvm/Support/ErrorHandling.h"
00033 #include "llvm/Support/FEnv.h"
00034 #include "llvm/Support/GetElementPtrTypeIterator.h"
00035 #include "llvm/Support/MathExtras.h"
00036 #include "llvm/Target/TargetLibraryInfo.h"
00037 #include <cerrno>
00038 #include <cmath>
00039 using namespace llvm;
00040 
00041 //===----------------------------------------------------------------------===//
00042 // Constant Folding internal helper functions
00043 //===----------------------------------------------------------------------===//
00044 
00045 /// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
00046 /// DataLayout.  This always returns a non-null constant, but it may be a
00047 /// ConstantExpr if unfoldable.
00048 static Constant *FoldBitCast(Constant *C, Type *DestTy,
00049                              const DataLayout &TD) {
00050   // Catch the obvious splat cases.
00051   if (C->isNullValue() && !DestTy->isX86_MMXTy())
00052     return Constant::getNullValue(DestTy);
00053   if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
00054     return Constant::getAllOnesValue(DestTy);
00055 
00056   // Handle a vector->integer cast.
00057   if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
00058     VectorType *VTy = dyn_cast<VectorType>(C->getType());
00059     if (VTy == 0)
00060       return ConstantExpr::getBitCast(C, DestTy);
00061 
00062     unsigned NumSrcElts = VTy->getNumElements();
00063     Type *SrcEltTy = VTy->getElementType();
00064 
00065     // If the vector is a vector of floating point, convert it to vector of int
00066     // to simplify things.
00067     if (SrcEltTy->isFloatingPointTy()) {
00068       unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
00069       Type *SrcIVTy =
00070         VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
00071       // Ask IR to do the conversion now that #elts line up.
00072       C = ConstantExpr::getBitCast(C, SrcIVTy);
00073     }
00074 
00075     ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
00076     if (CDV == 0)
00077       return ConstantExpr::getBitCast(C, DestTy);
00078 
00079     // Now that we know that the input value is a vector of integers, just shift
00080     // and insert them into our result.
00081     unsigned BitShift = TD.getTypeAllocSizeInBits(SrcEltTy);
00082     APInt Result(IT->getBitWidth(), 0);
00083     for (unsigned i = 0; i != NumSrcElts; ++i) {
00084       Result <<= BitShift;
00085       if (TD.isLittleEndian())
00086         Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
00087       else
00088         Result |= CDV->getElementAsInteger(i);
00089     }
00090 
00091     return ConstantInt::get(IT, Result);
00092   }
00093 
00094   // The code below only handles casts to vectors currently.
00095   VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
00096   if (DestVTy == 0)
00097     return ConstantExpr::getBitCast(C, DestTy);
00098 
00099   // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
00100   // vector so the code below can handle it uniformly.
00101   if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
00102     Constant *Ops = C; // don't take the address of C!
00103     return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
00104   }
00105 
00106   // If this is a bitcast from constant vector -> vector, fold it.
00107   if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
00108     return ConstantExpr::getBitCast(C, DestTy);
00109 
00110   // If the element types match, IR can fold it.
00111   unsigned NumDstElt = DestVTy->getNumElements();
00112   unsigned NumSrcElt = C->getType()->getVectorNumElements();
00113   if (NumDstElt == NumSrcElt)
00114     return ConstantExpr::getBitCast(C, DestTy);
00115 
00116   Type *SrcEltTy = C->getType()->getVectorElementType();
00117   Type *DstEltTy = DestVTy->getElementType();
00118 
00119   // Otherwise, we're changing the number of elements in a vector, which
00120   // requires endianness information to do the right thing.  For example,
00121   //    bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
00122   // folds to (little endian):
00123   //    <4 x i32> <i32 0, i32 0, i32 1, i32 0>
00124   // and to (big endian):
00125   //    <4 x i32> <i32 0, i32 0, i32 0, i32 1>
00126 
00127   // First thing is first.  We only want to think about integer here, so if
00128   // we have something in FP form, recast it as integer.
00129   if (DstEltTy->isFloatingPointTy()) {
00130     // Fold to an vector of integers with same size as our FP type.
00131     unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
00132     Type *DestIVTy =
00133       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
00134     // Recursively handle this integer conversion, if possible.
00135     C = FoldBitCast(C, DestIVTy, TD);
00136 
00137     // Finally, IR can handle this now that #elts line up.
00138     return ConstantExpr::getBitCast(C, DestTy);
00139   }
00140 
00141   // Okay, we know the destination is integer, if the input is FP, convert
00142   // it to integer first.
00143   if (SrcEltTy->isFloatingPointTy()) {
00144     unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
00145     Type *SrcIVTy =
00146       VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
00147     // Ask IR to do the conversion now that #elts line up.
00148     C = ConstantExpr::getBitCast(C, SrcIVTy);
00149     // If IR wasn't able to fold it, bail out.
00150     if (!isa<ConstantVector>(C) &&  // FIXME: Remove ConstantVector.
00151         !isa<ConstantDataVector>(C))
00152       return C;
00153   }
00154 
00155   // Now we know that the input and output vectors are both integer vectors
00156   // of the same size, and that their #elements is not the same.  Do the
00157   // conversion here, which depends on whether the input or output has
00158   // more elements.
00159   bool isLittleEndian = TD.isLittleEndian();
00160 
00161   SmallVector<Constant*, 32> Result;
00162   if (NumDstElt < NumSrcElt) {
00163     // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
00164     Constant *Zero = Constant::getNullValue(DstEltTy);
00165     unsigned Ratio = NumSrcElt/NumDstElt;
00166     unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
00167     unsigned SrcElt = 0;
00168     for (unsigned i = 0; i != NumDstElt; ++i) {
00169       // Build each element of the result.
00170       Constant *Elt = Zero;
00171       unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
00172       for (unsigned j = 0; j != Ratio; ++j) {
00173         Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
00174         if (!Src)  // Reject constantexpr elements.
00175           return ConstantExpr::getBitCast(C, DestTy);
00176 
00177         // Zero extend the element to the right size.
00178         Src = ConstantExpr::getZExt(Src, Elt->getType());
00179 
00180         // Shift it to the right place, depending on endianness.
00181         Src = ConstantExpr::getShl(Src,
00182                                    ConstantInt::get(Src->getType(), ShiftAmt));
00183         ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
00184 
00185         // Mix it in.
00186         Elt = ConstantExpr::getOr(Elt, Src);
00187       }
00188       Result.push_back(Elt);
00189     }
00190     return ConstantVector::get(Result);
00191   }
00192 
00193   // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
00194   unsigned Ratio = NumDstElt/NumSrcElt;
00195   unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
00196 
00197   // Loop over each source value, expanding into multiple results.
00198   for (unsigned i = 0; i != NumSrcElt; ++i) {
00199     Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
00200     if (!Src)  // Reject constantexpr elements.
00201       return ConstantExpr::getBitCast(C, DestTy);
00202 
00203     unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
00204     for (unsigned j = 0; j != Ratio; ++j) {
00205       // Shift the piece of the value into the right place, depending on
00206       // endianness.
00207       Constant *Elt = ConstantExpr::getLShr(Src,
00208                                   ConstantInt::get(Src->getType(), ShiftAmt));
00209       ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
00210 
00211       // Truncate and remember this piece.
00212       Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
00213     }
00214   }
00215 
00216   return ConstantVector::get(Result);
00217 }
00218 
00219 
00220 /// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
00221 /// from a global, return the global and the constant.  Because of
00222 /// constantexprs, this function is recursive.
00223 static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
00224                                        APInt &Offset, const DataLayout &TD) {
00225   // Trivial case, constant is the global.
00226   if ((GV = dyn_cast<GlobalValue>(C))) {
00227     Offset.clearAllBits();
00228     return true;
00229   }
00230 
00231   // Otherwise, if this isn't a constant expr, bail out.
00232   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
00233   if (!CE) return false;
00234 
00235   // Look through ptr->int and ptr->ptr casts.
00236   if (CE->getOpcode() == Instruction::PtrToInt ||
00237       CE->getOpcode() == Instruction::BitCast)
00238     return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
00239 
00240   // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
00241   if (GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
00242     // If the base isn't a global+constant, we aren't either.
00243     if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
00244       return false;
00245 
00246     // Otherwise, add any offset that our operands provide.
00247     return GEP->accumulateConstantOffset(TD, Offset);
00248   }
00249 
00250   return false;
00251 }
00252 
00253 /// ReadDataFromGlobal - Recursive helper to read bits out of global.  C is the
00254 /// constant being copied out of. ByteOffset is an offset into C.  CurPtr is the
00255 /// pointer to copy results into and BytesLeft is the number of bytes left in
00256 /// the CurPtr buffer.  TD is the target data.
00257 static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
00258                                unsigned char *CurPtr, unsigned BytesLeft,
00259                                const DataLayout &TD) {
00260   assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
00261          "Out of range access");
00262 
00263   // If this element is zero or undefined, we can just return since *CurPtr is
00264   // zero initialized.
00265   if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
00266     return true;
00267 
00268   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
00269     if (CI->getBitWidth() > 64 ||
00270         (CI->getBitWidth() & 7) != 0)
00271       return false;
00272 
00273     uint64_t Val = CI->getZExtValue();
00274     unsigned IntBytes = unsigned(CI->getBitWidth()/8);
00275 
00276     for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
00277       int n = ByteOffset;
00278       if (!TD.isLittleEndian())
00279         n = IntBytes - n - 1;
00280       CurPtr[i] = (unsigned char)(Val >> (n * 8));
00281       ++ByteOffset;
00282     }
00283     return true;
00284   }
00285 
00286   if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
00287     if (CFP->getType()->isDoubleTy()) {
00288       C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
00289       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
00290     }
00291     if (CFP->getType()->isFloatTy()){
00292       C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
00293       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
00294     }
00295     if (CFP->getType()->isHalfTy()){
00296       C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
00297       return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
00298     }
00299     return false;
00300   }
00301 
00302   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
00303     const StructLayout *SL = TD.getStructLayout(CS->getType());
00304     unsigned Index = SL->getElementContainingOffset(ByteOffset);
00305     uint64_t CurEltOffset = SL->getElementOffset(Index);
00306     ByteOffset -= CurEltOffset;
00307 
00308     while (1) {
00309       // If the element access is to the element itself and not to tail padding,
00310       // read the bytes from the element.
00311       uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
00312 
00313       if (ByteOffset < EltSize &&
00314           !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
00315                               BytesLeft, TD))
00316         return false;
00317 
00318       ++Index;
00319 
00320       // Check to see if we read from the last struct element, if so we're done.
00321       if (Index == CS->getType()->getNumElements())
00322         return true;
00323 
00324       // If we read all of the bytes we needed from this element we're done.
00325       uint64_t NextEltOffset = SL->getElementOffset(Index);
00326 
00327       if (BytesLeft <= NextEltOffset-CurEltOffset-ByteOffset)
00328         return true;
00329 
00330       // Move to the next element of the struct.
00331       CurPtr += NextEltOffset-CurEltOffset-ByteOffset;
00332       BytesLeft -= NextEltOffset-CurEltOffset-ByteOffset;
00333       ByteOffset = 0;
00334       CurEltOffset = NextEltOffset;
00335     }
00336     // not reached.
00337   }
00338 
00339   if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
00340       isa<ConstantDataSequential>(C)) {
00341     Type *EltTy = cast<SequentialType>(C->getType())->getElementType();
00342     uint64_t EltSize = TD.getTypeAllocSize(EltTy);
00343     uint64_t Index = ByteOffset / EltSize;
00344     uint64_t Offset = ByteOffset - Index * EltSize;
00345     uint64_t NumElts;
00346     if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
00347       NumElts = AT->getNumElements();
00348     else
00349       NumElts = cast<VectorType>(C->getType())->getNumElements();
00350 
00351     for (; Index != NumElts; ++Index) {
00352       if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
00353                               BytesLeft, TD))
00354         return false;
00355 
00356       uint64_t BytesWritten = EltSize - Offset;
00357       assert(BytesWritten <= EltSize && "Not indexing into this element?");
00358       if (BytesWritten >= BytesLeft)
00359         return true;
00360 
00361       Offset = 0;
00362       BytesLeft -= BytesWritten;
00363       CurPtr += BytesWritten;
00364     }
00365     return true;
00366   }
00367 
00368   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00369     if (CE->getOpcode() == Instruction::IntToPtr &&
00370         CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getContext()))
00371       return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
00372                                 BytesLeft, TD);
00373   }
00374 
00375   // Otherwise, unknown initializer type.
00376   return false;
00377 }
00378 
00379 static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
00380                                                  const DataLayout &TD) {
00381   Type *LoadTy = cast<PointerType>(C->getType())->getElementType();
00382   IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
00383 
00384   // If this isn't an integer load we can't fold it directly.
00385   if (!IntType) {
00386     // If this is a float/double load, we can try folding it as an int32/64 load
00387     // and then bitcast the result.  This can be useful for union cases.  Note
00388     // that address spaces don't matter here since we're not going to result in
00389     // an actual new load.
00390     Type *MapTy;
00391     if (LoadTy->isHalfTy())
00392       MapTy = Type::getInt16PtrTy(C->getContext());
00393     else if (LoadTy->isFloatTy())
00394       MapTy = Type::getInt32PtrTy(C->getContext());
00395     else if (LoadTy->isDoubleTy())
00396       MapTy = Type::getInt64PtrTy(C->getContext());
00397     else if (LoadTy->isVectorTy()) {
00398       MapTy = IntegerType::get(C->getContext(),
00399                                TD.getTypeAllocSizeInBits(LoadTy));
00400       MapTy = PointerType::getUnqual(MapTy);
00401     } else
00402       return 0;
00403 
00404     C = FoldBitCast(C, MapTy, TD);
00405     if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
00406       return FoldBitCast(Res, LoadTy, TD);
00407     return 0;
00408   }
00409 
00410   unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
00411   if (BytesLoaded > 32 || BytesLoaded == 0) return 0;
00412 
00413   GlobalValue *GVal;
00414   APInt Offset(TD.getPointerSizeInBits(), 0);
00415   if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
00416     return 0;
00417 
00418   GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
00419   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
00420       !GV->getInitializer()->getType()->isSized())
00421     return 0;
00422 
00423   // If we're loading off the beginning of the global, some bytes may be valid,
00424   // but we don't try to handle this.
00425   if (Offset.isNegative()) return 0;
00426 
00427   // If we're not accessing anything in this constant, the result is undefined.
00428   if (Offset.getZExtValue() >=
00429       TD.getTypeAllocSize(GV->getInitializer()->getType()))
00430     return UndefValue::get(IntType);
00431 
00432   unsigned char RawBytes[32] = {0};
00433   if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
00434                           BytesLoaded, TD))
00435     return 0;
00436 
00437   APInt ResultVal = APInt(IntType->getBitWidth(), 0);
00438   if (TD.isLittleEndian()) {
00439     ResultVal = RawBytes[BytesLoaded - 1];
00440     for (unsigned i = 1; i != BytesLoaded; ++i) {
00441       ResultVal <<= 8;
00442       ResultVal |= RawBytes[BytesLoaded-1-i];
00443     }
00444   } else {
00445     ResultVal = RawBytes[0];
00446     for (unsigned i = 1; i != BytesLoaded; ++i) {
00447       ResultVal <<= 8;
00448       ResultVal |= RawBytes[i];
00449     }
00450   }
00451 
00452   return ConstantInt::get(IntType->getContext(), ResultVal);
00453 }
00454 
00455 /// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
00456 /// produce if it is constant and determinable.  If this is not determinable,
00457 /// return null.
00458 Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
00459                                              const DataLayout *TD) {
00460   // First, try the easy cases:
00461   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
00462     if (GV->isConstant() && GV->hasDefinitiveInitializer())
00463       return GV->getInitializer();
00464 
00465   // If the loaded value isn't a constant expr, we can't handle it.
00466   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
00467   if (!CE) return 0;
00468 
00469   if (CE->getOpcode() == Instruction::GetElementPtr) {
00470     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
00471       if (GV->isConstant() && GV->hasDefinitiveInitializer())
00472         if (Constant *V =
00473              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
00474           return V;
00475   }
00476 
00477   // Instead of loading constant c string, use corresponding integer value
00478   // directly if string length is small enough.
00479   StringRef Str;
00480   if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
00481     unsigned StrLen = Str.size();
00482     Type *Ty = cast<PointerType>(CE->getType())->getElementType();
00483     unsigned NumBits = Ty->getPrimitiveSizeInBits();
00484     // Replace load with immediate integer if the result is an integer or fp
00485     // value.
00486     if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
00487         (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
00488       APInt StrVal(NumBits, 0);
00489       APInt SingleChar(NumBits, 0);
00490       if (TD->isLittleEndian()) {
00491         for (signed i = StrLen-1; i >= 0; i--) {
00492           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
00493           StrVal = (StrVal << 8) | SingleChar;
00494         }
00495       } else {
00496         for (unsigned i = 0; i < StrLen; i++) {
00497           SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
00498           StrVal = (StrVal << 8) | SingleChar;
00499         }
00500         // Append NULL at the end.
00501         SingleChar = 0;
00502         StrVal = (StrVal << 8) | SingleChar;
00503       }
00504 
00505       Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
00506       if (Ty->isFloatingPointTy())
00507         Res = ConstantExpr::getBitCast(Res, Ty);
00508       return Res;
00509     }
00510   }
00511 
00512   // If this load comes from anywhere in a constant global, and if the global
00513   // is all undef or zero, we know what it loads.
00514   if (GlobalVariable *GV =
00515         dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
00516     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
00517       Type *ResTy = cast<PointerType>(C->getType())->getElementType();
00518       if (GV->getInitializer()->isNullValue())
00519         return Constant::getNullValue(ResTy);
00520       if (isa<UndefValue>(GV->getInitializer()))
00521         return UndefValue::get(ResTy);
00522     }
00523   }
00524 
00525   // Try hard to fold loads from bitcasted strange and non-type-safe things.
00526   if (TD)
00527     return FoldReinterpretLoadFromConstPtr(CE, *TD);
00528   return 0;
00529 }
00530 
00531 static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
00532   if (LI->isVolatile()) return 0;
00533 
00534   if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
00535     return ConstantFoldLoadFromConstPtr(C, TD);
00536 
00537   return 0;
00538 }
00539 
00540 /// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
00541 /// Attempt to symbolically evaluate the result of a binary operator merging
00542 /// these together.  If target data info is available, it is provided as DL,
00543 /// otherwise DL is null.
00544 static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
00545                                            Constant *Op1, const DataLayout *DL){
00546   // SROA
00547 
00548   // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
00549   // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
00550   // bits.
00551 
00552 
00553   if (Opc == Instruction::And && DL) {
00554     unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
00555     APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
00556     APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
00557     ComputeMaskedBits(Op0, KnownZero0, KnownOne0, DL);
00558     ComputeMaskedBits(Op1, KnownZero1, KnownOne1, DL);
00559     if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
00560       // All the bits of Op0 that the 'and' could be masking are already zero.
00561       return Op0;
00562     }
00563     if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
00564       // All the bits of Op1 that the 'and' could be masking are already zero.
00565       return Op1;
00566     }
00567 
00568     APInt KnownZero = KnownZero0 | KnownZero1;
00569     APInt KnownOne = KnownOne0 & KnownOne1;
00570     if ((KnownZero | KnownOne).isAllOnesValue()) {
00571       return ConstantInt::get(Op0->getType(), KnownOne);
00572     }
00573   }
00574 
00575   // If the constant expr is something like &A[123] - &A[4].f, fold this into a
00576   // constant.  This happens frequently when iterating over a global array.
00577   if (Opc == Instruction::Sub && DL) {
00578     GlobalValue *GV1, *GV2;
00579     unsigned PtrSize = DL->getPointerSizeInBits();
00580     unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
00581     APInt Offs1(PtrSize, 0), Offs2(PtrSize, 0);
00582 
00583     if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
00584       if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
00585           GV1 == GV2) {
00586         // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
00587         // PtrToInt may change the bitwidth so we have convert to the right size
00588         // first.
00589         return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
00590                                                 Offs2.zextOrTrunc(OpSize));
00591       }
00592   }
00593 
00594   return 0;
00595 }
00596 
00597 /// CastGEPIndices - If array indices are not pointer-sized integers,
00598 /// explicitly cast them so that they aren't implicitly casted by the
00599 /// getelementptr.
00600 static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
00601                                 Type *ResultTy, const DataLayout *TD,
00602                                 const TargetLibraryInfo *TLI) {
00603   if (!TD) return 0;
00604   Type *IntPtrTy = TD->getIntPtrType(ResultTy->getContext());
00605 
00606   bool Any = false;
00607   SmallVector<Constant*, 32> NewIdxs;
00608   for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
00609     if ((i == 1 ||
00610          !isa<StructType>(GetElementPtrInst::getIndexedType(Ops[0]->getType(),
00611                                                         Ops.slice(1, i-1)))) &&
00612         Ops[i]->getType() != IntPtrTy) {
00613       Any = true;
00614       NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
00615                                                                       true,
00616                                                                       IntPtrTy,
00617                                                                       true),
00618                                               Ops[i], IntPtrTy));
00619     } else
00620       NewIdxs.push_back(Ops[i]);
00621   }
00622   if (!Any) return 0;
00623 
00624   Constant *C =
00625     ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
00626   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
00627     if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
00628       C = Folded;
00629   return C;
00630 }
00631 
00632 /// Strip the pointer casts, but preserve the address space information.
00633 static Constant* StripPtrCastKeepAS(Constant* Ptr) {
00634   assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
00635   PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
00636   Ptr = cast<Constant>(Ptr->stripPointerCasts());
00637   PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
00638 
00639   // Preserve the address space number of the pointer.
00640   if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
00641     NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
00642       OldPtrTy->getAddressSpace());
00643     Ptr = ConstantExpr::getBitCast(Ptr, NewPtrTy);
00644   }
00645   return Ptr;
00646 }
00647 
00648 /// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
00649 /// constant expression, do so.
00650 static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
00651                                          Type *ResultTy, const DataLayout *TD,
00652                                          const TargetLibraryInfo *TLI) {
00653   Constant *Ptr = Ops[0];
00654   if (!TD || !cast<PointerType>(Ptr->getType())->getElementType()->isSized() ||
00655       !Ptr->getType()->isPointerTy())
00656     return 0;
00657 
00658   Type *IntPtrTy = TD->getIntPtrType(Ptr->getContext());
00659 
00660   // If this is a constant expr gep that is effectively computing an
00661   // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
00662   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
00663     if (!isa<ConstantInt>(Ops[i])) {
00664 
00665       // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
00666       // "inttoptr (sub (ptrtoint Ptr), V)"
00667       if (Ops.size() == 2 &&
00668           cast<PointerType>(ResultTy)->getElementType()->isIntegerTy(8)) {
00669         ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
00670         assert((CE == 0 || CE->getType() == IntPtrTy) &&
00671                "CastGEPIndices didn't canonicalize index types!");
00672         if (CE && CE->getOpcode() == Instruction::Sub &&
00673             CE->getOperand(0)->isNullValue()) {
00674           Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
00675           Res = ConstantExpr::getSub(Res, CE->getOperand(1));
00676           Res = ConstantExpr::getIntToPtr(Res, ResultTy);
00677           if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
00678             Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
00679           return Res;
00680         }
00681       }
00682       return 0;
00683     }
00684 
00685   unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
00686   APInt Offset =
00687     APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
00688                                          makeArrayRef((Value *const*)
00689                                                         Ops.data() + 1,
00690                                                       Ops.size() - 1)));
00691   Ptr = StripPtrCastKeepAS(Ptr);
00692 
00693   // If this is a GEP of a GEP, fold it all into a single GEP.
00694   while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
00695     SmallVector<Value *, 4> NestedOps(GEP->op_begin()+1, GEP->op_end());
00696 
00697     // Do not try the incorporate the sub-GEP if some index is not a number.
00698     bool AllConstantInt = true;
00699     for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
00700       if (!isa<ConstantInt>(NestedOps[i])) {
00701         AllConstantInt = false;
00702         break;
00703       }
00704     if (!AllConstantInt)
00705       break;
00706 
00707     Ptr = cast<Constant>(GEP->getOperand(0));
00708     Offset += APInt(BitWidth,
00709                     TD->getIndexedOffset(Ptr->getType(), NestedOps));
00710     Ptr = StripPtrCastKeepAS(Ptr);
00711   }
00712 
00713   // If the base value for this address is a literal integer value, fold the
00714   // getelementptr to the resulting integer value casted to the pointer type.
00715   APInt BasePtr(BitWidth, 0);
00716   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
00717     if (CE->getOpcode() == Instruction::IntToPtr)
00718       if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
00719         BasePtr = Base->getValue().zextOrTrunc(BitWidth);
00720   if (Ptr->isNullValue() || BasePtr != 0) {
00721     Constant *C = ConstantInt::get(Ptr->getContext(), Offset+BasePtr);
00722     return ConstantExpr::getIntToPtr(C, ResultTy);
00723   }
00724 
00725   // Otherwise form a regular getelementptr. Recompute the indices so that
00726   // we eliminate over-indexing of the notional static type array bounds.
00727   // This makes it easy to determine if the getelementptr is "inbounds".
00728   // Also, this helps GlobalOpt do SROA on GlobalVariables.
00729   Type *Ty = Ptr->getType();
00730   assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
00731   SmallVector<Constant*, 32> NewIdxs;
00732   do {
00733     if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
00734       if (ATy->isPointerTy()) {
00735         // The only pointer indexing we'll do is on the first index of the GEP.
00736         if (!NewIdxs.empty())
00737           break;
00738 
00739         // Only handle pointers to sized types, not pointers to functions.
00740         if (!ATy->getElementType()->isSized())
00741           return 0;
00742       }
00743 
00744       // Determine which element of the array the offset points into.
00745       APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
00746       IntegerType *IntPtrTy = TD->getIntPtrType(Ty->getContext());
00747       if (ElemSize == 0)
00748         // The element size is 0. This may be [0 x Ty]*, so just use a zero
00749         // index for this level and proceed to the next level to see if it can
00750         // accommodate the offset.
00751         NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
00752       else {
00753         // The element size is non-zero divide the offset by the element
00754         // size (rounding down), to compute the index at this level.
00755         APInt NewIdx = Offset.udiv(ElemSize);
00756         Offset -= NewIdx * ElemSize;
00757         NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
00758       }
00759       Ty = ATy->getElementType();
00760     } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
00761       // If we end up with an offset that isn't valid for this struct type, we
00762       // can't re-form this GEP in a regular form, so bail out. The pointer
00763       // operand likely went through casts that are necessary to make the GEP
00764       // sensible.
00765       const StructLayout &SL = *TD->getStructLayout(STy);
00766       if (Offset.uge(SL.getSizeInBytes()))
00767         break;
00768 
00769       // Determine which field of the struct the offset points into. The
00770       // getZExtValue is fine as we've already ensured that the offset is
00771       // within the range representable by the StructLayout API.
00772       unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
00773       NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
00774                                          ElIdx));
00775       Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
00776       Ty = STy->getTypeAtIndex(ElIdx);
00777     } else {
00778       // We've reached some non-indexable type.
00779       break;
00780     }
00781   } while (Ty != cast<PointerType>(ResultTy)->getElementType());
00782 
00783   // If we haven't used up the entire offset by descending the static
00784   // type, then the offset is pointing into the middle of an indivisible
00785   // member, so we can't simplify it.
00786   if (Offset != 0)
00787     return 0;
00788 
00789   // Create a GEP.
00790   Constant *C =
00791     ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
00792   assert(cast<PointerType>(C->getType())->getElementType() == Ty &&
00793          "Computed GetElementPtr has unexpected type!");
00794 
00795   // If we ended up indexing a member with a type that doesn't match
00796   // the type of what the original indices indexed, add a cast.
00797   if (Ty != cast<PointerType>(ResultTy)->getElementType())
00798     C = FoldBitCast(C, ResultTy, *TD);
00799 
00800   return C;
00801 }
00802 
00803 
00804 
00805 //===----------------------------------------------------------------------===//
00806 // Constant Folding public APIs
00807 //===----------------------------------------------------------------------===//
00808 
00809 /// ConstantFoldInstruction - Try to constant fold the specified instruction.
00810 /// If successful, the constant result is returned, if not, null is returned.
00811 /// Note that this fails if not all of the operands are constant.  Otherwise,
00812 /// this function can only fail when attempting to fold instructions like loads
00813 /// and stores, which have no constant expression form.
00814 Constant *llvm::ConstantFoldInstruction(Instruction *I,
00815                                         const DataLayout *TD,
00816                                         const TargetLibraryInfo *TLI) {
00817   // Handle PHI nodes quickly here...
00818   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00819     Constant *CommonValue = 0;
00820 
00821     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00822       Value *Incoming = PN->getIncomingValue(i);
00823       // If the incoming value is undef then skip it.  Note that while we could
00824       // skip the value if it is equal to the phi node itself we choose not to
00825       // because that would break the rule that constant folding only applies if
00826       // all operands are constants.
00827       if (isa<UndefValue>(Incoming))
00828         continue;
00829       // If the incoming value is not a constant, then give up.
00830       Constant *C = dyn_cast<Constant>(Incoming);
00831       if (!C)
00832         return 0;
00833       // Fold the PHI's operands.
00834       if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
00835         C = ConstantFoldConstantExpression(NewC, TD, TLI);
00836       // If the incoming value is a different constant to
00837       // the one we saw previously, then give up.
00838       if (CommonValue && C != CommonValue)
00839         return 0;
00840       CommonValue = C;
00841     }
00842 
00843 
00844     // If we reach here, all incoming values are the same constant or undef.
00845     return CommonValue ? CommonValue : UndefValue::get(PN->getType());
00846   }
00847 
00848   // Scan the operand list, checking to see if they are all constants, if so,
00849   // hand off to ConstantFoldInstOperands.
00850   SmallVector<Constant*, 8> Ops;
00851   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
00852     Constant *Op = dyn_cast<Constant>(*i);
00853     if (!Op)
00854       return 0;  // All operands not constant!
00855 
00856     // Fold the Instruction's operands.
00857     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
00858       Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
00859 
00860     Ops.push_back(Op);
00861   }
00862 
00863   if (const CmpInst *CI = dyn_cast<CmpInst>(I))
00864     return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
00865                                            TD, TLI);
00866 
00867   if (const LoadInst *LI = dyn_cast<LoadInst>(I))
00868     return ConstantFoldLoadInst(LI, TD);
00869 
00870   if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I))
00871     return ConstantExpr::getInsertValue(
00872                                 cast<Constant>(IVI->getAggregateOperand()),
00873                                 cast<Constant>(IVI->getInsertedValueOperand()),
00874                                 IVI->getIndices());
00875 
00876   if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I))
00877     return ConstantExpr::getExtractValue(
00878                                     cast<Constant>(EVI->getAggregateOperand()),
00879                                     EVI->getIndices());
00880 
00881   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
00882 }
00883 
00884 static Constant *
00885 ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout *TD,
00886                                    const TargetLibraryInfo *TLI,
00887                                    SmallPtrSet<ConstantExpr *, 4> &FoldedOps) {
00888   SmallVector<Constant *, 8> Ops;
00889   for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
00890        ++i) {
00891     Constant *NewC = cast<Constant>(*i);
00892     // Recursively fold the ConstantExpr's operands. If we have already folded
00893     // a ConstantExpr, we don't have to process it again.
00894     if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
00895       if (FoldedOps.insert(NewCE))
00896         NewC = ConstantFoldConstantExpressionImpl(NewCE, TD, TLI, FoldedOps);
00897     }
00898     Ops.push_back(NewC);
00899   }
00900 
00901   if (CE->isCompare())
00902     return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
00903                                            TD, TLI);
00904   return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
00905 }
00906 
00907 /// ConstantFoldConstantExpression - Attempt to fold the constant expression
00908 /// using the specified DataLayout.  If successful, the constant result is
00909 /// result is returned, if not, null is returned.
00910 Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
00911                                                const DataLayout *TD,
00912                                                const TargetLibraryInfo *TLI) {
00913   SmallPtrSet<ConstantExpr *, 4> FoldedOps;
00914   return ConstantFoldConstantExpressionImpl(CE, TD, TLI, FoldedOps);
00915 }
00916 
00917 /// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
00918 /// specified opcode and operands.  If successful, the constant result is
00919 /// returned, if not, null is returned.  Note that this function can fail when
00920 /// attempting to fold instructions like loads and stores, which have no
00921 /// constant expression form.
00922 ///
00923 /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
00924 /// information, due to only being passed an opcode and operands. Constant
00925 /// folding using this function strips this information.
00926 ///
00927 Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
00928                                          ArrayRef<Constant *> Ops,
00929                                          const DataLayout *TD,
00930                                          const TargetLibraryInfo *TLI) {
00931   // Handle easy binops first.
00932   if (Instruction::isBinaryOp(Opcode)) {
00933     if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
00934       if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
00935         return C;
00936 
00937     return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
00938   }
00939 
00940   switch (Opcode) {
00941   default: return 0;
00942   case Instruction::ICmp:
00943   case Instruction::FCmp: llvm_unreachable("Invalid for compares");
00944   case Instruction::Call:
00945     if (Function *F = dyn_cast<Function>(Ops.back()))
00946       if (canConstantFoldCallTo(F))
00947         return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
00948     return 0;
00949   case Instruction::PtrToInt:
00950     // If the input is a inttoptr, eliminate the pair.  This requires knowing
00951     // the width of a pointer, so it can't be done in ConstantExpr::getCast.
00952     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
00953       if (TD && CE->getOpcode() == Instruction::IntToPtr) {
00954         Constant *Input = CE->getOperand(0);
00955         unsigned InWidth = Input->getType()->getScalarSizeInBits();
00956         if (TD->getPointerSizeInBits() < InWidth) {
00957           Constant *Mask =
00958             ConstantInt::get(CE->getContext(), APInt::getLowBitsSet(InWidth,
00959                                                   TD->getPointerSizeInBits()));
00960           Input = ConstantExpr::getAnd(Input, Mask);
00961         }
00962         // Do a zext or trunc to get to the dest size.
00963         return ConstantExpr::getIntegerCast(Input, DestTy, false);
00964       }
00965     }
00966     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
00967   case Instruction::IntToPtr:
00968     // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
00969     // the int size is >= the ptr size.  This requires knowing the width of a
00970     // pointer, so it can't be done in ConstantExpr::getCast.
00971     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0]))
00972       if (TD &&
00973           TD->getPointerSizeInBits() <= CE->getType()->getScalarSizeInBits() &&
00974           CE->getOpcode() == Instruction::PtrToInt)
00975         return FoldBitCast(CE->getOperand(0), DestTy, *TD);
00976 
00977     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
00978   case Instruction::Trunc:
00979   case Instruction::ZExt:
00980   case Instruction::SExt:
00981   case Instruction::FPTrunc:
00982   case Instruction::FPExt:
00983   case Instruction::UIToFP:
00984   case Instruction::SIToFP:
00985   case Instruction::FPToUI:
00986   case Instruction::FPToSI:
00987       return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
00988   case Instruction::BitCast:
00989     if (TD)
00990       return FoldBitCast(Ops[0], DestTy, *TD);
00991     return ConstantExpr::getBitCast(Ops[0], DestTy);
00992   case Instruction::Select:
00993     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
00994   case Instruction::ExtractElement:
00995     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
00996   case Instruction::InsertElement:
00997     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
00998   case Instruction::ShuffleVector:
00999     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
01000   case Instruction::GetElementPtr:
01001     if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
01002       return C;
01003     if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
01004       return C;
01005 
01006     return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
01007   }
01008 }
01009 
01010 /// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
01011 /// instruction (icmp/fcmp) with the specified operands.  If it fails, it
01012 /// returns a constant expression of the specified operands.
01013 ///
01014 Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
01015                                                 Constant *Ops0, Constant *Ops1,
01016                                                 const DataLayout *TD,
01017                                                 const TargetLibraryInfo *TLI) {
01018   // fold: icmp (inttoptr x), null         -> icmp x, 0
01019   // fold: icmp (ptrtoint x), 0            -> icmp x, null
01020   // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
01021   // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
01022   //
01023   // ConstantExpr::getCompare cannot do this, because it doesn't have TD
01024   // around to know if bit truncation is happening.
01025   if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
01026     if (TD && Ops1->isNullValue()) {
01027       Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
01028       if (CE0->getOpcode() == Instruction::IntToPtr) {
01029         // Convert the integer value to the right size to ensure we get the
01030         // proper extension or truncation.
01031         Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
01032                                                    IntPtrTy, false);
01033         Constant *Null = Constant::getNullValue(C->getType());
01034         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
01035       }
01036 
01037       // Only do this transformation if the int is intptrty in size, otherwise
01038       // there is a truncation or extension that we aren't modeling.
01039       if (CE0->getOpcode() == Instruction::PtrToInt &&
01040           CE0->getType() == IntPtrTy) {
01041         Constant *C = CE0->getOperand(0);
01042         Constant *Null = Constant::getNullValue(C->getType());
01043         return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
01044       }
01045     }
01046 
01047     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
01048       if (TD && CE0->getOpcode() == CE1->getOpcode()) {
01049         Type *IntPtrTy = TD->getIntPtrType(CE0->getContext());
01050 
01051         if (CE0->getOpcode() == Instruction::IntToPtr) {
01052           // Convert the integer value to the right size to ensure we get the
01053           // proper extension or truncation.
01054           Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
01055                                                       IntPtrTy, false);
01056           Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
01057                                                       IntPtrTy, false);
01058           return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
01059         }
01060 
01061         // Only do this transformation if the int is intptrty in size, otherwise
01062         // there is a truncation or extension that we aren't modeling.
01063         if ((CE0->getOpcode() == Instruction::PtrToInt &&
01064              CE0->getType() == IntPtrTy &&
01065              CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()))
01066           return ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0),
01067                                                  CE1->getOperand(0), TD, TLI);
01068       }
01069     }
01070 
01071     // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
01072     // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
01073     if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
01074         CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
01075       Constant *LHS =
01076         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
01077                                         TD, TLI);
01078       Constant *RHS =
01079         ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
01080                                         TD, TLI);
01081       unsigned OpC =
01082         Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
01083       Constant *Ops[] = { LHS, RHS };
01084       return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
01085     }
01086   }
01087 
01088   return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
01089 }
01090 
01091 
01092 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
01093 /// getelementptr constantexpr, return the constant value being addressed by the
01094 /// constant expression, or null if something is funny and we can't decide.
01095 Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
01096                                                        ConstantExpr *CE) {
01097   if (!CE->getOperand(1)->isNullValue())
01098     return 0;  // Do not allow stepping over the value!
01099 
01100   // Loop over all of the operands, tracking down which value we are
01101   // addressing.
01102   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
01103     C = C->getAggregateElement(CE->getOperand(i));
01104     if (C == 0) return 0;
01105   }
01106   return C;
01107 }
01108 
01109 /// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
01110 /// indices (with an *implied* zero pointer index that is not in the list),
01111 /// return the constant value being addressed by a virtual load, or null if
01112 /// something is funny and we can't decide.
01113 Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
01114                                                   ArrayRef<Constant*> Indices) {
01115   // Loop over all of the operands, tracking down which value we are
01116   // addressing.
01117   for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
01118     C = C->getAggregateElement(Indices[i]);
01119     if (C == 0) return 0;
01120   }
01121   return C;
01122 }
01123 
01124 
01125 //===----------------------------------------------------------------------===//
01126 //  Constant Folding for Calls
01127 //
01128 
01129 /// canConstantFoldCallTo - Return true if its even possible to fold a call to
01130 /// the specified function.
01131 bool
01132 llvm::canConstantFoldCallTo(const Function *F) {
01133   switch (F->getIntrinsicID()) {
01134   case Intrinsic::fabs:
01135   case Intrinsic::log:
01136   case Intrinsic::log2:
01137   case Intrinsic::log10:
01138   case Intrinsic::exp:
01139   case Intrinsic::exp2:
01140   case Intrinsic::floor:
01141   case Intrinsic::sqrt:
01142   case Intrinsic::pow:
01143   case Intrinsic::powi:
01144   case Intrinsic::bswap:
01145   case Intrinsic::ctpop:
01146   case Intrinsic::ctlz:
01147   case Intrinsic::cttz:
01148   case Intrinsic::sadd_with_overflow:
01149   case Intrinsic::uadd_with_overflow:
01150   case Intrinsic::ssub_with_overflow:
01151   case Intrinsic::usub_with_overflow:
01152   case Intrinsic::smul_with_overflow:
01153   case Intrinsic::umul_with_overflow:
01154   case Intrinsic::convert_from_fp16:
01155   case Intrinsic::convert_to_fp16:
01156   case Intrinsic::x86_sse_cvtss2si:
01157   case Intrinsic::x86_sse_cvtss2si64:
01158   case Intrinsic::x86_sse_cvttss2si:
01159   case Intrinsic::x86_sse_cvttss2si64:
01160   case Intrinsic::x86_sse2_cvtsd2si:
01161   case Intrinsic::x86_sse2_cvtsd2si64:
01162   case Intrinsic::x86_sse2_cvttsd2si:
01163   case Intrinsic::x86_sse2_cvttsd2si64:
01164     return true;
01165   default:
01166     return false;
01167   case 0: break;
01168   }
01169 
01170   if (!F->hasName()) return false;
01171   StringRef Name = F->getName();
01172 
01173   // In these cases, the check of the length is required.  We don't want to
01174   // return true for a name like "cos\0blah" which strcmp would return equal to
01175   // "cos", but has length 8.
01176   switch (Name[0]) {
01177   default: return false;
01178   case 'a':
01179     return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
01180   case 'c':
01181     return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
01182   case 'e':
01183     return Name == "exp" || Name == "exp2";
01184   case 'f':
01185     return Name == "fabs" || Name == "fmod" || Name == "floor";
01186   case 'l':
01187     return Name == "log" || Name == "log10";
01188   case 'p':
01189     return Name == "pow";
01190   case 's':
01191     return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
01192       Name == "sinf" || Name == "sqrtf";
01193   case 't':
01194     return Name == "tan" || Name == "tanh";
01195   }
01196 }
01197 
01198 static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
01199                                 Type *Ty) {
01200   sys::llvm_fenv_clearexcept();
01201   V = NativeFP(V);
01202   if (sys::llvm_fenv_testexcept()) {
01203     sys::llvm_fenv_clearexcept();
01204     return 0;
01205   }
01206 
01207   if (Ty->isHalfTy()) {
01208     APFloat APF(V);
01209     bool unused;
01210     APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
01211     return ConstantFP::get(Ty->getContext(), APF);
01212   }
01213   if (Ty->isFloatTy())
01214     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
01215   if (Ty->isDoubleTy())
01216     return ConstantFP::get(Ty->getContext(), APFloat(V));
01217   llvm_unreachable("Can only constant fold half/float/double");
01218 }
01219 
01220 static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
01221                                       double V, double W, Type *Ty) {
01222   sys::llvm_fenv_clearexcept();
01223   V = NativeFP(V, W);
01224   if (sys::llvm_fenv_testexcept()) {
01225     sys::llvm_fenv_clearexcept();
01226     return 0;
01227   }
01228 
01229   if (Ty->isHalfTy()) {
01230     APFloat APF(V);
01231     bool unused;
01232     APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
01233     return ConstantFP::get(Ty->getContext(), APF);
01234   }
01235   if (Ty->isFloatTy())
01236     return ConstantFP::get(Ty->getContext(), APFloat((float)V));
01237   if (Ty->isDoubleTy())
01238     return ConstantFP::get(Ty->getContext(), APFloat(V));
01239   llvm_unreachable("Can only constant fold half/float/double");
01240 }
01241 
01242 /// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
01243 /// conversion of a constant floating point. If roundTowardZero is false, the
01244 /// default IEEE rounding is used (toward nearest, ties to even). This matches
01245 /// the behavior of the non-truncating SSE instructions in the default rounding
01246 /// mode. The desired integer type Ty is used to select how many bits are
01247 /// available for the result. Returns null if the conversion cannot be
01248 /// performed, otherwise returns the Constant value resulting from the
01249 /// conversion.
01250 static Constant *ConstantFoldConvertToInt(const APFloat &Val,
01251                                           bool roundTowardZero, Type *Ty) {
01252   // All of these conversion intrinsics form an integer of at most 64bits.
01253   unsigned ResultWidth = cast<IntegerType>(Ty)->getBitWidth();
01254   assert(ResultWidth <= 64 &&
01255          "Can only constant fold conversions to 64 and 32 bit ints");
01256 
01257   uint64_t UIntVal;
01258   bool isExact = false;
01259   APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
01260                                               : APFloat::rmNearestTiesToEven;
01261   APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
01262                                                   /*isSigned=*/true, mode,
01263                                                   &isExact);
01264   if (status != APFloat::opOK && status != APFloat::opInexact)
01265     return 0;
01266   return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
01267 }
01268 
01269 /// ConstantFoldCall - Attempt to constant fold a call to the specified function
01270 /// with the specified arguments, returning null if unsuccessful.
01271 Constant *
01272 llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
01273                        const TargetLibraryInfo *TLI) {
01274   if (!F->hasName()) return 0;
01275   StringRef Name = F->getName();
01276 
01277   Type *Ty = F->getReturnType();
01278   if (Operands.size() == 1) {
01279     if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
01280       if (F->getIntrinsicID() == Intrinsic::convert_to_fp16) {
01281         APFloat Val(Op->getValueAPF());
01282 
01283         bool lost = false;
01284         Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
01285 
01286         return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
01287       }
01288       if (!TLI)
01289         return 0;
01290 
01291       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
01292         return 0;
01293 
01294       /// We only fold functions with finite arguments. Folding NaN and inf is
01295       /// likely to be aborted with an exception anyway, and some host libms
01296       /// have known errors raising exceptions.
01297       if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
01298         return 0;
01299 
01300       /// Currently APFloat versions of these functions do not exist, so we use
01301       /// the host native double versions.  Float versions are not called
01302       /// directly but for all these it is true (float)(f((double)arg)) ==
01303       /// f(arg).  Long double not supported yet.
01304       double V;
01305       if (Ty->isFloatTy())
01306         V = Op->getValueAPF().convertToFloat();
01307       else if (Ty->isDoubleTy())
01308         V = Op->getValueAPF().convertToDouble();
01309       else {
01310         bool unused;
01311         APFloat APF = Op->getValueAPF();
01312         APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
01313         V = APF.convertToDouble();
01314       }
01315 
01316       switch (F->getIntrinsicID()) {
01317         default: break;
01318         case Intrinsic::fabs:
01319           return ConstantFoldFP(fabs, V, Ty);
01320 #if HAVE_LOG2
01321         case Intrinsic::log2:
01322           return ConstantFoldFP(log2, V, Ty);
01323 #endif
01324 #if HAVE_LOG
01325         case Intrinsic::log:
01326           return ConstantFoldFP(log, V, Ty);
01327 #endif
01328 #if HAVE_LOG10
01329         case Intrinsic::log10:
01330           return ConstantFoldFP(log10, V, Ty);
01331 #endif
01332 #if HAVE_EXP
01333         case Intrinsic::exp:
01334           return ConstantFoldFP(exp, V, Ty);
01335 #endif
01336 #if HAVE_EXP2
01337         case Intrinsic::exp2:
01338           return ConstantFoldFP(exp2, V, Ty);
01339 #endif
01340         case Intrinsic::floor:
01341           return ConstantFoldFP(floor, V, Ty);
01342       }
01343 
01344       switch (Name[0]) {
01345       case 'a':
01346         if (Name == "acos" && TLI->has(LibFunc::acos))
01347           return ConstantFoldFP(acos, V, Ty);
01348         else if (Name == "asin" && TLI->has(LibFunc::asin))
01349           return ConstantFoldFP(asin, V, Ty);
01350         else if (Name == "atan" && TLI->has(LibFunc::atan))
01351           return ConstantFoldFP(atan, V, Ty);
01352         break;
01353       case 'c':
01354         if (Name == "ceil" && TLI->has(LibFunc::ceil))
01355           return ConstantFoldFP(ceil, V, Ty);
01356         else if (Name == "cos" && TLI->has(LibFunc::cos))
01357           return ConstantFoldFP(cos, V, Ty);
01358         else if (Name == "cosh" && TLI->has(LibFunc::cosh))
01359           return ConstantFoldFP(cosh, V, Ty);
01360         else if (Name == "cosf" && TLI->has(LibFunc::cosf))
01361           return ConstantFoldFP(cos, V, Ty);
01362         break;
01363       case 'e':
01364         if (Name == "exp" && TLI->has(LibFunc::exp))
01365           return ConstantFoldFP(exp, V, Ty);
01366 
01367         if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
01368           // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
01369           // C99 library.
01370           return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
01371         }
01372         break;
01373       case 'f':
01374         if (Name == "fabs" && TLI->has(LibFunc::fabs))
01375           return ConstantFoldFP(fabs, V, Ty);
01376         else if (Name == "floor" && TLI->has(LibFunc::floor))
01377           return ConstantFoldFP(floor, V, Ty);
01378         break;
01379       case 'l':
01380         if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
01381           return ConstantFoldFP(log, V, Ty);
01382         else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
01383           return ConstantFoldFP(log10, V, Ty);
01384         else if (F->getIntrinsicID() == Intrinsic::sqrt &&
01385                  (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
01386           if (V >= -0.0)
01387             return ConstantFoldFP(sqrt, V, Ty);
01388           else // Undefined
01389             return Constant::getNullValue(Ty);
01390         }
01391         break;
01392       case 's':
01393         if (Name == "sin" && TLI->has(LibFunc::sin))
01394           return ConstantFoldFP(sin, V, Ty);
01395         else if (Name == "sinh" && TLI->has(LibFunc::sinh))
01396           return ConstantFoldFP(sinh, V, Ty);
01397         else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
01398           return ConstantFoldFP(sqrt, V, Ty);
01399         else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
01400           return ConstantFoldFP(sqrt, V, Ty);
01401         else if (Name == "sinf" && TLI->has(LibFunc::sinf))
01402           return ConstantFoldFP(sin, V, Ty);
01403         break;
01404       case 't':
01405         if (Name == "tan" && TLI->has(LibFunc::tan))
01406           return ConstantFoldFP(tan, V, Ty);
01407         else if (Name == "tanh" && TLI->has(LibFunc::tanh))
01408           return ConstantFoldFP(tanh, V, Ty);
01409         break;
01410       default:
01411         break;
01412       }
01413       return 0;
01414     }
01415 
01416     if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
01417       switch (F->getIntrinsicID()) {
01418       case Intrinsic::bswap:
01419         return ConstantInt::get(F->getContext(), Op->getValue().byteSwap());
01420       case Intrinsic::ctpop:
01421         return ConstantInt::get(Ty, Op->getValue().countPopulation());
01422       case Intrinsic::convert_from_fp16: {
01423         APFloat Val(APFloat::IEEEhalf, Op->getValue());
01424 
01425         bool lost = false;
01426         APFloat::opStatus status =
01427           Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
01428 
01429         // Conversion is always precise.
01430         (void)status;
01431         assert(status == APFloat::opOK && !lost &&
01432                "Precision lost during fp16 constfolding");
01433 
01434         return ConstantFP::get(F->getContext(), Val);
01435       }
01436       default:
01437         return 0;
01438       }
01439     }
01440 
01441     // Support ConstantVector in case we have an Undef in the top.
01442     if (isa<ConstantVector>(Operands[0]) ||
01443         isa<ConstantDataVector>(Operands[0])) {
01444       Constant *Op = cast<Constant>(Operands[0]);
01445       switch (F->getIntrinsicID()) {
01446       default: break;
01447       case Intrinsic::x86_sse_cvtss2si:
01448       case Intrinsic::x86_sse_cvtss2si64:
01449       case Intrinsic::x86_sse2_cvtsd2si:
01450       case Intrinsic::x86_sse2_cvtsd2si64:
01451         if (ConstantFP *FPOp =
01452               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
01453           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
01454                                           /*roundTowardZero=*/false, Ty);
01455       case Intrinsic::x86_sse_cvttss2si:
01456       case Intrinsic::x86_sse_cvttss2si64:
01457       case Intrinsic::x86_sse2_cvttsd2si:
01458       case Intrinsic::x86_sse2_cvttsd2si64:
01459         if (ConstantFP *FPOp =
01460               dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
01461           return ConstantFoldConvertToInt(FPOp->getValueAPF(),
01462                                           /*roundTowardZero=*/true, Ty);
01463       }
01464     }
01465 
01466     if (isa<UndefValue>(Operands[0])) {
01467       if (F->getIntrinsicID() == Intrinsic::bswap)
01468         return Operands[0];
01469       return 0;
01470     }
01471 
01472     return 0;
01473   }
01474 
01475   if (Operands.size() == 2) {
01476     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
01477       if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
01478         return 0;
01479       double Op1V;
01480       if (Ty->isFloatTy())
01481         Op1V = Op1->getValueAPF().convertToFloat();
01482       else if (Ty->isDoubleTy())
01483         Op1V = Op1->getValueAPF().convertToDouble();
01484       else {
01485         bool unused;
01486         APFloat APF = Op1->getValueAPF();
01487         APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
01488         Op1V = APF.convertToDouble();
01489       }
01490 
01491       if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
01492         if (Op2->getType() != Op1->getType())
01493           return 0;
01494 
01495         double Op2V;
01496         if (Ty->isFloatTy())
01497           Op2V = Op2->getValueAPF().convertToFloat();
01498         else if (Ty->isDoubleTy())
01499           Op2V = Op2->getValueAPF().convertToDouble();
01500         else {
01501           bool unused;
01502           APFloat APF = Op2->getValueAPF();
01503           APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
01504           Op2V = APF.convertToDouble();
01505         }
01506 
01507         if (F->getIntrinsicID() == Intrinsic::pow) {
01508           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
01509         }
01510         if (!TLI)
01511           return 0;
01512         if (Name == "pow" && TLI->has(LibFunc::pow))
01513           return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
01514         if (Name == "fmod" && TLI->has(LibFunc::fmod))
01515           return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
01516         if (Name == "atan2" && TLI->has(LibFunc::atan2))
01517           return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
01518       } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
01519         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isHalfTy())
01520           return ConstantFP::get(F->getContext(),
01521                                  APFloat((float)std::pow((float)Op1V,
01522                                                  (int)Op2C->getZExtValue())));
01523         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isFloatTy())
01524           return ConstantFP::get(F->getContext(),
01525                                  APFloat((float)std::pow((float)Op1V,
01526                                                  (int)Op2C->getZExtValue())));
01527         if (F->getIntrinsicID() == Intrinsic::powi && Ty->isDoubleTy())
01528           return ConstantFP::get(F->getContext(),
01529                                  APFloat((double)std::pow((double)Op1V,
01530                                                    (int)Op2C->getZExtValue())));
01531       }
01532       return 0;
01533     }
01534 
01535     if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
01536       if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
01537         switch (F->getIntrinsicID()) {
01538         default: break;
01539         case Intrinsic::sadd_with_overflow:
01540         case Intrinsic::uadd_with_overflow:
01541         case Intrinsic::ssub_with_overflow:
01542         case Intrinsic::usub_with_overflow:
01543         case Intrinsic::smul_with_overflow:
01544         case Intrinsic::umul_with_overflow: {
01545           APInt Res;
01546           bool Overflow;
01547           switch (F->getIntrinsicID()) {
01548           default: llvm_unreachable("Invalid case");
01549           case Intrinsic::sadd_with_overflow:
01550             Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
01551             break;
01552           case Intrinsic::uadd_with_overflow:
01553             Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
01554             break;
01555           case Intrinsic::ssub_with_overflow:
01556             Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
01557             break;
01558           case Intrinsic::usub_with_overflow:
01559             Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
01560             break;
01561           case Intrinsic::smul_with_overflow:
01562             Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
01563             break;
01564           case Intrinsic::umul_with_overflow:
01565             Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
01566             break;
01567           }
01568           Constant *Ops[] = {
01569             ConstantInt::get(F->getContext(), Res),
01570             ConstantInt::get(Type::getInt1Ty(F->getContext()), Overflow)
01571           };
01572           return ConstantStruct::get(cast<StructType>(F->getReturnType()), Ops);
01573         }
01574         case Intrinsic::cttz:
01575           if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
01576             return UndefValue::get(Ty);
01577           return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
01578         case Intrinsic::ctlz:
01579           if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
01580             return UndefValue::get(Ty);
01581           return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
01582         }
01583       }
01584 
01585       return 0;
01586     }
01587     return 0;
01588   }
01589   return 0;
01590 }