LLVM  mainline
ConstantFold.cpp
Go to the documentation of this file.
00001 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
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 implements folding of constants for LLVM.  This implements the
00011 // (internal) ConstantFold.h interface, which is used by the
00012 // ConstantExpr::get* methods to automatically fold constants when possible.
00013 //
00014 // The current constant folding implementation is implemented in two pieces: the
00015 // pieces that don't need DataLayout, and the pieces that do. This is to avoid
00016 // a dependence in IR on Target.
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #include "ConstantFold.h"
00021 #include "llvm/ADT/SmallVector.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/Function.h"
00025 #include "llvm/IR/GetElementPtrTypeIterator.h"
00026 #include "llvm/IR/GlobalAlias.h"
00027 #include "llvm/IR/GlobalVariable.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/IR/Operator.h"
00030 #include "llvm/IR/PatternMatch.h"
00031 #include "llvm/Support/Compiler.h"
00032 #include "llvm/Support/ErrorHandling.h"
00033 #include "llvm/Support/ManagedStatic.h"
00034 #include "llvm/Support/MathExtras.h"
00035 #include <limits>
00036 using namespace llvm;
00037 using namespace llvm::PatternMatch;
00038 
00039 //===----------------------------------------------------------------------===//
00040 //                ConstantFold*Instruction Implementations
00041 //===----------------------------------------------------------------------===//
00042 
00043 /// BitCastConstantVector - Convert the specified vector Constant node to the
00044 /// specified vector type.  At this point, we know that the elements of the
00045 /// input vector constant are all simple integer or FP values.
00046 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
00047 
00048   if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
00049   if (CV->isNullValue()) return Constant::getNullValue(DstTy);
00050 
00051   // If this cast changes element count then we can't handle it here:
00052   // doing so requires endianness information.  This should be handled by
00053   // Analysis/ConstantFolding.cpp
00054   unsigned NumElts = DstTy->getNumElements();
00055   if (NumElts != CV->getType()->getVectorNumElements())
00056     return nullptr;
00057   
00058   Type *DstEltTy = DstTy->getElementType();
00059 
00060   SmallVector<Constant*, 16> Result;
00061   Type *Ty = IntegerType::get(CV->getContext(), 32);
00062   for (unsigned i = 0; i != NumElts; ++i) {
00063     Constant *C =
00064       ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
00065     C = ConstantExpr::getBitCast(C, DstEltTy);
00066     Result.push_back(C);
00067   }
00068 
00069   return ConstantVector::get(Result);
00070 }
00071 
00072 /// This function determines which opcode to use to fold two constant cast 
00073 /// expressions together. It uses CastInst::isEliminableCastPair to determine
00074 /// the opcode. Consequently its just a wrapper around that function.
00075 /// @brief Determine if it is valid to fold a cast of a cast
00076 static unsigned
00077 foldConstantCastPair(
00078   unsigned opc,          ///< opcode of the second cast constant expression
00079   ConstantExpr *Op,      ///< the first cast constant expression
00080   Type *DstTy            ///< destination type of the first cast
00081 ) {
00082   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
00083   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
00084   assert(CastInst::isCast(opc) && "Invalid cast opcode");
00085 
00086   // The the types and opcodes for the two Cast constant expressions
00087   Type *SrcTy = Op->getOperand(0)->getType();
00088   Type *MidTy = Op->getType();
00089   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
00090   Instruction::CastOps secondOp = Instruction::CastOps(opc);
00091 
00092   // Assume that pointers are never more than 64 bits wide, and only use this
00093   // for the middle type. Otherwise we could end up folding away illegal
00094   // bitcasts between address spaces with different sizes.
00095   IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
00096 
00097   // Let CastInst::isEliminableCastPair do the heavy lifting.
00098   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
00099                                         nullptr, FakeIntPtrTy, nullptr);
00100 }
00101 
00102 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
00103   Type *SrcTy = V->getType();
00104   if (SrcTy == DestTy)
00105     return V; // no-op cast
00106 
00107   // Check to see if we are casting a pointer to an aggregate to a pointer to
00108   // the first element.  If so, return the appropriate GEP instruction.
00109   if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
00110     if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
00111       if (PTy->getAddressSpace() == DPTy->getAddressSpace()
00112           && DPTy->getElementType()->isSized()) {
00113         SmallVector<Value*, 8> IdxList;
00114         Value *Zero =
00115           Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
00116         IdxList.push_back(Zero);
00117         Type *ElTy = PTy->getElementType();
00118         while (ElTy != DPTy->getElementType()) {
00119           if (StructType *STy = dyn_cast<StructType>(ElTy)) {
00120             if (STy->getNumElements() == 0) break;
00121             ElTy = STy->getElementType(0);
00122             IdxList.push_back(Zero);
00123           } else if (SequentialType *STy = 
00124                      dyn_cast<SequentialType>(ElTy)) {
00125             if (ElTy->isPointerTy()) break;  // Can't index into pointers!
00126             ElTy = STy->getElementType();
00127             IdxList.push_back(Zero);
00128           } else {
00129             break;
00130           }
00131         }
00132 
00133         if (ElTy == DPTy->getElementType())
00134           // This GEP is inbounds because all indices are zero.
00135           return ConstantExpr::getInBoundsGetElementPtr(PTy->getElementType(),
00136                                                         V, IdxList);
00137       }
00138 
00139   // Handle casts from one vector constant to another.  We know that the src 
00140   // and dest type have the same size (otherwise its an illegal cast).
00141   if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
00142     if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
00143       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
00144              "Not cast between same sized vectors!");
00145       SrcTy = nullptr;
00146       // First, check for null.  Undef is already handled.
00147       if (isa<ConstantAggregateZero>(V))
00148         return Constant::getNullValue(DestTy);
00149 
00150       // Handle ConstantVector and ConstantAggregateVector.
00151       return BitCastConstantVector(V, DestPTy);
00152     }
00153 
00154     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
00155     // This allows for other simplifications (although some of them
00156     // can only be handled by Analysis/ConstantFolding.cpp).
00157     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
00158       return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
00159   }
00160 
00161   // Finally, implement bitcast folding now.   The code below doesn't handle
00162   // bitcast right.
00163   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
00164     return ConstantPointerNull::get(cast<PointerType>(DestTy));
00165 
00166   // Handle integral constant input.
00167   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00168     if (DestTy->isIntegerTy())
00169       // Integral -> Integral. This is a no-op because the bit widths must
00170       // be the same. Consequently, we just fold to V.
00171       return V;
00172 
00173     // See note below regarding the PPC_FP128 restriction.
00174     if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())
00175       return ConstantFP::get(DestTy->getContext(),
00176                              APFloat(DestTy->getFltSemantics(),
00177                                      CI->getValue()));
00178 
00179     // Otherwise, can't fold this (vector?)
00180     return nullptr;
00181   }
00182 
00183   // Handle ConstantFP input: FP -> Integral.
00184   if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
00185     // PPC_FP128 is really the sum of two consecutive doubles, where the first
00186     // double is always stored first in memory, regardless of the target
00187     // endianness. The memory layout of i128, however, depends on the target
00188     // endianness, and so we can't fold this without target endianness
00189     // information. This should instead be handled by
00190     // Analysis/ConstantFolding.cpp
00191     if (FP->getType()->isPPC_FP128Ty())
00192       return nullptr;
00193 
00194     return ConstantInt::get(FP->getContext(),
00195                             FP->getValueAPF().bitcastToAPInt());
00196   }
00197 
00198   return nullptr;
00199 }
00200 
00201 
00202 /// ExtractConstantBytes - V is an integer constant which only has a subset of
00203 /// its bytes used.  The bytes used are indicated by ByteStart (which is the
00204 /// first byte used, counting from the least significant byte) and ByteSize,
00205 /// which is the number of bytes used.
00206 ///
00207 /// This function analyzes the specified constant to see if the specified byte
00208 /// range can be returned as a simplified constant.  If so, the constant is
00209 /// returned, otherwise null is returned.
00210 /// 
00211 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
00212                                       unsigned ByteSize) {
00213   assert(C->getType()->isIntegerTy() &&
00214          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
00215          "Non-byte sized integer input");
00216   unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
00217   assert(ByteSize && "Must be accessing some piece");
00218   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
00219   assert(ByteSize != CSize && "Should not extract everything");
00220   
00221   // Constant Integers are simple.
00222   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
00223     APInt V = CI->getValue();
00224     if (ByteStart)
00225       V = V.lshr(ByteStart*8);
00226     V = V.trunc(ByteSize*8);
00227     return ConstantInt::get(CI->getContext(), V);
00228   }
00229   
00230   // In the input is a constant expr, we might be able to recursively simplify.
00231   // If not, we definitely can't do anything.
00232   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
00233   if (!CE) return nullptr;
00234 
00235   switch (CE->getOpcode()) {
00236   default: return nullptr;
00237   case Instruction::Or: {
00238     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
00239     if (!RHS)
00240       return nullptr;
00241     
00242     // X | -1 -> -1.
00243     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
00244       if (RHSC->isAllOnesValue())
00245         return RHSC;
00246     
00247     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
00248     if (!LHS)
00249       return nullptr;
00250     return ConstantExpr::getOr(LHS, RHS);
00251   }
00252   case Instruction::And: {
00253     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
00254     if (!RHS)
00255       return nullptr;
00256     
00257     // X & 0 -> 0.
00258     if (RHS->isNullValue())
00259       return RHS;
00260     
00261     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
00262     if (!LHS)
00263       return nullptr;
00264     return ConstantExpr::getAnd(LHS, RHS);
00265   }
00266   case Instruction::LShr: {
00267     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
00268     if (!Amt)
00269       return nullptr;
00270     unsigned ShAmt = Amt->getZExtValue();
00271     // Cannot analyze non-byte shifts.
00272     if ((ShAmt & 7) != 0)
00273       return nullptr;
00274     ShAmt >>= 3;
00275     
00276     // If the extract is known to be all zeros, return zero.
00277     if (ByteStart >= CSize-ShAmt)
00278       return Constant::getNullValue(IntegerType::get(CE->getContext(),
00279                                                      ByteSize*8));
00280     // If the extract is known to be fully in the input, extract it.
00281     if (ByteStart+ByteSize+ShAmt <= CSize)
00282       return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
00283     
00284     // TODO: Handle the 'partially zero' case.
00285     return nullptr;
00286   }
00287     
00288   case Instruction::Shl: {
00289     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
00290     if (!Amt)
00291       return nullptr;
00292     unsigned ShAmt = Amt->getZExtValue();
00293     // Cannot analyze non-byte shifts.
00294     if ((ShAmt & 7) != 0)
00295       return nullptr;
00296     ShAmt >>= 3;
00297     
00298     // If the extract is known to be all zeros, return zero.
00299     if (ByteStart+ByteSize <= ShAmt)
00300       return Constant::getNullValue(IntegerType::get(CE->getContext(),
00301                                                      ByteSize*8));
00302     // If the extract is known to be fully in the input, extract it.
00303     if (ByteStart >= ShAmt)
00304       return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
00305     
00306     // TODO: Handle the 'partially zero' case.
00307     return nullptr;
00308   }
00309       
00310   case Instruction::ZExt: {
00311     unsigned SrcBitSize =
00312       cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
00313     
00314     // If extracting something that is completely zero, return 0.
00315     if (ByteStart*8 >= SrcBitSize)
00316       return Constant::getNullValue(IntegerType::get(CE->getContext(),
00317                                                      ByteSize*8));
00318 
00319     // If exactly extracting the input, return it.
00320     if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
00321       return CE->getOperand(0);
00322     
00323     // If extracting something completely in the input, if if the input is a
00324     // multiple of 8 bits, recurse.
00325     if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
00326       return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
00327       
00328     // Otherwise, if extracting a subset of the input, which is not multiple of
00329     // 8 bits, do a shift and trunc to get the bits.
00330     if ((ByteStart+ByteSize)*8 < SrcBitSize) {
00331       assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
00332       Constant *Res = CE->getOperand(0);
00333       if (ByteStart)
00334         Res = ConstantExpr::getLShr(Res, 
00335                                  ConstantInt::get(Res->getType(), ByteStart*8));
00336       return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
00337                                                           ByteSize*8));
00338     }
00339     
00340     // TODO: Handle the 'partially zero' case.
00341     return nullptr;
00342   }
00343   }
00344 }
00345 
00346 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
00347 /// on Ty, with any known factors factored out. If Folded is false,
00348 /// return null if no factoring was possible, to avoid endlessly
00349 /// bouncing an unfoldable expression back into the top-level folder.
00350 ///
00351 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
00352                                  bool Folded) {
00353   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00354     Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
00355     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
00356     return ConstantExpr::getNUWMul(E, N);
00357   }
00358 
00359   if (StructType *STy = dyn_cast<StructType>(Ty))
00360     if (!STy->isPacked()) {
00361       unsigned NumElems = STy->getNumElements();
00362       // An empty struct has size zero.
00363       if (NumElems == 0)
00364         return ConstantExpr::getNullValue(DestTy);
00365       // Check for a struct with all members having the same size.
00366       Constant *MemberSize =
00367         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
00368       bool AllSame = true;
00369       for (unsigned i = 1; i != NumElems; ++i)
00370         if (MemberSize !=
00371             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
00372           AllSame = false;
00373           break;
00374         }
00375       if (AllSame) {
00376         Constant *N = ConstantInt::get(DestTy, NumElems);
00377         return ConstantExpr::getNUWMul(MemberSize, N);
00378       }
00379     }
00380 
00381   // Pointer size doesn't depend on the pointee type, so canonicalize them
00382   // to an arbitrary pointee.
00383   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
00384     if (!PTy->getElementType()->isIntegerTy(1))
00385       return
00386         getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
00387                                          PTy->getAddressSpace()),
00388                         DestTy, true);
00389 
00390   // If there's no interesting folding happening, bail so that we don't create
00391   // a constant that looks like it needs folding but really doesn't.
00392   if (!Folded)
00393     return nullptr;
00394 
00395   // Base case: Get a regular sizeof expression.
00396   Constant *C = ConstantExpr::getSizeOf(Ty);
00397   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
00398                                                     DestTy, false),
00399                             C, DestTy);
00400   return C;
00401 }
00402 
00403 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
00404 /// on Ty, with any known factors factored out. If Folded is false,
00405 /// return null if no factoring was possible, to avoid endlessly
00406 /// bouncing an unfoldable expression back into the top-level folder.
00407 ///
00408 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
00409                                   bool Folded) {
00410   // The alignment of an array is equal to the alignment of the
00411   // array element. Note that this is not always true for vectors.
00412   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00413     Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
00414     C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
00415                                                       DestTy,
00416                                                       false),
00417                               C, DestTy);
00418     return C;
00419   }
00420 
00421   if (StructType *STy = dyn_cast<StructType>(Ty)) {
00422     // Packed structs always have an alignment of 1.
00423     if (STy->isPacked())
00424       return ConstantInt::get(DestTy, 1);
00425 
00426     // Otherwise, struct alignment is the maximum alignment of any member.
00427     // Without target data, we can't compare much, but we can check to see
00428     // if all the members have the same alignment.
00429     unsigned NumElems = STy->getNumElements();
00430     // An empty struct has minimal alignment.
00431     if (NumElems == 0)
00432       return ConstantInt::get(DestTy, 1);
00433     // Check for a struct with all members having the same alignment.
00434     Constant *MemberAlign =
00435       getFoldedAlignOf(STy->getElementType(0), DestTy, true);
00436     bool AllSame = true;
00437     for (unsigned i = 1; i != NumElems; ++i)
00438       if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
00439         AllSame = false;
00440         break;
00441       }
00442     if (AllSame)
00443       return MemberAlign;
00444   }
00445 
00446   // Pointer alignment doesn't depend on the pointee type, so canonicalize them
00447   // to an arbitrary pointee.
00448   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
00449     if (!PTy->getElementType()->isIntegerTy(1))
00450       return
00451         getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
00452                                                            1),
00453                                           PTy->getAddressSpace()),
00454                          DestTy, true);
00455 
00456   // If there's no interesting folding happening, bail so that we don't create
00457   // a constant that looks like it needs folding but really doesn't.
00458   if (!Folded)
00459     return nullptr;
00460 
00461   // Base case: Get a regular alignof expression.
00462   Constant *C = ConstantExpr::getAlignOf(Ty);
00463   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
00464                                                     DestTy, false),
00465                             C, DestTy);
00466   return C;
00467 }
00468 
00469 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
00470 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
00471 /// return null if no factoring was possible, to avoid endlessly
00472 /// bouncing an unfoldable expression back into the top-level folder.
00473 ///
00474 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
00475                                    Type *DestTy,
00476                                    bool Folded) {
00477   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
00478     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
00479                                                                 DestTy, false),
00480                                         FieldNo, DestTy);
00481     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
00482     return ConstantExpr::getNUWMul(E, N);
00483   }
00484 
00485   if (StructType *STy = dyn_cast<StructType>(Ty))
00486     if (!STy->isPacked()) {
00487       unsigned NumElems = STy->getNumElements();
00488       // An empty struct has no members.
00489       if (NumElems == 0)
00490         return nullptr;
00491       // Check for a struct with all members having the same size.
00492       Constant *MemberSize =
00493         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
00494       bool AllSame = true;
00495       for (unsigned i = 1; i != NumElems; ++i)
00496         if (MemberSize !=
00497             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
00498           AllSame = false;
00499           break;
00500         }
00501       if (AllSame) {
00502         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
00503                                                                     false,
00504                                                                     DestTy,
00505                                                                     false),
00506                                             FieldNo, DestTy);
00507         return ConstantExpr::getNUWMul(MemberSize, N);
00508       }
00509     }
00510 
00511   // If there's no interesting folding happening, bail so that we don't create
00512   // a constant that looks like it needs folding but really doesn't.
00513   if (!Folded)
00514     return nullptr;
00515 
00516   // Base case: Get a regular offsetof expression.
00517   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
00518   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
00519                                                     DestTy, false),
00520                             C, DestTy);
00521   return C;
00522 }
00523 
00524 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
00525                                             Type *DestTy) {
00526   if (isa<UndefValue>(V)) {
00527     // zext(undef) = 0, because the top bits will be zero.
00528     // sext(undef) = 0, because the top bits will all be the same.
00529     // [us]itofp(undef) = 0, because the result value is bounded.
00530     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
00531         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
00532       return Constant::getNullValue(DestTy);
00533     return UndefValue::get(DestTy);
00534   }
00535 
00536   if (V->isNullValue() && !DestTy->isX86_MMXTy())
00537     return Constant::getNullValue(DestTy);
00538 
00539   // If the cast operand is a constant expression, there's a few things we can
00540   // do to try to simplify it.
00541   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00542     if (CE->isCast()) {
00543       // Try hard to fold cast of cast because they are often eliminable.
00544       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
00545         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
00546     } else if (CE->getOpcode() == Instruction::GetElementPtr &&
00547                // Do not fold addrspacecast (gep 0, .., 0). It might make the
00548                // addrspacecast uncanonicalized.
00549                opc != Instruction::AddrSpaceCast) {
00550       // If all of the indexes in the GEP are null values, there is no pointer
00551       // adjustment going on.  We might as well cast the source pointer.
00552       bool isAllNull = true;
00553       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
00554         if (!CE->getOperand(i)->isNullValue()) {
00555           isAllNull = false;
00556           break;
00557         }
00558       if (isAllNull)
00559         // This is casting one pointer type to another, always BitCast
00560         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
00561     }
00562   }
00563 
00564   // If the cast operand is a constant vector, perform the cast by
00565   // operating on each element. In the cast of bitcasts, the element
00566   // count may be mismatched; don't attempt to handle that here.
00567   if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
00568       DestTy->isVectorTy() &&
00569       DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
00570     SmallVector<Constant*, 16> res;
00571     VectorType *DestVecTy = cast<VectorType>(DestTy);
00572     Type *DstEltTy = DestVecTy->getElementType();
00573     Type *Ty = IntegerType::get(V->getContext(), 32);
00574     for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i) {
00575       Constant *C =
00576         ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
00577       res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
00578     }
00579     return ConstantVector::get(res);
00580   }
00581 
00582   // We actually have to do a cast now. Perform the cast according to the
00583   // opcode specified.
00584   switch (opc) {
00585   default:
00586     llvm_unreachable("Failed to cast constant expression");
00587   case Instruction::FPTrunc:
00588   case Instruction::FPExt:
00589     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
00590       bool ignored;
00591       APFloat Val = FPC->getValueAPF();
00592       Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
00593                   DestTy->isFloatTy() ? APFloat::IEEEsingle :
00594                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
00595                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
00596                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
00597                   DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble :
00598                   APFloat::Bogus,
00599                   APFloat::rmNearestTiesToEven, &ignored);
00600       return ConstantFP::get(V->getContext(), Val);
00601     }
00602     return nullptr; // Can't fold.
00603   case Instruction::FPToUI: 
00604   case Instruction::FPToSI:
00605     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
00606       const APFloat &V = FPC->getValueAPF();
00607       bool ignored;
00608       uint64_t x[2]; 
00609       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00610       if (APFloat::opInvalidOp ==
00611           V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
00612                              APFloat::rmTowardZero, &ignored)) {
00613         // Undefined behavior invoked - the destination type can't represent
00614         // the input constant.
00615         return UndefValue::get(DestTy);
00616       }
00617       APInt Val(DestBitWidth, x);
00618       return ConstantInt::get(FPC->getContext(), Val);
00619     }
00620     return nullptr; // Can't fold.
00621   case Instruction::IntToPtr:   //always treated as unsigned
00622     if (V->isNullValue())       // Is it an integral null value?
00623       return ConstantPointerNull::get(cast<PointerType>(DestTy));
00624     return nullptr;                   // Other pointer types cannot be casted
00625   case Instruction::PtrToInt:   // always treated as unsigned
00626     // Is it a null pointer value?
00627     if (V->isNullValue())
00628       return ConstantInt::get(DestTy, 0);
00629     // If this is a sizeof-like expression, pull out multiplications by
00630     // known factors to expose them to subsequent folding. If it's an
00631     // alignof-like expression, factor out known factors.
00632     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00633       if (CE->getOpcode() == Instruction::GetElementPtr &&
00634           CE->getOperand(0)->isNullValue()) {
00635         Type *Ty =
00636           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
00637         if (CE->getNumOperands() == 2) {
00638           // Handle a sizeof-like expression.
00639           Constant *Idx = CE->getOperand(1);
00640           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
00641           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
00642             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
00643                                                                 DestTy, false),
00644                                         Idx, DestTy);
00645             return ConstantExpr::getMul(C, Idx);
00646           }
00647         } else if (CE->getNumOperands() == 3 &&
00648                    CE->getOperand(1)->isNullValue()) {
00649           // Handle an alignof-like expression.
00650           if (StructType *STy = dyn_cast<StructType>(Ty))
00651             if (!STy->isPacked()) {
00652               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
00653               if (CI->isOne() &&
00654                   STy->getNumElements() == 2 &&
00655                   STy->getElementType(0)->isIntegerTy(1)) {
00656                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
00657               }
00658             }
00659           // Handle an offsetof-like expression.
00660           if (Ty->isStructTy() || Ty->isArrayTy()) {
00661             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
00662                                                 DestTy, false))
00663               return C;
00664           }
00665         }
00666       }
00667     // Other pointer types cannot be casted
00668     return nullptr;
00669   case Instruction::UIToFP:
00670   case Instruction::SIToFP:
00671     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00672       APInt api = CI->getValue();
00673       APFloat apf(DestTy->getFltSemantics(),
00674                   APInt::getNullValue(DestTy->getPrimitiveSizeInBits()));
00675       if (APFloat::opOverflow &
00676           apf.convertFromAPInt(api, opc==Instruction::SIToFP,
00677                               APFloat::rmNearestTiesToEven)) {
00678         // Undefined behavior invoked - the destination type can't represent
00679         // the input constant.
00680         return UndefValue::get(DestTy);
00681       }
00682       return ConstantFP::get(V->getContext(), apf);
00683     }
00684     return nullptr;
00685   case Instruction::ZExt:
00686     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00687       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00688       return ConstantInt::get(V->getContext(),
00689                               CI->getValue().zext(BitWidth));
00690     }
00691     return nullptr;
00692   case Instruction::SExt:
00693     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00694       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00695       return ConstantInt::get(V->getContext(),
00696                               CI->getValue().sext(BitWidth));
00697     }
00698     return nullptr;
00699   case Instruction::Trunc: {
00700     if (V->getType()->isVectorTy())
00701       return nullptr;
00702 
00703     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
00704     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
00705       return ConstantInt::get(V->getContext(),
00706                               CI->getValue().trunc(DestBitWidth));
00707     }
00708     
00709     // The input must be a constantexpr.  See if we can simplify this based on
00710     // the bytes we are demanding.  Only do this if the source and dest are an
00711     // even multiple of a byte.
00712     if ((DestBitWidth & 7) == 0 &&
00713         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
00714       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
00715         return Res;
00716       
00717     return nullptr;
00718   }
00719   case Instruction::BitCast:
00720     return FoldBitCast(V, DestTy);
00721   case Instruction::AddrSpaceCast:
00722     return nullptr;
00723   }
00724 }
00725 
00726 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
00727                                               Constant *V1, Constant *V2) {
00728   // Check for i1 and vector true/false conditions.
00729   if (Cond->isNullValue()) return V2;
00730   if (Cond->isAllOnesValue()) return V1;
00731 
00732   // If the condition is a vector constant, fold the result elementwise.
00733   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
00734     SmallVector<Constant*, 16> Result;
00735     Type *Ty = IntegerType::get(CondV->getContext(), 32);
00736     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
00737       Constant *V;
00738       Constant *V1Element = ConstantExpr::getExtractElement(V1,
00739                                                     ConstantInt::get(Ty, i));
00740       Constant *V2Element = ConstantExpr::getExtractElement(V2,
00741                                                     ConstantInt::get(Ty, i));
00742       Constant *Cond = dyn_cast<Constant>(CondV->getOperand(i));
00743       if (V1Element == V2Element) {
00744         V = V1Element;
00745       } else if (isa<UndefValue>(Cond)) {
00746         V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
00747       } else {
00748         if (!isa<ConstantInt>(Cond)) break;
00749         V = Cond->isNullValue() ? V2Element : V1Element;
00750       }
00751       Result.push_back(V);
00752     }
00753     
00754     // If we were able to build the vector, return it.
00755     if (Result.size() == V1->getType()->getVectorNumElements())
00756       return ConstantVector::get(Result);
00757   }
00758 
00759   if (isa<UndefValue>(Cond)) {
00760     if (isa<UndefValue>(V1)) return V1;
00761     return V2;
00762   }
00763   if (isa<UndefValue>(V1)) return V2;
00764   if (isa<UndefValue>(V2)) return V1;
00765   if (V1 == V2) return V1;
00766 
00767   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
00768     if (TrueVal->getOpcode() == Instruction::Select)
00769       if (TrueVal->getOperand(0) == Cond)
00770         return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
00771   }
00772   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
00773     if (FalseVal->getOpcode() == Instruction::Select)
00774       if (FalseVal->getOperand(0) == Cond)
00775         return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
00776   }
00777 
00778   return nullptr;
00779 }
00780 
00781 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
00782                                                       Constant *Idx) {
00783   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
00784     return UndefValue::get(Val->getType()->getVectorElementType());
00785   if (Val->isNullValue())  // ee(zero, x) -> zero
00786     return Constant::getNullValue(Val->getType()->getVectorElementType());
00787   // ee({w,x,y,z}, undef) -> undef
00788   if (isa<UndefValue>(Idx))
00789     return UndefValue::get(Val->getType()->getVectorElementType());
00790 
00791   if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
00792     uint64_t Index = CIdx->getZExtValue();
00793     // ee({w,x,y,z}, wrong_value) -> undef
00794     if (Index >= Val->getType()->getVectorNumElements())
00795       return UndefValue::get(Val->getType()->getVectorElementType());
00796     return Val->getAggregateElement(Index);
00797   }
00798   return nullptr;
00799 }
00800 
00801 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
00802                                                      Constant *Elt,
00803                                                      Constant *Idx) {
00804   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
00805   if (!CIdx) return nullptr;
00806   const APInt &IdxVal = CIdx->getValue();
00807   
00808   SmallVector<Constant*, 16> Result;
00809   Type *Ty = IntegerType::get(Val->getContext(), 32);
00810   for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
00811     if (i == IdxVal) {
00812       Result.push_back(Elt);
00813       continue;
00814     }
00815     
00816     Constant *C =
00817       ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
00818     Result.push_back(C);
00819   }
00820   
00821   return ConstantVector::get(Result);
00822 }
00823 
00824 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
00825                                                      Constant *V2,
00826                                                      Constant *Mask) {
00827   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
00828   Type *EltTy = V1->getType()->getVectorElementType();
00829 
00830   // Undefined shuffle mask -> undefined value.
00831   if (isa<UndefValue>(Mask))
00832     return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
00833 
00834   // Don't break the bitcode reader hack.
00835   if (isa<ConstantExpr>(Mask)) return nullptr;
00836   
00837   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
00838 
00839   // Loop over the shuffle mask, evaluating each element.
00840   SmallVector<Constant*, 32> Result;
00841   for (unsigned i = 0; i != MaskNumElts; ++i) {
00842     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
00843     if (Elt == -1) {
00844       Result.push_back(UndefValue::get(EltTy));
00845       continue;
00846     }
00847     Constant *InElt;
00848     if (unsigned(Elt) >= SrcNumElts*2)
00849       InElt = UndefValue::get(EltTy);
00850     else if (unsigned(Elt) >= SrcNumElts) {
00851       Type *Ty = IntegerType::get(V2->getContext(), 32);
00852       InElt =
00853         ConstantExpr::getExtractElement(V2,
00854                                         ConstantInt::get(Ty, Elt - SrcNumElts));
00855     } else {
00856       Type *Ty = IntegerType::get(V1->getContext(), 32);
00857       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
00858     }
00859     Result.push_back(InElt);
00860   }
00861 
00862   return ConstantVector::get(Result);
00863 }
00864 
00865 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
00866                                                     ArrayRef<unsigned> Idxs) {
00867   // Base case: no indices, so return the entire value.
00868   if (Idxs.empty())
00869     return Agg;
00870 
00871   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
00872     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
00873 
00874   return nullptr;
00875 }
00876 
00877 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
00878                                                    Constant *Val,
00879                                                    ArrayRef<unsigned> Idxs) {
00880   // Base case: no indices, so replace the entire value.
00881   if (Idxs.empty())
00882     return Val;
00883 
00884   unsigned NumElts;
00885   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
00886     NumElts = ST->getNumElements();
00887   else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
00888     NumElts = AT->getNumElements();
00889   else
00890     NumElts = Agg->getType()->getVectorNumElements();
00891 
00892   SmallVector<Constant*, 32> Result;
00893   for (unsigned i = 0; i != NumElts; ++i) {
00894     Constant *C = Agg->getAggregateElement(i);
00895     if (!C) return nullptr;
00896 
00897     if (Idxs[0] == i)
00898       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
00899     
00900     Result.push_back(C);
00901   }
00902   
00903   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
00904     return ConstantStruct::get(ST, Result);
00905   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
00906     return ConstantArray::get(AT, Result);
00907   return ConstantVector::get(Result);
00908 }
00909 
00910 
00911 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
00912                                               Constant *C1, Constant *C2) {
00913   // Handle UndefValue up front.
00914   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
00915     switch (Opcode) {
00916     case Instruction::Xor:
00917       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
00918         // Handle undef ^ undef -> 0 special case. This is a common
00919         // idiom (misuse).
00920         return Constant::getNullValue(C1->getType());
00921       // Fallthrough
00922     case Instruction::Add:
00923     case Instruction::Sub:
00924       return UndefValue::get(C1->getType());
00925     case Instruction::And:
00926       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
00927         return C1;
00928       return Constant::getNullValue(C1->getType());   // undef & X -> 0
00929     case Instruction::Mul: {
00930       // undef * undef -> undef
00931       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
00932         return C1;
00933       const APInt *CV;
00934       // X * undef -> undef   if X is odd
00935       if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
00936         if ((*CV)[0])
00937           return UndefValue::get(C1->getType());
00938 
00939       // X * undef -> 0       otherwise
00940       return Constant::getNullValue(C1->getType());
00941     }
00942     case Instruction::SDiv:
00943     case Instruction::UDiv:
00944       // X / undef -> undef
00945       if (match(C1, m_Zero()))
00946         return C2;
00947       // undef / 0 -> undef
00948       // undef / 1 -> undef
00949       if (match(C2, m_Zero()) || match(C2, m_One()))
00950         return C1;
00951       // undef / X -> 0       otherwise
00952       return Constant::getNullValue(C1->getType());
00953     case Instruction::URem:
00954     case Instruction::SRem:
00955       // X % undef -> undef
00956       if (match(C2, m_Undef()))
00957         return C2;
00958       // undef % 0 -> undef
00959       if (match(C2, m_Zero()))
00960         return C1;
00961       // undef % X -> 0       otherwise
00962       return Constant::getNullValue(C1->getType());
00963     case Instruction::Or:                          // X | undef -> -1
00964       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
00965         return C1;
00966       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
00967     case Instruction::LShr:
00968       // X >>l undef -> undef
00969       if (isa<UndefValue>(C2))
00970         return C2;
00971       // undef >>l 0 -> undef
00972       if (match(C2, m_Zero()))
00973         return C1;
00974       // undef >>l X -> 0
00975       return Constant::getNullValue(C1->getType());
00976     case Instruction::AShr:
00977       // X >>a undef -> undef
00978       if (isa<UndefValue>(C2))
00979         return C2;
00980       // undef >>a 0 -> undef
00981       if (match(C2, m_Zero()))
00982         return C1;
00983       // TODO: undef >>a X -> undef if the shift is exact
00984       // undef >>a X -> 0
00985       return Constant::getNullValue(C1->getType());
00986     case Instruction::Shl:
00987       // X << undef -> undef
00988       if (isa<UndefValue>(C2))
00989         return C2;
00990       // undef << 0 -> undef
00991       if (match(C2, m_Zero()))
00992         return C1;
00993       // undef << X -> 0
00994       return Constant::getNullValue(C1->getType());
00995     }
00996   }
00997 
00998   // Handle simplifications when the RHS is a constant int.
00999   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
01000     switch (Opcode) {
01001     case Instruction::Add:
01002       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
01003       break;
01004     case Instruction::Sub:
01005       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
01006       break;
01007     case Instruction::Mul:
01008       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
01009       if (CI2->equalsInt(1))
01010         return C1;                                              // X * 1 == X
01011       break;
01012     case Instruction::UDiv:
01013     case Instruction::SDiv:
01014       if (CI2->equalsInt(1))
01015         return C1;                                            // X / 1 == X
01016       if (CI2->equalsInt(0))
01017         return UndefValue::get(CI2->getType());               // X / 0 == undef
01018       break;
01019     case Instruction::URem:
01020     case Instruction::SRem:
01021       if (CI2->equalsInt(1))
01022         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
01023       if (CI2->equalsInt(0))
01024         return UndefValue::get(CI2->getType());               // X % 0 == undef
01025       break;
01026     case Instruction::And:
01027       if (CI2->isZero()) return C2;                           // X & 0 == 0
01028       if (CI2->isAllOnesValue())
01029         return C1;                                            // X & -1 == X
01030 
01031       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01032         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
01033         if (CE1->getOpcode() == Instruction::ZExt) {
01034           unsigned DstWidth = CI2->getType()->getBitWidth();
01035           unsigned SrcWidth =
01036             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
01037           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
01038           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
01039             return C1;
01040         }
01041 
01042         // If and'ing the address of a global with a constant, fold it.
01043         if (CE1->getOpcode() == Instruction::PtrToInt && 
01044             isa<GlobalValue>(CE1->getOperand(0))) {
01045           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
01046 
01047           // Functions are at least 4-byte aligned.
01048           unsigned GVAlign = GV->getAlignment();
01049           if (isa<Function>(GV))
01050             GVAlign = std::max(GVAlign, 4U);
01051 
01052           if (GVAlign > 1) {
01053             unsigned DstWidth = CI2->getType()->getBitWidth();
01054             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
01055             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
01056 
01057             // If checking bits we know are clear, return zero.
01058             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
01059               return Constant::getNullValue(CI2->getType());
01060           }
01061         }
01062       }
01063       break;
01064     case Instruction::Or:
01065       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
01066       if (CI2->isAllOnesValue())
01067         return C2;                         // X | -1 == -1
01068       break;
01069     case Instruction::Xor:
01070       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
01071 
01072       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01073         switch (CE1->getOpcode()) {
01074         default: break;
01075         case Instruction::ICmp:
01076         case Instruction::FCmp:
01077           // cmp pred ^ true -> cmp !pred
01078           assert(CI2->equalsInt(1));
01079           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
01080           pred = CmpInst::getInversePredicate(pred);
01081           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
01082                                           CE1->getOperand(1));
01083         }
01084       }
01085       break;
01086     case Instruction::AShr:
01087       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
01088       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
01089         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
01090           return ConstantExpr::getLShr(C1, C2);
01091       break;
01092     }
01093   } else if (isa<ConstantInt>(C1)) {
01094     // If C1 is a ConstantInt and C2 is not, swap the operands.
01095     if (Instruction::isCommutative(Opcode))
01096       return ConstantExpr::get(Opcode, C2, C1);
01097   }
01098 
01099   // At this point we know neither constant is an UndefValue.
01100   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
01101     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
01102       const APInt &C1V = CI1->getValue();
01103       const APInt &C2V = CI2->getValue();
01104       switch (Opcode) {
01105       default:
01106         break;
01107       case Instruction::Add:     
01108         return ConstantInt::get(CI1->getContext(), C1V + C2V);
01109       case Instruction::Sub:     
01110         return ConstantInt::get(CI1->getContext(), C1V - C2V);
01111       case Instruction::Mul:     
01112         return ConstantInt::get(CI1->getContext(), C1V * C2V);
01113       case Instruction::UDiv:
01114         assert(!CI2->isNullValue() && "Div by zero handled above");
01115         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
01116       case Instruction::SDiv:
01117         assert(!CI2->isNullValue() && "Div by zero handled above");
01118         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
01119           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
01120         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
01121       case Instruction::URem:
01122         assert(!CI2->isNullValue() && "Div by zero handled above");
01123         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
01124       case Instruction::SRem:
01125         assert(!CI2->isNullValue() && "Div by zero handled above");
01126         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
01127           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
01128         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
01129       case Instruction::And:
01130         return ConstantInt::get(CI1->getContext(), C1V & C2V);
01131       case Instruction::Or:
01132         return ConstantInt::get(CI1->getContext(), C1V | C2V);
01133       case Instruction::Xor:
01134         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
01135       case Instruction::Shl:
01136         if (C2V.ult(C1V.getBitWidth()))
01137           return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
01138         return UndefValue::get(C1->getType()); // too big shift is undef
01139       case Instruction::LShr:
01140         if (C2V.ult(C1V.getBitWidth()))
01141           return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
01142         return UndefValue::get(C1->getType()); // too big shift is undef
01143       case Instruction::AShr:
01144         if (C2V.ult(C1V.getBitWidth()))
01145           return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
01146         return UndefValue::get(C1->getType()); // too big shift is undef
01147       }
01148     }
01149 
01150     switch (Opcode) {
01151     case Instruction::SDiv:
01152     case Instruction::UDiv:
01153     case Instruction::URem:
01154     case Instruction::SRem:
01155     case Instruction::LShr:
01156     case Instruction::AShr:
01157     case Instruction::Shl:
01158       if (CI1->equalsInt(0)) return C1;
01159       break;
01160     default:
01161       break;
01162     }
01163   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
01164     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
01165       APFloat C1V = CFP1->getValueAPF();
01166       APFloat C2V = CFP2->getValueAPF();
01167       APFloat C3V = C1V;  // copy for modification
01168       switch (Opcode) {
01169       default:                   
01170         break;
01171       case Instruction::FAdd:
01172         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
01173         return ConstantFP::get(C1->getContext(), C3V);
01174       case Instruction::FSub:
01175         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
01176         return ConstantFP::get(C1->getContext(), C3V);
01177       case Instruction::FMul:
01178         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
01179         return ConstantFP::get(C1->getContext(), C3V);
01180       case Instruction::FDiv:
01181         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
01182         return ConstantFP::get(C1->getContext(), C3V);
01183       case Instruction::FRem:
01184         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
01185         return ConstantFP::get(C1->getContext(), C3V);
01186       }
01187     }
01188   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
01189     // Perform elementwise folding.
01190     SmallVector<Constant*, 16> Result;
01191     Type *Ty = IntegerType::get(VTy->getContext(), 32);
01192     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
01193       Constant *LHS =
01194         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
01195       Constant *RHS =
01196         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
01197       
01198       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
01199     }
01200     
01201     return ConstantVector::get(Result);
01202   }
01203 
01204   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01205     // There are many possible foldings we could do here.  We should probably
01206     // at least fold add of a pointer with an integer into the appropriate
01207     // getelementptr.  This will improve alias analysis a bit.
01208 
01209     // Given ((a + b) + c), if (b + c) folds to something interesting, return
01210     // (a + (b + c)).
01211     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
01212       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
01213       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
01214         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
01215     }
01216   } else if (isa<ConstantExpr>(C2)) {
01217     // If C2 is a constant expr and C1 isn't, flop them around and fold the
01218     // other way if possible.
01219     if (Instruction::isCommutative(Opcode))
01220       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
01221   }
01222 
01223   // i1 can be simplified in many cases.
01224   if (C1->getType()->isIntegerTy(1)) {
01225     switch (Opcode) {
01226     case Instruction::Add:
01227     case Instruction::Sub:
01228       return ConstantExpr::getXor(C1, C2);
01229     case Instruction::Mul:
01230       return ConstantExpr::getAnd(C1, C2);
01231     case Instruction::Shl:
01232     case Instruction::LShr:
01233     case Instruction::AShr:
01234       // We can assume that C2 == 0.  If it were one the result would be
01235       // undefined because the shift value is as large as the bitwidth.
01236       return C1;
01237     case Instruction::SDiv:
01238     case Instruction::UDiv:
01239       // We can assume that C2 == 1.  If it were zero the result would be
01240       // undefined through division by zero.
01241       return C1;
01242     case Instruction::URem:
01243     case Instruction::SRem:
01244       // We can assume that C2 == 1.  If it were zero the result would be
01245       // undefined through division by zero.
01246       return ConstantInt::getFalse(C1->getContext());
01247     default:
01248       break;
01249     }
01250   }
01251 
01252   // We don't know how to fold this.
01253   return nullptr;
01254 }
01255 
01256 /// isZeroSizedType - This type is zero sized if its an array or structure of
01257 /// zero sized types.  The only leaf zero sized type is an empty structure.
01258 static bool isMaybeZeroSizedType(Type *Ty) {
01259   if (StructType *STy = dyn_cast<StructType>(Ty)) {
01260     if (STy->isOpaque()) return true;  // Can't say.
01261 
01262     // If all of elements have zero size, this does too.
01263     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
01264       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
01265     return true;
01266 
01267   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
01268     return isMaybeZeroSizedType(ATy->getElementType());
01269   }
01270   return false;
01271 }
01272 
01273 /// IdxCompare - Compare the two constants as though they were getelementptr
01274 /// indices.  This allows coersion of the types to be the same thing.
01275 ///
01276 /// If the two constants are the "same" (after coersion), return 0.  If the
01277 /// first is less than the second, return -1, if the second is less than the
01278 /// first, return 1.  If the constants are not integral, return -2.
01279 ///
01280 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
01281   if (C1 == C2) return 0;
01282 
01283   // Ok, we found a different index.  If they are not ConstantInt, we can't do
01284   // anything with them.
01285   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
01286     return -2; // don't know!
01287 
01288   // We cannot compare the indices if they don't fit in an int64_t.
01289   if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 ||
01290       cast<ConstantInt>(C2)->getValue().getActiveBits() > 64)
01291     return -2; // don't know!
01292 
01293   // Ok, we have two differing integer indices.  Sign extend them to be the same
01294   // type.
01295   int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue();
01296   int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue();
01297 
01298   if (C1Val == C2Val) return 0;  // They are equal
01299 
01300   // If the type being indexed over is really just a zero sized type, there is
01301   // no pointer difference being made here.
01302   if (isMaybeZeroSizedType(ElTy))
01303     return -2; // dunno.
01304 
01305   // If they are really different, now that they are the same type, then we
01306   // found a difference!
01307   if (C1Val < C2Val)
01308     return -1;
01309   else
01310     return 1;
01311 }
01312 
01313 /// evaluateFCmpRelation - This function determines if there is anything we can
01314 /// decide about the two constants provided.  This doesn't need to handle simple
01315 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
01316 /// If we can determine that the two constants have a particular relation to 
01317 /// each other, we should return the corresponding FCmpInst predicate, 
01318 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
01319 /// ConstantFoldCompareInstruction.
01320 ///
01321 /// To simplify this code we canonicalize the relation so that the first
01322 /// operand is always the most "complex" of the two.  We consider ConstantFP
01323 /// to be the simplest, and ConstantExprs to be the most complex.
01324 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
01325   assert(V1->getType() == V2->getType() &&
01326          "Cannot compare values of different types!");
01327 
01328   // Handle degenerate case quickly
01329   if (V1 == V2) return FCmpInst::FCMP_OEQ;
01330 
01331   if (!isa<ConstantExpr>(V1)) {
01332     if (!isa<ConstantExpr>(V2)) {
01333       // Simple case, use the standard constant folder.
01334       ConstantInt *R = nullptr;
01335       R = dyn_cast<ConstantInt>(
01336                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
01337       if (R && !R->isZero()) 
01338         return FCmpInst::FCMP_OEQ;
01339       R = dyn_cast<ConstantInt>(
01340                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
01341       if (R && !R->isZero()) 
01342         return FCmpInst::FCMP_OLT;
01343       R = dyn_cast<ConstantInt>(
01344                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
01345       if (R && !R->isZero()) 
01346         return FCmpInst::FCMP_OGT;
01347 
01348       // Nothing more we can do
01349       return FCmpInst::BAD_FCMP_PREDICATE;
01350     }
01351 
01352     // If the first operand is simple and second is ConstantExpr, swap operands.
01353     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
01354     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
01355       return FCmpInst::getSwappedPredicate(SwappedRelation);
01356   } else {
01357     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
01358     // constantexpr or a simple constant.
01359     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
01360     switch (CE1->getOpcode()) {
01361     case Instruction::FPTrunc:
01362     case Instruction::FPExt:
01363     case Instruction::UIToFP:
01364     case Instruction::SIToFP:
01365       // We might be able to do something with these but we don't right now.
01366       break;
01367     default:
01368       break;
01369     }
01370   }
01371   // There are MANY other foldings that we could perform here.  They will
01372   // probably be added on demand, as they seem needed.
01373   return FCmpInst::BAD_FCMP_PREDICATE;
01374 }
01375 
01376 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
01377                                                       const GlobalValue *GV2) {
01378   auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
01379     if (GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage())
01380       return true;
01381     if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
01382       Type *Ty = GVar->getType()->getPointerElementType();
01383       // A global with opaque type might end up being zero sized.
01384       if (!Ty->isSized())
01385         return true;
01386       // A global with an empty type might lie at the address of any other
01387       // global.
01388       if (Ty->isEmptyTy())
01389         return true;
01390     }
01391     return false;
01392   };
01393   // Don't try to decide equality of aliases.
01394   if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
01395     if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
01396       return ICmpInst::ICMP_NE;
01397   return ICmpInst::BAD_ICMP_PREDICATE;
01398 }
01399 
01400 /// evaluateICmpRelation - This function determines if there is anything we can
01401 /// decide about the two constants provided.  This doesn't need to handle simple
01402 /// things like integer comparisons, but should instead handle ConstantExprs
01403 /// and GlobalValues.  If we can determine that the two constants have a
01404 /// particular relation to each other, we should return the corresponding ICmp
01405 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
01406 ///
01407 /// To simplify this code we canonicalize the relation so that the first
01408 /// operand is always the most "complex" of the two.  We consider simple
01409 /// constants (like ConstantInt) to be the simplest, followed by
01410 /// GlobalValues, followed by ConstantExpr's (the most complex).
01411 ///
01412 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
01413                                                 bool isSigned) {
01414   assert(V1->getType() == V2->getType() &&
01415          "Cannot compare different types of values!");
01416   if (V1 == V2) return ICmpInst::ICMP_EQ;
01417 
01418   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
01419       !isa<BlockAddress>(V1)) {
01420     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
01421         !isa<BlockAddress>(V2)) {
01422       // We distilled this down to a simple case, use the standard constant
01423       // folder.
01424       ConstantInt *R = nullptr;
01425       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
01426       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
01427       if (R && !R->isZero()) 
01428         return pred;
01429       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01430       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
01431       if (R && !R->isZero())
01432         return pred;
01433       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01434       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
01435       if (R && !R->isZero())
01436         return pred;
01437 
01438       // If we couldn't figure it out, bail.
01439       return ICmpInst::BAD_ICMP_PREDICATE;
01440     }
01441 
01442     // If the first operand is simple, swap operands.
01443     ICmpInst::Predicate SwappedRelation = 
01444       evaluateICmpRelation(V2, V1, isSigned);
01445     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01446       return ICmpInst::getSwappedPredicate(SwappedRelation);
01447 
01448   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
01449     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
01450       ICmpInst::Predicate SwappedRelation = 
01451         evaluateICmpRelation(V2, V1, isSigned);
01452       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01453         return ICmpInst::getSwappedPredicate(SwappedRelation);
01454       return ICmpInst::BAD_ICMP_PREDICATE;
01455     }
01456 
01457     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
01458     // constant (which, since the types must match, means that it's a
01459     // ConstantPointerNull).
01460     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
01461       return areGlobalsPotentiallyEqual(GV, GV2);
01462     } else if (isa<BlockAddress>(V2)) {
01463       return ICmpInst::ICMP_NE; // Globals never equal labels.
01464     } else {
01465       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
01466       // GlobalVals can never be null unless they have external weak linkage.
01467       // We don't try to evaluate aliases here.
01468       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
01469         return ICmpInst::ICMP_NE;
01470     }
01471   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
01472     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
01473       ICmpInst::Predicate SwappedRelation = 
01474         evaluateICmpRelation(V2, V1, isSigned);
01475       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01476         return ICmpInst::getSwappedPredicate(SwappedRelation);
01477       return ICmpInst::BAD_ICMP_PREDICATE;
01478     }
01479     
01480     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
01481     // constant (which, since the types must match, means that it is a
01482     // ConstantPointerNull).
01483     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
01484       // Block address in another function can't equal this one, but block
01485       // addresses in the current function might be the same if blocks are
01486       // empty.
01487       if (BA2->getFunction() != BA->getFunction())
01488         return ICmpInst::ICMP_NE;
01489     } else {
01490       // Block addresses aren't null, don't equal the address of globals.
01491       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
01492              "Canonicalization guarantee!");
01493       return ICmpInst::ICMP_NE;
01494     }
01495   } else {
01496     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
01497     // constantexpr, a global, block address, or a simple constant.
01498     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
01499     Constant *CE1Op0 = CE1->getOperand(0);
01500 
01501     switch (CE1->getOpcode()) {
01502     case Instruction::Trunc:
01503     case Instruction::FPTrunc:
01504     case Instruction::FPExt:
01505     case Instruction::FPToUI:
01506     case Instruction::FPToSI:
01507       break; // We can't evaluate floating point casts or truncations.
01508 
01509     case Instruction::UIToFP:
01510     case Instruction::SIToFP:
01511     case Instruction::BitCast:
01512     case Instruction::ZExt:
01513     case Instruction::SExt:
01514       // If the cast is not actually changing bits, and the second operand is a
01515       // null pointer, do the comparison with the pre-casted value.
01516       if (V2->isNullValue() &&
01517           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
01518         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
01519         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
01520         return evaluateICmpRelation(CE1Op0,
01521                                     Constant::getNullValue(CE1Op0->getType()), 
01522                                     isSigned);
01523       }
01524       break;
01525 
01526     case Instruction::GetElementPtr: {
01527       GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
01528       // Ok, since this is a getelementptr, we know that the constant has a
01529       // pointer type.  Check the various cases.
01530       if (isa<ConstantPointerNull>(V2)) {
01531         // If we are comparing a GEP to a null pointer, check to see if the base
01532         // of the GEP equals the null pointer.
01533         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
01534           if (GV->hasExternalWeakLinkage())
01535             // Weak linkage GVals could be zero or not. We're comparing that
01536             // to null pointer so its greater-or-equal
01537             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
01538           else 
01539             // If its not weak linkage, the GVal must have a non-zero address
01540             // so the result is greater-than
01541             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01542         } else if (isa<ConstantPointerNull>(CE1Op0)) {
01543           // If we are indexing from a null pointer, check to see if we have any
01544           // non-zero indices.
01545           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
01546             if (!CE1->getOperand(i)->isNullValue())
01547               // Offsetting from null, must not be equal.
01548               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01549           // Only zero indexes from null, must still be zero.
01550           return ICmpInst::ICMP_EQ;
01551         }
01552         // Otherwise, we can't really say if the first operand is null or not.
01553       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
01554         if (isa<ConstantPointerNull>(CE1Op0)) {
01555           if (GV2->hasExternalWeakLinkage())
01556             // Weak linkage GVals could be zero or not. We're comparing it to
01557             // a null pointer, so its less-or-equal
01558             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
01559           else
01560             // If its not weak linkage, the GVal must have a non-zero address
01561             // so the result is less-than
01562             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01563         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
01564           if (GV == GV2) {
01565             // If this is a getelementptr of the same global, then it must be
01566             // different.  Because the types must match, the getelementptr could
01567             // only have at most one index, and because we fold getelementptr's
01568             // with a single zero index, it must be nonzero.
01569             assert(CE1->getNumOperands() == 2 &&
01570                    !CE1->getOperand(1)->isNullValue() &&
01571                    "Surprising getelementptr!");
01572             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01573           } else {
01574             if (CE1GEP->hasAllZeroIndices())
01575               return areGlobalsPotentiallyEqual(GV, GV2);
01576             return ICmpInst::BAD_ICMP_PREDICATE;
01577           }
01578         }
01579       } else {
01580         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
01581         Constant *CE2Op0 = CE2->getOperand(0);
01582 
01583         // There are MANY other foldings that we could perform here.  They will
01584         // probably be added on demand, as they seem needed.
01585         switch (CE2->getOpcode()) {
01586         default: break;
01587         case Instruction::GetElementPtr:
01588           // By far the most common case to handle is when the base pointers are
01589           // obviously to the same global.
01590           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
01591             // Don't know relative ordering, but check for inequality.
01592             if (CE1Op0 != CE2Op0) {
01593               GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
01594               if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
01595                 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
01596                                                   cast<GlobalValue>(CE2Op0));
01597               return ICmpInst::BAD_ICMP_PREDICATE;
01598             }
01599             // Ok, we know that both getelementptr instructions are based on the
01600             // same global.  From this, we can precisely determine the relative
01601             // ordering of the resultant pointers.
01602             unsigned i = 1;
01603 
01604             // The logic below assumes that the result of the comparison
01605             // can be determined by finding the first index that differs.
01606             // This doesn't work if there is over-indexing in any
01607             // subsequent indices, so check for that case first.
01608             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
01609                 !CE2->isGEPWithNoNotionalOverIndexing())
01610                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01611 
01612             // Compare all of the operands the GEP's have in common.
01613             gep_type_iterator GTI = gep_type_begin(CE1);
01614             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
01615                  ++i, ++GTI)
01616               switch (IdxCompare(CE1->getOperand(i),
01617                                  CE2->getOperand(i), GTI.getIndexedType())) {
01618               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
01619               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
01620               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
01621               }
01622 
01623             // Ok, we ran out of things they have in common.  If any leftovers
01624             // are non-zero then we have a difference, otherwise we are equal.
01625             for (; i < CE1->getNumOperands(); ++i)
01626               if (!CE1->getOperand(i)->isNullValue()) {
01627                 if (isa<ConstantInt>(CE1->getOperand(i)))
01628                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01629                 else
01630                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01631               }
01632 
01633             for (; i < CE2->getNumOperands(); ++i)
01634               if (!CE2->getOperand(i)->isNullValue()) {
01635                 if (isa<ConstantInt>(CE2->getOperand(i)))
01636                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01637                 else
01638                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01639               }
01640             return ICmpInst::ICMP_EQ;
01641           }
01642         }
01643       }
01644     }
01645     default:
01646       break;
01647     }
01648   }
01649 
01650   return ICmpInst::BAD_ICMP_PREDICATE;
01651 }
01652 
01653 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
01654                                                Constant *C1, Constant *C2) {
01655   Type *ResultTy;
01656   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
01657     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
01658                                VT->getNumElements());
01659   else
01660     ResultTy = Type::getInt1Ty(C1->getContext());
01661 
01662   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
01663   if (pred == FCmpInst::FCMP_FALSE)
01664     return Constant::getNullValue(ResultTy);
01665 
01666   if (pred == FCmpInst::FCMP_TRUE)
01667     return Constant::getAllOnesValue(ResultTy);
01668 
01669   // Handle some degenerate cases first
01670   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
01671     CmpInst::Predicate Predicate = CmpInst::Predicate(pred);
01672     bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
01673     // For EQ and NE, we can always pick a value for the undef to make the
01674     // predicate pass or fail, so we can return undef.
01675     // Also, if both operands are undef, we can return undef for int comparison.
01676     if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
01677       return UndefValue::get(ResultTy);
01678 
01679     // Otherwise, for integer compare, pick the same value as the non-undef
01680     // operand, and fold it to true or false.
01681     if (isIntegerPredicate)
01682       return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
01683 
01684     // Choosing NaN for the undef will always make unordered comparison succeed
01685     // and ordered comparison fails.
01686     return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
01687   }
01688 
01689   // icmp eq/ne(null,GV) -> false/true
01690   if (C1->isNullValue()) {
01691     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
01692       // Don't try to evaluate aliases.  External weak GV can be null.
01693       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
01694         if (pred == ICmpInst::ICMP_EQ)
01695           return ConstantInt::getFalse(C1->getContext());
01696         else if (pred == ICmpInst::ICMP_NE)
01697           return ConstantInt::getTrue(C1->getContext());
01698       }
01699   // icmp eq/ne(GV,null) -> false/true
01700   } else if (C2->isNullValue()) {
01701     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
01702       // Don't try to evaluate aliases.  External weak GV can be null.
01703       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
01704         if (pred == ICmpInst::ICMP_EQ)
01705           return ConstantInt::getFalse(C1->getContext());
01706         else if (pred == ICmpInst::ICMP_NE)
01707           return ConstantInt::getTrue(C1->getContext());
01708       }
01709   }
01710 
01711   // If the comparison is a comparison between two i1's, simplify it.
01712   if (C1->getType()->isIntegerTy(1)) {
01713     switch(pred) {
01714     case ICmpInst::ICMP_EQ:
01715       if (isa<ConstantInt>(C2))
01716         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
01717       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
01718     case ICmpInst::ICMP_NE:
01719       return ConstantExpr::getXor(C1, C2);
01720     default:
01721       break;
01722     }
01723   }
01724 
01725   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
01726     APInt V1 = cast<ConstantInt>(C1)->getValue();
01727     APInt V2 = cast<ConstantInt>(C2)->getValue();
01728     switch (pred) {
01729     default: llvm_unreachable("Invalid ICmp Predicate");
01730     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
01731     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
01732     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
01733     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
01734     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
01735     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
01736     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
01737     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
01738     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
01739     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
01740     }
01741   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
01742     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
01743     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
01744     APFloat::cmpResult R = C1V.compare(C2V);
01745     switch (pred) {
01746     default: llvm_unreachable("Invalid FCmp Predicate");
01747     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
01748     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
01749     case FCmpInst::FCMP_UNO:
01750       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
01751     case FCmpInst::FCMP_ORD:
01752       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
01753     case FCmpInst::FCMP_UEQ:
01754       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
01755                                         R==APFloat::cmpEqual);
01756     case FCmpInst::FCMP_OEQ:   
01757       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
01758     case FCmpInst::FCMP_UNE:
01759       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
01760     case FCmpInst::FCMP_ONE:   
01761       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
01762                                         R==APFloat::cmpGreaterThan);
01763     case FCmpInst::FCMP_ULT: 
01764       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
01765                                         R==APFloat::cmpLessThan);
01766     case FCmpInst::FCMP_OLT:   
01767       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
01768     case FCmpInst::FCMP_UGT:
01769       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
01770                                         R==APFloat::cmpGreaterThan);
01771     case FCmpInst::FCMP_OGT:
01772       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
01773     case FCmpInst::FCMP_ULE:
01774       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
01775     case FCmpInst::FCMP_OLE: 
01776       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
01777                                         R==APFloat::cmpEqual);
01778     case FCmpInst::FCMP_UGE:
01779       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
01780     case FCmpInst::FCMP_OGE: 
01781       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
01782                                         R==APFloat::cmpEqual);
01783     }
01784   } else if (C1->getType()->isVectorTy()) {
01785     // If we can constant fold the comparison of each element, constant fold
01786     // the whole vector comparison.
01787     SmallVector<Constant*, 4> ResElts;
01788     Type *Ty = IntegerType::get(C1->getContext(), 32);
01789     // Compare the elements, producing an i1 result or constant expr.
01790     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
01791       Constant *C1E =
01792         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
01793       Constant *C2E =
01794         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
01795       
01796       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
01797     }
01798     
01799     return ConstantVector::get(ResElts);
01800   }
01801 
01802   if (C1->getType()->isFloatingPointTy() &&
01803       // Only call evaluateFCmpRelation if we have a constant expr to avoid
01804       // infinite recursive loop
01805       (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
01806     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
01807     switch (evaluateFCmpRelation(C1, C2)) {
01808     default: llvm_unreachable("Unknown relation!");
01809     case FCmpInst::FCMP_UNO:
01810     case FCmpInst::FCMP_ORD:
01811     case FCmpInst::FCMP_UEQ:
01812     case FCmpInst::FCMP_UNE:
01813     case FCmpInst::FCMP_ULT:
01814     case FCmpInst::FCMP_UGT:
01815     case FCmpInst::FCMP_ULE:
01816     case FCmpInst::FCMP_UGE:
01817     case FCmpInst::FCMP_TRUE:
01818     case FCmpInst::FCMP_FALSE:
01819     case FCmpInst::BAD_FCMP_PREDICATE:
01820       break; // Couldn't determine anything about these constants.
01821     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
01822       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
01823                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
01824                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
01825       break;
01826     case FCmpInst::FCMP_OLT: // We know that C1 < C2
01827       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
01828                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
01829                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
01830       break;
01831     case FCmpInst::FCMP_OGT: // We know that C1 > C2
01832       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
01833                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
01834                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
01835       break;
01836     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
01837       // We can only partially decide this relation.
01838       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
01839         Result = 0;
01840       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
01841         Result = 1;
01842       break;
01843     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
01844       // We can only partially decide this relation.
01845       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
01846         Result = 0;
01847       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
01848         Result = 1;
01849       break;
01850     case FCmpInst::FCMP_ONE: // We know that C1 != C2
01851       // We can only partially decide this relation.
01852       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
01853         Result = 0;
01854       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
01855         Result = 1;
01856       break;
01857     }
01858 
01859     // If we evaluated the result, return it now.
01860     if (Result != -1)
01861       return ConstantInt::get(ResultTy, Result);
01862 
01863   } else {
01864     // Evaluate the relation between the two constants, per the predicate.
01865     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
01866     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
01867     default: llvm_unreachable("Unknown relational!");
01868     case ICmpInst::BAD_ICMP_PREDICATE:
01869       break;  // Couldn't determine anything about these constants.
01870     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
01871       // If we know the constants are equal, we can decide the result of this
01872       // computation precisely.
01873       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
01874       break;
01875     case ICmpInst::ICMP_ULT:
01876       switch (pred) {
01877       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
01878         Result = 1; break;
01879       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
01880         Result = 0; break;
01881       }
01882       break;
01883     case ICmpInst::ICMP_SLT:
01884       switch (pred) {
01885       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
01886         Result = 1; break;
01887       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
01888         Result = 0; break;
01889       }
01890       break;
01891     case ICmpInst::ICMP_UGT:
01892       switch (pred) {
01893       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
01894         Result = 1; break;
01895       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
01896         Result = 0; break;
01897       }
01898       break;
01899     case ICmpInst::ICMP_SGT:
01900       switch (pred) {
01901       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
01902         Result = 1; break;
01903       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
01904         Result = 0; break;
01905       }
01906       break;
01907     case ICmpInst::ICMP_ULE:
01908       if (pred == ICmpInst::ICMP_UGT) Result = 0;
01909       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
01910       break;
01911     case ICmpInst::ICMP_SLE:
01912       if (pred == ICmpInst::ICMP_SGT) Result = 0;
01913       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
01914       break;
01915     case ICmpInst::ICMP_UGE:
01916       if (pred == ICmpInst::ICMP_ULT) Result = 0;
01917       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
01918       break;
01919     case ICmpInst::ICMP_SGE:
01920       if (pred == ICmpInst::ICMP_SLT) Result = 0;
01921       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
01922       break;
01923     case ICmpInst::ICMP_NE:
01924       if (pred == ICmpInst::ICMP_EQ) Result = 0;
01925       if (pred == ICmpInst::ICMP_NE) Result = 1;
01926       break;
01927     }
01928 
01929     // If we evaluated the result, return it now.
01930     if (Result != -1)
01931       return ConstantInt::get(ResultTy, Result);
01932 
01933     // If the right hand side is a bitcast, try using its inverse to simplify
01934     // it by moving it to the left hand side.  We can't do this if it would turn
01935     // a vector compare into a scalar compare or visa versa.
01936     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
01937       Constant *CE2Op0 = CE2->getOperand(0);
01938       if (CE2->getOpcode() == Instruction::BitCast &&
01939           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
01940         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
01941         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
01942       }
01943     }
01944 
01945     // If the left hand side is an extension, try eliminating it.
01946     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01947       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
01948           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
01949         Constant *CE1Op0 = CE1->getOperand(0);
01950         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
01951         if (CE1Inverse == CE1Op0) {
01952           // Check whether we can safely truncate the right hand side.
01953           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
01954           if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
01955                                     C2->getType()) == C2)
01956             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
01957         }
01958       }
01959     }
01960 
01961     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
01962         (C1->isNullValue() && !C2->isNullValue())) {
01963       // If C2 is a constant expr and C1 isn't, flip them around and fold the
01964       // other way if possible.
01965       // Also, if C1 is null and C2 isn't, flip them around.
01966       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
01967       return ConstantExpr::getICmp(pred, C2, C1);
01968     }
01969   }
01970   return nullptr;
01971 }
01972 
01973 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
01974 /// is "inbounds".
01975 template<typename IndexTy>
01976 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
01977   // No indices means nothing that could be out of bounds.
01978   if (Idxs.empty()) return true;
01979 
01980   // If the first index is zero, it's in bounds.
01981   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
01982 
01983   // If the first index is one and all the rest are zero, it's in bounds,
01984   // by the one-past-the-end rule.
01985   if (!cast<ConstantInt>(Idxs[0])->isOne())
01986     return false;
01987   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
01988     if (!cast<Constant>(Idxs[i])->isNullValue())
01989       return false;
01990   return true;
01991 }
01992 
01993 /// \brief Test whether a given ConstantInt is in-range for a SequentialType.
01994 static bool isIndexInRangeOfSequentialType(const SequentialType *STy,
01995                                            const ConstantInt *CI) {
01996   if (const PointerType *PTy = dyn_cast<PointerType>(STy))
01997     // Only handle pointers to sized types, not pointers to functions.
01998     return PTy->getElementType()->isSized();
01999 
02000   uint64_t NumElements = 0;
02001   // Determine the number of elements in our sequential type.
02002   if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
02003     NumElements = ATy->getNumElements();
02004   else if (const VectorType *VTy = dyn_cast<VectorType>(STy))
02005     NumElements = VTy->getNumElements();
02006 
02007   assert((isa<ArrayType>(STy) || NumElements > 0) &&
02008          "didn't expect non-array type to have zero elements!");
02009 
02010   // We cannot bounds check the index if it doesn't fit in an int64_t.
02011   if (CI->getValue().getActiveBits() > 64)
02012     return false;
02013 
02014   // A negative index or an index past the end of our sequential type is
02015   // considered out-of-range.
02016   int64_t IndexVal = CI->getSExtValue();
02017   if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
02018     return false;
02019 
02020   // Otherwise, it is in-range.
02021   return true;
02022 }
02023 
02024 template<typename IndexTy>
02025 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
02026                                                bool inBounds,
02027                                                ArrayRef<IndexTy> Idxs) {
02028   if (Idxs.empty()) return C;
02029   Constant *Idx0 = cast<Constant>(Idxs[0]);
02030   if ((Idxs.size() == 1 && Idx0->isNullValue()))
02031     return C;
02032 
02033   if (isa<UndefValue>(C)) {
02034     PointerType *Ptr = cast<PointerType>(C->getType());
02035     Type *Ty = GetElementPtrInst::getIndexedType(
02036         cast<PointerType>(Ptr->getScalarType())->getElementType(), Idxs);
02037     assert(Ty && "Invalid indices for GEP!");
02038     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
02039   }
02040 
02041   if (C->isNullValue()) {
02042     bool isNull = true;
02043     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
02044       if (!cast<Constant>(Idxs[i])->isNullValue()) {
02045         isNull = false;
02046         break;
02047       }
02048     if (isNull) {
02049       PointerType *Ptr = cast<PointerType>(C->getType());
02050       Type *Ty = GetElementPtrInst::getIndexedType(
02051           cast<PointerType>(Ptr->getScalarType())->getElementType(), Idxs);
02052       assert(Ty && "Invalid indices for GEP!");
02053       return ConstantPointerNull::get(PointerType::get(Ty,
02054                                                        Ptr->getAddressSpace()));
02055     }
02056   }
02057 
02058   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
02059     // Combine Indices - If the source pointer to this getelementptr instruction
02060     // is a getelementptr instruction, combine the indices of the two
02061     // getelementptr instructions into a single instruction.
02062     //
02063     if (CE->getOpcode() == Instruction::GetElementPtr) {
02064       Type *LastTy = nullptr;
02065       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
02066            I != E; ++I)
02067         LastTy = *I;
02068 
02069       // We cannot combine indices if doing so would take us outside of an
02070       // array or vector.  Doing otherwise could trick us if we evaluated such a
02071       // GEP as part of a load.
02072       //
02073       // e.g. Consider if the original GEP was:
02074       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
02075       //                    i32 0, i32 0, i64 0)
02076       //
02077       // If we then tried to offset it by '8' to get to the third element,
02078       // an i8, we should *not* get:
02079       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
02080       //                    i32 0, i32 0, i64 8)
02081       //
02082       // This GEP tries to index array element '8  which runs out-of-bounds.
02083       // Subsequent evaluation would get confused and produce erroneous results.
02084       //
02085       // The following prohibits such a GEP from being formed by checking to see
02086       // if the index is in-range with respect to an array or vector.
02087       bool PerformFold = false;
02088       if (Idx0->isNullValue())
02089         PerformFold = true;
02090       else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy))
02091         if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
02092           PerformFold = isIndexInRangeOfSequentialType(STy, CI);
02093 
02094       if (PerformFold) {
02095         SmallVector<Value*, 16> NewIndices;
02096         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
02097         NewIndices.append(CE->op_begin() + 1, CE->op_end() - 1);
02098 
02099         // Add the last index of the source with the first index of the new GEP.
02100         // Make sure to handle the case when they are actually different types.
02101         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
02102         // Otherwise it must be an array.
02103         if (!Idx0->isNullValue()) {
02104           Type *IdxTy = Combined->getType();
02105           if (IdxTy != Idx0->getType()) {
02106             unsigned CommonExtendedWidth =
02107                 std::max(IdxTy->getIntegerBitWidth(),
02108                          Idx0->getType()->getIntegerBitWidth());
02109             CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
02110 
02111             Type *CommonTy =
02112                 Type::getIntNTy(IdxTy->getContext(), CommonExtendedWidth);
02113             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
02114             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, CommonTy);
02115             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
02116           } else {
02117             Combined =
02118               ConstantExpr::get(Instruction::Add, Idx0, Combined);
02119           }
02120         }
02121 
02122         NewIndices.push_back(Combined);
02123         NewIndices.append(Idxs.begin() + 1, Idxs.end());
02124         return ConstantExpr::getGetElementPtr(
02125             cast<GEPOperator>(CE)->getSourceElementType(), CE->getOperand(0),
02126             NewIndices, inBounds && cast<GEPOperator>(CE)->isInBounds());
02127       }
02128     }
02129 
02130     // Attempt to fold casts to the same type away.  For example, folding:
02131     //
02132     //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
02133     //                       i64 0, i64 0)
02134     // into:
02135     //
02136     //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
02137     //
02138     // Don't fold if the cast is changing address spaces.
02139     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
02140       PointerType *SrcPtrTy =
02141         dyn_cast<PointerType>(CE->getOperand(0)->getType());
02142       PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
02143       if (SrcPtrTy && DstPtrTy) {
02144         ArrayType *SrcArrayTy =
02145           dyn_cast<ArrayType>(SrcPtrTy->getElementType());
02146         ArrayType *DstArrayTy =
02147           dyn_cast<ArrayType>(DstPtrTy->getElementType());
02148         if (SrcArrayTy && DstArrayTy
02149             && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
02150             && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
02151           return ConstantExpr::getGetElementPtr(
02152               SrcArrayTy, (Constant *)CE->getOperand(0), Idxs, inBounds);
02153       }
02154     }
02155   }
02156 
02157   // Check to see if any array indices are not within the corresponding
02158   // notional array or vector bounds. If so, try to determine if they can be
02159   // factored out into preceding dimensions.
02160   bool Unknown = false;
02161   SmallVector<Constant *, 8> NewIdxs;
02162   Type *Ty = C->getType();
02163   Type *Prev = nullptr;
02164   for (unsigned i = 0, e = Idxs.size(); i != e;
02165        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
02166     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
02167       if (isa<ArrayType>(Ty) || isa<VectorType>(Ty))
02168         if (CI->getSExtValue() > 0 &&
02169             !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) {
02170           if (isa<SequentialType>(Prev)) {
02171             // It's out of range, but we can factor it into the prior
02172             // dimension.
02173             NewIdxs.resize(Idxs.size());
02174             uint64_t NumElements = 0;
02175             if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
02176               NumElements = ATy->getNumElements();
02177             else
02178               NumElements = cast<VectorType>(Ty)->getNumElements();
02179 
02180             ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements);
02181             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
02182 
02183             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
02184             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
02185 
02186             unsigned CommonExtendedWidth =
02187                 std::max(PrevIdx->getType()->getIntegerBitWidth(),
02188                          Div->getType()->getIntegerBitWidth());
02189             CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
02190 
02191             // Before adding, extend both operands to i64 to avoid
02192             // overflow trouble.
02193             if (!PrevIdx->getType()->isIntegerTy(CommonExtendedWidth))
02194               PrevIdx = ConstantExpr::getSExt(
02195                   PrevIdx,
02196                   Type::getIntNTy(Div->getContext(), CommonExtendedWidth));
02197             if (!Div->getType()->isIntegerTy(CommonExtendedWidth))
02198               Div = ConstantExpr::getSExt(
02199                   Div, Type::getIntNTy(Div->getContext(), CommonExtendedWidth));
02200 
02201             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
02202           } else {
02203             // It's out of range, but the prior dimension is a struct
02204             // so we can't do anything about it.
02205             Unknown = true;
02206           }
02207         }
02208     } else {
02209       // We don't know if it's in range or not.
02210       Unknown = true;
02211     }
02212   }
02213 
02214   // If we did any factoring, start over with the adjusted indices.
02215   if (!NewIdxs.empty()) {
02216     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
02217       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
02218     return ConstantExpr::getGetElementPtr(nullptr, C, NewIdxs, inBounds);
02219   }
02220 
02221   // If all indices are known integers and normalized, we can do a simple
02222   // check for the "inbounds" property.
02223   if (!Unknown && !inBounds)
02224     if (auto *GV = dyn_cast<GlobalVariable>(C))
02225       if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
02226         return ConstantExpr::getInBoundsGetElementPtr(nullptr, C, Idxs);
02227 
02228   return nullptr;
02229 }
02230 
02231 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
02232                                           bool inBounds,
02233                                           ArrayRef<Constant *> Idxs) {
02234   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
02235 }
02236 
02237 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
02238                                           bool inBounds,
02239                                           ArrayRef<Value *> Idxs) {
02240   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
02241 }