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