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