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         GEPOperator *GEPO = cast<GEPOperator>(CE);
00636         Type *Ty = GEPO->getSourceElementType();
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     // ee({w,x,y,z}, wrong_value) -> undef
00793     if (CIdx->uge(Val->getType()->getVectorNumElements()))
00794       return UndefValue::get(Val->getType()->getVectorElementType());
00795     return Val->getAggregateElement(CIdx->getZExtValue());
00796   }
00797   return nullptr;
00798 }
00799 
00800 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
00801                                                      Constant *Elt,
00802                                                      Constant *Idx) {
00803   if (isa<UndefValue>(Idx))
00804     return UndefValue::get(Val->getType());
00805 
00806   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
00807   if (!CIdx) return nullptr;
00808 
00809   unsigned NumElts = Val->getType()->getVectorNumElements();
00810   if (CIdx->uge(NumElts))
00811     return UndefValue::get(Val->getType());
00812 
00813   SmallVector<Constant*, 16> Result;
00814   Result.reserve(NumElts);
00815   auto *Ty = Type::getInt32Ty(Val->getContext());
00816   uint64_t IdxVal = CIdx->getZExtValue();
00817   for (unsigned i = 0; i != NumElts; ++i) {    
00818     if (i == IdxVal) {
00819       Result.push_back(Elt);
00820       continue;
00821     }
00822     
00823     Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
00824     Result.push_back(C);
00825   }
00826 
00827   return ConstantVector::get(Result);
00828 }
00829 
00830 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
00831                                                      Constant *V2,
00832                                                      Constant *Mask) {
00833   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
00834   Type *EltTy = V1->getType()->getVectorElementType();
00835 
00836   // Undefined shuffle mask -> undefined value.
00837   if (isa<UndefValue>(Mask))
00838     return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
00839 
00840   // Don't break the bitcode reader hack.
00841   if (isa<ConstantExpr>(Mask)) return nullptr;
00842   
00843   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
00844 
00845   // Loop over the shuffle mask, evaluating each element.
00846   SmallVector<Constant*, 32> Result;
00847   for (unsigned i = 0; i != MaskNumElts; ++i) {
00848     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
00849     if (Elt == -1) {
00850       Result.push_back(UndefValue::get(EltTy));
00851       continue;
00852     }
00853     Constant *InElt;
00854     if (unsigned(Elt) >= SrcNumElts*2)
00855       InElt = UndefValue::get(EltTy);
00856     else if (unsigned(Elt) >= SrcNumElts) {
00857       Type *Ty = IntegerType::get(V2->getContext(), 32);
00858       InElt =
00859         ConstantExpr::getExtractElement(V2,
00860                                         ConstantInt::get(Ty, Elt - SrcNumElts));
00861     } else {
00862       Type *Ty = IntegerType::get(V1->getContext(), 32);
00863       InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
00864     }
00865     Result.push_back(InElt);
00866   }
00867 
00868   return ConstantVector::get(Result);
00869 }
00870 
00871 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
00872                                                     ArrayRef<unsigned> Idxs) {
00873   // Base case: no indices, so return the entire value.
00874   if (Idxs.empty())
00875     return Agg;
00876 
00877   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
00878     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
00879 
00880   return nullptr;
00881 }
00882 
00883 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
00884                                                    Constant *Val,
00885                                                    ArrayRef<unsigned> Idxs) {
00886   // Base case: no indices, so replace the entire value.
00887   if (Idxs.empty())
00888     return Val;
00889 
00890   unsigned NumElts;
00891   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
00892     NumElts = ST->getNumElements();
00893   else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
00894     NumElts = AT->getNumElements();
00895   else
00896     NumElts = Agg->getType()->getVectorNumElements();
00897 
00898   SmallVector<Constant*, 32> Result;
00899   for (unsigned i = 0; i != NumElts; ++i) {
00900     Constant *C = Agg->getAggregateElement(i);
00901     if (!C) return nullptr;
00902 
00903     if (Idxs[0] == i)
00904       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
00905     
00906     Result.push_back(C);
00907   }
00908   
00909   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
00910     return ConstantStruct::get(ST, Result);
00911   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
00912     return ConstantArray::get(AT, Result);
00913   return ConstantVector::get(Result);
00914 }
00915 
00916 
00917 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
00918                                               Constant *C1, Constant *C2) {
00919   // Handle UndefValue up front.
00920   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
00921     switch (Opcode) {
00922     case Instruction::Xor:
00923       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
00924         // Handle undef ^ undef -> 0 special case. This is a common
00925         // idiom (misuse).
00926         return Constant::getNullValue(C1->getType());
00927       // Fallthrough
00928     case Instruction::Add:
00929     case Instruction::Sub:
00930       return UndefValue::get(C1->getType());
00931     case Instruction::And:
00932       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
00933         return C1;
00934       return Constant::getNullValue(C1->getType());   // undef & X -> 0
00935     case Instruction::Mul: {
00936       // undef * undef -> undef
00937       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
00938         return C1;
00939       const APInt *CV;
00940       // X * undef -> undef   if X is odd
00941       if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
00942         if ((*CV)[0])
00943           return UndefValue::get(C1->getType());
00944 
00945       // X * undef -> 0       otherwise
00946       return Constant::getNullValue(C1->getType());
00947     }
00948     case Instruction::SDiv:
00949     case Instruction::UDiv:
00950       // X / undef -> undef
00951       if (match(C1, m_Zero()))
00952         return C2;
00953       // undef / 0 -> undef
00954       // undef / 1 -> undef
00955       if (match(C2, m_Zero()) || match(C2, m_One()))
00956         return C1;
00957       // undef / X -> 0       otherwise
00958       return Constant::getNullValue(C1->getType());
00959     case Instruction::URem:
00960     case Instruction::SRem:
00961       // X % undef -> undef
00962       if (match(C2, m_Undef()))
00963         return C2;
00964       // undef % 0 -> undef
00965       if (match(C2, m_Zero()))
00966         return C1;
00967       // undef % X -> 0       otherwise
00968       return Constant::getNullValue(C1->getType());
00969     case Instruction::Or:                          // X | undef -> -1
00970       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
00971         return C1;
00972       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
00973     case Instruction::LShr:
00974       // X >>l undef -> undef
00975       if (isa<UndefValue>(C2))
00976         return C2;
00977       // undef >>l 0 -> undef
00978       if (match(C2, m_Zero()))
00979         return C1;
00980       // undef >>l X -> 0
00981       return Constant::getNullValue(C1->getType());
00982     case Instruction::AShr:
00983       // X >>a undef -> undef
00984       if (isa<UndefValue>(C2))
00985         return C2;
00986       // undef >>a 0 -> undef
00987       if (match(C2, m_Zero()))
00988         return C1;
00989       // TODO: undef >>a X -> undef if the shift is exact
00990       // undef >>a X -> 0
00991       return Constant::getNullValue(C1->getType());
00992     case Instruction::Shl:
00993       // X << undef -> undef
00994       if (isa<UndefValue>(C2))
00995         return C2;
00996       // undef << 0 -> undef
00997       if (match(C2, m_Zero()))
00998         return C1;
00999       // undef << X -> 0
01000       return Constant::getNullValue(C1->getType());
01001     }
01002   }
01003 
01004   // Handle simplifications when the RHS is a constant int.
01005   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
01006     switch (Opcode) {
01007     case Instruction::Add:
01008       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
01009       break;
01010     case Instruction::Sub:
01011       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
01012       break;
01013     case Instruction::Mul:
01014       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
01015       if (CI2->equalsInt(1))
01016         return C1;                                              // X * 1 == X
01017       break;
01018     case Instruction::UDiv:
01019     case Instruction::SDiv:
01020       if (CI2->equalsInt(1))
01021         return C1;                                            // X / 1 == X
01022       if (CI2->equalsInt(0))
01023         return UndefValue::get(CI2->getType());               // X / 0 == undef
01024       break;
01025     case Instruction::URem:
01026     case Instruction::SRem:
01027       if (CI2->equalsInt(1))
01028         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
01029       if (CI2->equalsInt(0))
01030         return UndefValue::get(CI2->getType());               // X % 0 == undef
01031       break;
01032     case Instruction::And:
01033       if (CI2->isZero()) return C2;                           // X & 0 == 0
01034       if (CI2->isAllOnesValue())
01035         return C1;                                            // X & -1 == X
01036 
01037       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01038         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
01039         if (CE1->getOpcode() == Instruction::ZExt) {
01040           unsigned DstWidth = CI2->getType()->getBitWidth();
01041           unsigned SrcWidth =
01042             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
01043           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
01044           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
01045             return C1;
01046         }
01047 
01048         // If and'ing the address of a global with a constant, fold it.
01049         if (CE1->getOpcode() == Instruction::PtrToInt && 
01050             isa<GlobalValue>(CE1->getOperand(0))) {
01051           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
01052 
01053           // Functions are at least 4-byte aligned.
01054           unsigned GVAlign = GV->getAlignment();
01055           if (isa<Function>(GV))
01056             GVAlign = std::max(GVAlign, 4U);
01057 
01058           if (GVAlign > 1) {
01059             unsigned DstWidth = CI2->getType()->getBitWidth();
01060             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
01061             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
01062 
01063             // If checking bits we know are clear, return zero.
01064             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
01065               return Constant::getNullValue(CI2->getType());
01066           }
01067         }
01068       }
01069       break;
01070     case Instruction::Or:
01071       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
01072       if (CI2->isAllOnesValue())
01073         return C2;                         // X | -1 == -1
01074       break;
01075     case Instruction::Xor:
01076       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
01077 
01078       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01079         switch (CE1->getOpcode()) {
01080         default: break;
01081         case Instruction::ICmp:
01082         case Instruction::FCmp:
01083           // cmp pred ^ true -> cmp !pred
01084           assert(CI2->equalsInt(1));
01085           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
01086           pred = CmpInst::getInversePredicate(pred);
01087           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
01088                                           CE1->getOperand(1));
01089         }
01090       }
01091       break;
01092     case Instruction::AShr:
01093       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
01094       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
01095         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
01096           return ConstantExpr::getLShr(C1, C2);
01097       break;
01098     }
01099   } else if (isa<ConstantInt>(C1)) {
01100     // If C1 is a ConstantInt and C2 is not, swap the operands.
01101     if (Instruction::isCommutative(Opcode))
01102       return ConstantExpr::get(Opcode, C2, C1);
01103   }
01104 
01105   // At this point we know neither constant is an UndefValue.
01106   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
01107     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
01108       const APInt &C1V = CI1->getValue();
01109       const APInt &C2V = CI2->getValue();
01110       switch (Opcode) {
01111       default:
01112         break;
01113       case Instruction::Add:     
01114         return ConstantInt::get(CI1->getContext(), C1V + C2V);
01115       case Instruction::Sub:     
01116         return ConstantInt::get(CI1->getContext(), C1V - C2V);
01117       case Instruction::Mul:     
01118         return ConstantInt::get(CI1->getContext(), C1V * C2V);
01119       case Instruction::UDiv:
01120         assert(!CI2->isNullValue() && "Div by zero handled above");
01121         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
01122       case Instruction::SDiv:
01123         assert(!CI2->isNullValue() && "Div by zero handled above");
01124         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
01125           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
01126         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
01127       case Instruction::URem:
01128         assert(!CI2->isNullValue() && "Div by zero handled above");
01129         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
01130       case Instruction::SRem:
01131         assert(!CI2->isNullValue() && "Div by zero handled above");
01132         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
01133           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
01134         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
01135       case Instruction::And:
01136         return ConstantInt::get(CI1->getContext(), C1V & C2V);
01137       case Instruction::Or:
01138         return ConstantInt::get(CI1->getContext(), C1V | C2V);
01139       case Instruction::Xor:
01140         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
01141       case Instruction::Shl:
01142         if (C2V.ult(C1V.getBitWidth()))
01143           return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
01144         return UndefValue::get(C1->getType()); // too big shift is undef
01145       case Instruction::LShr:
01146         if (C2V.ult(C1V.getBitWidth()))
01147           return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
01148         return UndefValue::get(C1->getType()); // too big shift is undef
01149       case Instruction::AShr:
01150         if (C2V.ult(C1V.getBitWidth()))
01151           return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
01152         return UndefValue::get(C1->getType()); // too big shift is undef
01153       }
01154     }
01155 
01156     switch (Opcode) {
01157     case Instruction::SDiv:
01158     case Instruction::UDiv:
01159     case Instruction::URem:
01160     case Instruction::SRem:
01161     case Instruction::LShr:
01162     case Instruction::AShr:
01163     case Instruction::Shl:
01164       if (CI1->equalsInt(0)) return C1;
01165       break;
01166     default:
01167       break;
01168     }
01169   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
01170     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
01171       APFloat C1V = CFP1->getValueAPF();
01172       APFloat C2V = CFP2->getValueAPF();
01173       APFloat C3V = C1V;  // copy for modification
01174       switch (Opcode) {
01175       default:                   
01176         break;
01177       case Instruction::FAdd:
01178         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
01179         return ConstantFP::get(C1->getContext(), C3V);
01180       case Instruction::FSub:
01181         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
01182         return ConstantFP::get(C1->getContext(), C3V);
01183       case Instruction::FMul:
01184         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
01185         return ConstantFP::get(C1->getContext(), C3V);
01186       case Instruction::FDiv:
01187         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
01188         return ConstantFP::get(C1->getContext(), C3V);
01189       case Instruction::FRem:
01190         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
01191         return ConstantFP::get(C1->getContext(), C3V);
01192       }
01193     }
01194   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
01195     // Perform elementwise folding.
01196     SmallVector<Constant*, 16> Result;
01197     Type *Ty = IntegerType::get(VTy->getContext(), 32);
01198     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
01199       Constant *LHS =
01200         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
01201       Constant *RHS =
01202         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
01203       
01204       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
01205     }
01206     
01207     return ConstantVector::get(Result);
01208   }
01209 
01210   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01211     // There are many possible foldings we could do here.  We should probably
01212     // at least fold add of a pointer with an integer into the appropriate
01213     // getelementptr.  This will improve alias analysis a bit.
01214 
01215     // Given ((a + b) + c), if (b + c) folds to something interesting, return
01216     // (a + (b + c)).
01217     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
01218       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
01219       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
01220         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
01221     }
01222   } else if (isa<ConstantExpr>(C2)) {
01223     // If C2 is a constant expr and C1 isn't, flop them around and fold the
01224     // other way if possible.
01225     if (Instruction::isCommutative(Opcode))
01226       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
01227   }
01228 
01229   // i1 can be simplified in many cases.
01230   if (C1->getType()->isIntegerTy(1)) {
01231     switch (Opcode) {
01232     case Instruction::Add:
01233     case Instruction::Sub:
01234       return ConstantExpr::getXor(C1, C2);
01235     case Instruction::Mul:
01236       return ConstantExpr::getAnd(C1, C2);
01237     case Instruction::Shl:
01238     case Instruction::LShr:
01239     case Instruction::AShr:
01240       // We can assume that C2 == 0.  If it were one the result would be
01241       // undefined because the shift value is as large as the bitwidth.
01242       return C1;
01243     case Instruction::SDiv:
01244     case Instruction::UDiv:
01245       // We can assume that C2 == 1.  If it were zero the result would be
01246       // undefined through division by zero.
01247       return C1;
01248     case Instruction::URem:
01249     case Instruction::SRem:
01250       // We can assume that C2 == 1.  If it were zero the result would be
01251       // undefined through division by zero.
01252       return ConstantInt::getFalse(C1->getContext());
01253     default:
01254       break;
01255     }
01256   }
01257 
01258   // We don't know how to fold this.
01259   return nullptr;
01260 }
01261 
01262 /// isZeroSizedType - This type is zero sized if its an array or structure of
01263 /// zero sized types.  The only leaf zero sized type is an empty structure.
01264 static bool isMaybeZeroSizedType(Type *Ty) {
01265   if (StructType *STy = dyn_cast<StructType>(Ty)) {
01266     if (STy->isOpaque()) return true;  // Can't say.
01267 
01268     // If all of elements have zero size, this does too.
01269     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
01270       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
01271     return true;
01272 
01273   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
01274     return isMaybeZeroSizedType(ATy->getElementType());
01275   }
01276   return false;
01277 }
01278 
01279 /// IdxCompare - Compare the two constants as though they were getelementptr
01280 /// indices.  This allows coersion of the types to be the same thing.
01281 ///
01282 /// If the two constants are the "same" (after coersion), return 0.  If the
01283 /// first is less than the second, return -1, if the second is less than the
01284 /// first, return 1.  If the constants are not integral, return -2.
01285 ///
01286 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
01287   if (C1 == C2) return 0;
01288 
01289   // Ok, we found a different index.  If they are not ConstantInt, we can't do
01290   // anything with them.
01291   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
01292     return -2; // don't know!
01293 
01294   // We cannot compare the indices if they don't fit in an int64_t.
01295   if (cast<ConstantInt>(C1)->getValue().getActiveBits() > 64 ||
01296       cast<ConstantInt>(C2)->getValue().getActiveBits() > 64)
01297     return -2; // don't know!
01298 
01299   // Ok, we have two differing integer indices.  Sign extend them to be the same
01300   // type.
01301   int64_t C1Val = cast<ConstantInt>(C1)->getSExtValue();
01302   int64_t C2Val = cast<ConstantInt>(C2)->getSExtValue();
01303 
01304   if (C1Val == C2Val) return 0;  // They are equal
01305 
01306   // If the type being indexed over is really just a zero sized type, there is
01307   // no pointer difference being made here.
01308   if (isMaybeZeroSizedType(ElTy))
01309     return -2; // dunno.
01310 
01311   // If they are really different, now that they are the same type, then we
01312   // found a difference!
01313   if (C1Val < C2Val)
01314     return -1;
01315   else
01316     return 1;
01317 }
01318 
01319 /// evaluateFCmpRelation - This function determines if there is anything we can
01320 /// decide about the two constants provided.  This doesn't need to handle simple
01321 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
01322 /// If we can determine that the two constants have a particular relation to 
01323 /// each other, we should return the corresponding FCmpInst predicate, 
01324 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
01325 /// ConstantFoldCompareInstruction.
01326 ///
01327 /// To simplify this code we canonicalize the relation so that the first
01328 /// operand is always the most "complex" of the two.  We consider ConstantFP
01329 /// to be the simplest, and ConstantExprs to be the most complex.
01330 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
01331   assert(V1->getType() == V2->getType() &&
01332          "Cannot compare values of different types!");
01333 
01334   // Handle degenerate case quickly
01335   if (V1 == V2) return FCmpInst::FCMP_OEQ;
01336 
01337   if (!isa<ConstantExpr>(V1)) {
01338     if (!isa<ConstantExpr>(V2)) {
01339       // Simple case, use the standard constant folder.
01340       ConstantInt *R = nullptr;
01341       R = dyn_cast<ConstantInt>(
01342                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
01343       if (R && !R->isZero()) 
01344         return FCmpInst::FCMP_OEQ;
01345       R = dyn_cast<ConstantInt>(
01346                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
01347       if (R && !R->isZero()) 
01348         return FCmpInst::FCMP_OLT;
01349       R = dyn_cast<ConstantInt>(
01350                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
01351       if (R && !R->isZero()) 
01352         return FCmpInst::FCMP_OGT;
01353 
01354       // Nothing more we can do
01355       return FCmpInst::BAD_FCMP_PREDICATE;
01356     }
01357 
01358     // If the first operand is simple and second is ConstantExpr, swap operands.
01359     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
01360     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
01361       return FCmpInst::getSwappedPredicate(SwappedRelation);
01362   } else {
01363     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
01364     // constantexpr or a simple constant.
01365     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
01366     switch (CE1->getOpcode()) {
01367     case Instruction::FPTrunc:
01368     case Instruction::FPExt:
01369     case Instruction::UIToFP:
01370     case Instruction::SIToFP:
01371       // We might be able to do something with these but we don't right now.
01372       break;
01373     default:
01374       break;
01375     }
01376   }
01377   // There are MANY other foldings that we could perform here.  They will
01378   // probably be added on demand, as they seem needed.
01379   return FCmpInst::BAD_FCMP_PREDICATE;
01380 }
01381 
01382 static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
01383                                                       const GlobalValue *GV2) {
01384   auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
01385     if (GV->hasExternalWeakLinkage() || GV->hasWeakAnyLinkage())
01386       return true;
01387     if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
01388       Type *Ty = GVar->getValueType();
01389       // A global with opaque type might end up being zero sized.
01390       if (!Ty->isSized())
01391         return true;
01392       // A global with an empty type might lie at the address of any other
01393       // global.
01394       if (Ty->isEmptyTy())
01395         return true;
01396     }
01397     return false;
01398   };
01399   // Don't try to decide equality of aliases.
01400   if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
01401     if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
01402       return ICmpInst::ICMP_NE;
01403   return ICmpInst::BAD_ICMP_PREDICATE;
01404 }
01405 
01406 /// evaluateICmpRelation - This function determines if there is anything we can
01407 /// decide about the two constants provided.  This doesn't need to handle simple
01408 /// things like integer comparisons, but should instead handle ConstantExprs
01409 /// and GlobalValues.  If we can determine that the two constants have a
01410 /// particular relation to each other, we should return the corresponding ICmp
01411 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
01412 ///
01413 /// To simplify this code we canonicalize the relation so that the first
01414 /// operand is always the most "complex" of the two.  We consider simple
01415 /// constants (like ConstantInt) to be the simplest, followed by
01416 /// GlobalValues, followed by ConstantExpr's (the most complex).
01417 ///
01418 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
01419                                                 bool isSigned) {
01420   assert(V1->getType() == V2->getType() &&
01421          "Cannot compare different types of values!");
01422   if (V1 == V2) return ICmpInst::ICMP_EQ;
01423 
01424   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
01425       !isa<BlockAddress>(V1)) {
01426     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
01427         !isa<BlockAddress>(V2)) {
01428       // We distilled this down to a simple case, use the standard constant
01429       // folder.
01430       ConstantInt *R = nullptr;
01431       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
01432       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
01433       if (R && !R->isZero()) 
01434         return pred;
01435       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01436       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
01437       if (R && !R->isZero())
01438         return pred;
01439       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01440       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
01441       if (R && !R->isZero())
01442         return pred;
01443 
01444       // If we couldn't figure it out, bail.
01445       return ICmpInst::BAD_ICMP_PREDICATE;
01446     }
01447 
01448     // If the first operand is simple, swap operands.
01449     ICmpInst::Predicate SwappedRelation = 
01450       evaluateICmpRelation(V2, V1, isSigned);
01451     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01452       return ICmpInst::getSwappedPredicate(SwappedRelation);
01453 
01454   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
01455     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
01456       ICmpInst::Predicate SwappedRelation = 
01457         evaluateICmpRelation(V2, V1, isSigned);
01458       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01459         return ICmpInst::getSwappedPredicate(SwappedRelation);
01460       return ICmpInst::BAD_ICMP_PREDICATE;
01461     }
01462 
01463     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
01464     // constant (which, since the types must match, means that it's a
01465     // ConstantPointerNull).
01466     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
01467       return areGlobalsPotentiallyEqual(GV, GV2);
01468     } else if (isa<BlockAddress>(V2)) {
01469       return ICmpInst::ICMP_NE; // Globals never equal labels.
01470     } else {
01471       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
01472       // GlobalVals can never be null unless they have external weak linkage.
01473       // We don't try to evaluate aliases here.
01474       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
01475         return ICmpInst::ICMP_NE;
01476     }
01477   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
01478     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
01479       ICmpInst::Predicate SwappedRelation = 
01480         evaluateICmpRelation(V2, V1, isSigned);
01481       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
01482         return ICmpInst::getSwappedPredicate(SwappedRelation);
01483       return ICmpInst::BAD_ICMP_PREDICATE;
01484     }
01485     
01486     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
01487     // constant (which, since the types must match, means that it is a
01488     // ConstantPointerNull).
01489     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
01490       // Block address in another function can't equal this one, but block
01491       // addresses in the current function might be the same if blocks are
01492       // empty.
01493       if (BA2->getFunction() != BA->getFunction())
01494         return ICmpInst::ICMP_NE;
01495     } else {
01496       // Block addresses aren't null, don't equal the address of globals.
01497       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
01498              "Canonicalization guarantee!");
01499       return ICmpInst::ICMP_NE;
01500     }
01501   } else {
01502     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
01503     // constantexpr, a global, block address, or a simple constant.
01504     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
01505     Constant *CE1Op0 = CE1->getOperand(0);
01506 
01507     switch (CE1->getOpcode()) {
01508     case Instruction::Trunc:
01509     case Instruction::FPTrunc:
01510     case Instruction::FPExt:
01511     case Instruction::FPToUI:
01512     case Instruction::FPToSI:
01513       break; // We can't evaluate floating point casts or truncations.
01514 
01515     case Instruction::UIToFP:
01516     case Instruction::SIToFP:
01517     case Instruction::BitCast:
01518     case Instruction::ZExt:
01519     case Instruction::SExt:
01520       // If the cast is not actually changing bits, and the second operand is a
01521       // null pointer, do the comparison with the pre-casted value.
01522       if (V2->isNullValue() &&
01523           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
01524         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
01525         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
01526         return evaluateICmpRelation(CE1Op0,
01527                                     Constant::getNullValue(CE1Op0->getType()), 
01528                                     isSigned);
01529       }
01530       break;
01531 
01532     case Instruction::GetElementPtr: {
01533       GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
01534       // Ok, since this is a getelementptr, we know that the constant has a
01535       // pointer type.  Check the various cases.
01536       if (isa<ConstantPointerNull>(V2)) {
01537         // If we are comparing a GEP to a null pointer, check to see if the base
01538         // of the GEP equals the null pointer.
01539         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
01540           if (GV->hasExternalWeakLinkage())
01541             // Weak linkage GVals could be zero or not. We're comparing that
01542             // to null pointer so its greater-or-equal
01543             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
01544           else 
01545             // If its not weak linkage, the GVal must have a non-zero address
01546             // so the result is greater-than
01547             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01548         } else if (isa<ConstantPointerNull>(CE1Op0)) {
01549           // If we are indexing from a null pointer, check to see if we have any
01550           // non-zero indices.
01551           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
01552             if (!CE1->getOperand(i)->isNullValue())
01553               // Offsetting from null, must not be equal.
01554               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01555           // Only zero indexes from null, must still be zero.
01556           return ICmpInst::ICMP_EQ;
01557         }
01558         // Otherwise, we can't really say if the first operand is null or not.
01559       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
01560         if (isa<ConstantPointerNull>(CE1Op0)) {
01561           if (GV2->hasExternalWeakLinkage())
01562             // Weak linkage GVals could be zero or not. We're comparing it to
01563             // a null pointer, so its less-or-equal
01564             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
01565           else
01566             // If its not weak linkage, the GVal must have a non-zero address
01567             // so the result is less-than
01568             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01569         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
01570           if (GV == GV2) {
01571             // If this is a getelementptr of the same global, then it must be
01572             // different.  Because the types must match, the getelementptr could
01573             // only have at most one index, and because we fold getelementptr's
01574             // with a single zero index, it must be nonzero.
01575             assert(CE1->getNumOperands() == 2 &&
01576                    !CE1->getOperand(1)->isNullValue() &&
01577                    "Surprising getelementptr!");
01578             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01579           } else {
01580             if (CE1GEP->hasAllZeroIndices())
01581               return areGlobalsPotentiallyEqual(GV, GV2);
01582             return ICmpInst::BAD_ICMP_PREDICATE;
01583           }
01584         }
01585       } else {
01586         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
01587         Constant *CE2Op0 = CE2->getOperand(0);
01588 
01589         // There are MANY other foldings that we could perform here.  They will
01590         // probably be added on demand, as they seem needed.
01591         switch (CE2->getOpcode()) {
01592         default: break;
01593         case Instruction::GetElementPtr:
01594           // By far the most common case to handle is when the base pointers are
01595           // obviously to the same global.
01596           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
01597             // Don't know relative ordering, but check for inequality.
01598             if (CE1Op0 != CE2Op0) {
01599               GEPOperator *CE2GEP = cast<GEPOperator>(CE2);
01600               if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
01601                 return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
01602                                                   cast<GlobalValue>(CE2Op0));
01603               return ICmpInst::BAD_ICMP_PREDICATE;
01604             }
01605             // Ok, we know that both getelementptr instructions are based on the
01606             // same global.  From this, we can precisely determine the relative
01607             // ordering of the resultant pointers.
01608             unsigned i = 1;
01609 
01610             // The logic below assumes that the result of the comparison
01611             // can be determined by finding the first index that differs.
01612             // This doesn't work if there is over-indexing in any
01613             // subsequent indices, so check for that case first.
01614             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
01615                 !CE2->isGEPWithNoNotionalOverIndexing())
01616                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01617 
01618             // Compare all of the operands the GEP's have in common.
01619             gep_type_iterator GTI = gep_type_begin(CE1);
01620             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
01621                  ++i, ++GTI)
01622               switch (IdxCompare(CE1->getOperand(i),
01623                                  CE2->getOperand(i), GTI.getIndexedType())) {
01624               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
01625               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
01626               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
01627               }
01628 
01629             // Ok, we ran out of things they have in common.  If any leftovers
01630             // are non-zero then we have a difference, otherwise we are equal.
01631             for (; i < CE1->getNumOperands(); ++i)
01632               if (!CE1->getOperand(i)->isNullValue()) {
01633                 if (isa<ConstantInt>(CE1->getOperand(i)))
01634                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
01635                 else
01636                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01637               }
01638 
01639             for (; i < CE2->getNumOperands(); ++i)
01640               if (!CE2->getOperand(i)->isNullValue()) {
01641                 if (isa<ConstantInt>(CE2->getOperand(i)))
01642                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
01643                 else
01644                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
01645               }
01646             return ICmpInst::ICMP_EQ;
01647           }
01648         }
01649       }
01650     }
01651     default:
01652       break;
01653     }
01654   }
01655 
01656   return ICmpInst::BAD_ICMP_PREDICATE;
01657 }
01658 
01659 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
01660                                                Constant *C1, Constant *C2) {
01661   Type *ResultTy;
01662   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
01663     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
01664                                VT->getNumElements());
01665   else
01666     ResultTy = Type::getInt1Ty(C1->getContext());
01667 
01668   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
01669   if (pred == FCmpInst::FCMP_FALSE)
01670     return Constant::getNullValue(ResultTy);
01671 
01672   if (pred == FCmpInst::FCMP_TRUE)
01673     return Constant::getAllOnesValue(ResultTy);
01674 
01675   // Handle some degenerate cases first
01676   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
01677     CmpInst::Predicate Predicate = CmpInst::Predicate(pred);
01678     bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
01679     // For EQ and NE, we can always pick a value for the undef to make the
01680     // predicate pass or fail, so we can return undef.
01681     // Also, if both operands are undef, we can return undef for int comparison.
01682     if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
01683       return UndefValue::get(ResultTy);
01684 
01685     // Otherwise, for integer compare, pick the same value as the non-undef
01686     // operand, and fold it to true or false.
01687     if (isIntegerPredicate)
01688       return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
01689 
01690     // Choosing NaN for the undef will always make unordered comparison succeed
01691     // and ordered comparison fails.
01692     return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
01693   }
01694 
01695   // icmp eq/ne(null,GV) -> false/true
01696   if (C1->isNullValue()) {
01697     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
01698       // Don't try to evaluate aliases.  External weak GV can be null.
01699       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
01700         if (pred == ICmpInst::ICMP_EQ)
01701           return ConstantInt::getFalse(C1->getContext());
01702         else if (pred == ICmpInst::ICMP_NE)
01703           return ConstantInt::getTrue(C1->getContext());
01704       }
01705   // icmp eq/ne(GV,null) -> false/true
01706   } else if (C2->isNullValue()) {
01707     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
01708       // Don't try to evaluate aliases.  External weak GV can be null.
01709       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
01710         if (pred == ICmpInst::ICMP_EQ)
01711           return ConstantInt::getFalse(C1->getContext());
01712         else if (pred == ICmpInst::ICMP_NE)
01713           return ConstantInt::getTrue(C1->getContext());
01714       }
01715   }
01716 
01717   // If the comparison is a comparison between two i1's, simplify it.
01718   if (C1->getType()->isIntegerTy(1)) {
01719     switch(pred) {
01720     case ICmpInst::ICMP_EQ:
01721       if (isa<ConstantInt>(C2))
01722         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
01723       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
01724     case ICmpInst::ICMP_NE:
01725       return ConstantExpr::getXor(C1, C2);
01726     default:
01727       break;
01728     }
01729   }
01730 
01731   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
01732     APInt V1 = cast<ConstantInt>(C1)->getValue();
01733     APInt V2 = cast<ConstantInt>(C2)->getValue();
01734     switch (pred) {
01735     default: llvm_unreachable("Invalid ICmp Predicate");
01736     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
01737     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
01738     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
01739     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
01740     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
01741     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
01742     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
01743     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
01744     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
01745     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
01746     }
01747   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
01748     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
01749     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
01750     APFloat::cmpResult R = C1V.compare(C2V);
01751     switch (pred) {
01752     default: llvm_unreachable("Invalid FCmp Predicate");
01753     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
01754     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
01755     case FCmpInst::FCMP_UNO:
01756       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
01757     case FCmpInst::FCMP_ORD:
01758       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
01759     case FCmpInst::FCMP_UEQ:
01760       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
01761                                         R==APFloat::cmpEqual);
01762     case FCmpInst::FCMP_OEQ:   
01763       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
01764     case FCmpInst::FCMP_UNE:
01765       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
01766     case FCmpInst::FCMP_ONE:   
01767       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
01768                                         R==APFloat::cmpGreaterThan);
01769     case FCmpInst::FCMP_ULT: 
01770       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
01771                                         R==APFloat::cmpLessThan);
01772     case FCmpInst::FCMP_OLT:   
01773       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
01774     case FCmpInst::FCMP_UGT:
01775       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
01776                                         R==APFloat::cmpGreaterThan);
01777     case FCmpInst::FCMP_OGT:
01778       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
01779     case FCmpInst::FCMP_ULE:
01780       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
01781     case FCmpInst::FCMP_OLE: 
01782       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
01783                                         R==APFloat::cmpEqual);
01784     case FCmpInst::FCMP_UGE:
01785       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
01786     case FCmpInst::FCMP_OGE: 
01787       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
01788                                         R==APFloat::cmpEqual);
01789     }
01790   } else if (C1->getType()->isVectorTy()) {
01791     // If we can constant fold the comparison of each element, constant fold
01792     // the whole vector comparison.
01793     SmallVector<Constant*, 4> ResElts;
01794     Type *Ty = IntegerType::get(C1->getContext(), 32);
01795     // Compare the elements, producing an i1 result or constant expr.
01796     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
01797       Constant *C1E =
01798         ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, i));
01799       Constant *C2E =
01800         ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, i));
01801       
01802       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
01803     }
01804     
01805     return ConstantVector::get(ResElts);
01806   }
01807 
01808   if (C1->getType()->isFloatingPointTy() &&
01809       // Only call evaluateFCmpRelation if we have a constant expr to avoid
01810       // infinite recursive loop
01811       (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
01812     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
01813     switch (evaluateFCmpRelation(C1, C2)) {
01814     default: llvm_unreachable("Unknown relation!");
01815     case FCmpInst::FCMP_UNO:
01816     case FCmpInst::FCMP_ORD:
01817     case FCmpInst::FCMP_UEQ:
01818     case FCmpInst::FCMP_UNE:
01819     case FCmpInst::FCMP_ULT:
01820     case FCmpInst::FCMP_UGT:
01821     case FCmpInst::FCMP_ULE:
01822     case FCmpInst::FCMP_UGE:
01823     case FCmpInst::FCMP_TRUE:
01824     case FCmpInst::FCMP_FALSE:
01825     case FCmpInst::BAD_FCMP_PREDICATE:
01826       break; // Couldn't determine anything about these constants.
01827     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
01828       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
01829                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
01830                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
01831       break;
01832     case FCmpInst::FCMP_OLT: // We know that C1 < C2
01833       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
01834                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
01835                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
01836       break;
01837     case FCmpInst::FCMP_OGT: // We know that C1 > C2
01838       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
01839                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
01840                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
01841       break;
01842     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
01843       // We can only partially decide this relation.
01844       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
01845         Result = 0;
01846       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
01847         Result = 1;
01848       break;
01849     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
01850       // We can only partially decide this relation.
01851       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
01852         Result = 0;
01853       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
01854         Result = 1;
01855       break;
01856     case FCmpInst::FCMP_ONE: // We know that C1 != C2
01857       // We can only partially decide this relation.
01858       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
01859         Result = 0;
01860       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
01861         Result = 1;
01862       break;
01863     }
01864 
01865     // If we evaluated the result, return it now.
01866     if (Result != -1)
01867       return ConstantInt::get(ResultTy, Result);
01868 
01869   } else {
01870     // Evaluate the relation between the two constants, per the predicate.
01871     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
01872     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
01873     default: llvm_unreachable("Unknown relational!");
01874     case ICmpInst::BAD_ICMP_PREDICATE:
01875       break;  // Couldn't determine anything about these constants.
01876     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
01877       // If we know the constants are equal, we can decide the result of this
01878       // computation precisely.
01879       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
01880       break;
01881     case ICmpInst::ICMP_ULT:
01882       switch (pred) {
01883       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
01884         Result = 1; break;
01885       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
01886         Result = 0; break;
01887       }
01888       break;
01889     case ICmpInst::ICMP_SLT:
01890       switch (pred) {
01891       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
01892         Result = 1; break;
01893       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
01894         Result = 0; break;
01895       }
01896       break;
01897     case ICmpInst::ICMP_UGT:
01898       switch (pred) {
01899       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
01900         Result = 1; break;
01901       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
01902         Result = 0; break;
01903       }
01904       break;
01905     case ICmpInst::ICMP_SGT:
01906       switch (pred) {
01907       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
01908         Result = 1; break;
01909       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
01910         Result = 0; break;
01911       }
01912       break;
01913     case ICmpInst::ICMP_ULE:
01914       if (pred == ICmpInst::ICMP_UGT) Result = 0;
01915       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
01916       break;
01917     case ICmpInst::ICMP_SLE:
01918       if (pred == ICmpInst::ICMP_SGT) Result = 0;
01919       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
01920       break;
01921     case ICmpInst::ICMP_UGE:
01922       if (pred == ICmpInst::ICMP_ULT) Result = 0;
01923       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
01924       break;
01925     case ICmpInst::ICMP_SGE:
01926       if (pred == ICmpInst::ICMP_SLT) Result = 0;
01927       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
01928       break;
01929     case ICmpInst::ICMP_NE:
01930       if (pred == ICmpInst::ICMP_EQ) Result = 0;
01931       if (pred == ICmpInst::ICMP_NE) Result = 1;
01932       break;
01933     }
01934 
01935     // If we evaluated the result, return it now.
01936     if (Result != -1)
01937       return ConstantInt::get(ResultTy, Result);
01938 
01939     // If the right hand side is a bitcast, try using its inverse to simplify
01940     // it by moving it to the left hand side.  We can't do this if it would turn
01941     // a vector compare into a scalar compare or visa versa.
01942     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
01943       Constant *CE2Op0 = CE2->getOperand(0);
01944       if (CE2->getOpcode() == Instruction::BitCast &&
01945           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
01946         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
01947         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
01948       }
01949     }
01950 
01951     // If the left hand side is an extension, try eliminating it.
01952     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
01953       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
01954           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
01955         Constant *CE1Op0 = CE1->getOperand(0);
01956         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
01957         if (CE1Inverse == CE1Op0) {
01958           // Check whether we can safely truncate the right hand side.
01959           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
01960           if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
01961                                     C2->getType()) == C2)
01962             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
01963         }
01964       }
01965     }
01966 
01967     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
01968         (C1->isNullValue() && !C2->isNullValue())) {
01969       // If C2 is a constant expr and C1 isn't, flip them around and fold the
01970       // other way if possible.
01971       // Also, if C1 is null and C2 isn't, flip them around.
01972       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
01973       return ConstantExpr::getICmp(pred, C2, C1);
01974     }
01975   }
01976   return nullptr;
01977 }
01978 
01979 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
01980 /// is "inbounds".
01981 template<typename IndexTy>
01982 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
01983   // No indices means nothing that could be out of bounds.
01984   if (Idxs.empty()) return true;
01985 
01986   // If the first index is zero, it's in bounds.
01987   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
01988 
01989   // If the first index is one and all the rest are zero, it's in bounds,
01990   // by the one-past-the-end rule.
01991   if (!cast<ConstantInt>(Idxs[0])->isOne())
01992     return false;
01993   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
01994     if (!cast<Constant>(Idxs[i])->isNullValue())
01995       return false;
01996   return true;
01997 }
01998 
01999 /// \brief Test whether a given ConstantInt is in-range for a SequentialType.
02000 static bool isIndexInRangeOfSequentialType(const SequentialType *STy,
02001                                            const ConstantInt *CI) {
02002   if (const PointerType *PTy = dyn_cast<PointerType>(STy))
02003     // Only handle pointers to sized types, not pointers to functions.
02004     return PTy->getElementType()->isSized();
02005 
02006   uint64_t NumElements = 0;
02007   // Determine the number of elements in our sequential type.
02008   if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
02009     NumElements = ATy->getNumElements();
02010   else if (const VectorType *VTy = dyn_cast<VectorType>(STy))
02011     NumElements = VTy->getNumElements();
02012 
02013   assert((isa<ArrayType>(STy) || NumElements > 0) &&
02014          "didn't expect non-array type to have zero elements!");
02015 
02016   // We cannot bounds check the index if it doesn't fit in an int64_t.
02017   if (CI->getValue().getActiveBits() > 64)
02018     return false;
02019 
02020   // A negative index or an index past the end of our sequential type is
02021   // considered out-of-range.
02022   int64_t IndexVal = CI->getSExtValue();
02023   if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
02024     return false;
02025 
02026   // Otherwise, it is in-range.
02027   return true;
02028 }
02029 
02030 template<typename IndexTy>
02031 static Constant *ConstantFoldGetElementPtrImpl(Type *PointeeTy, Constant *C,
02032                                                bool inBounds,
02033                                                ArrayRef<IndexTy> Idxs) {
02034   if (Idxs.empty()) return C;
02035   Constant *Idx0 = cast<Constant>(Idxs[0]);
02036   if ((Idxs.size() == 1 && Idx0->isNullValue()))
02037     return C;
02038 
02039   if (isa<UndefValue>(C)) {
02040     PointerType *Ptr = cast<PointerType>(C->getType());
02041     Type *Ty = GetElementPtrInst::getIndexedType(
02042         cast<PointerType>(Ptr->getScalarType())->getElementType(), Idxs);
02043     assert(Ty && "Invalid indices for GEP!");
02044     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
02045   }
02046 
02047   if (C->isNullValue()) {
02048     bool isNull = true;
02049     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
02050       if (!cast<Constant>(Idxs[i])->isNullValue()) {
02051         isNull = false;
02052         break;
02053       }
02054     if (isNull) {
02055       PointerType *Ptr = cast<PointerType>(C->getType());
02056       Type *Ty = GetElementPtrInst::getIndexedType(
02057           cast<PointerType>(Ptr->getScalarType())->getElementType(), Idxs);
02058       assert(Ty && "Invalid indices for GEP!");
02059       return ConstantPointerNull::get(PointerType::get(Ty,
02060                                                        Ptr->getAddressSpace()));
02061     }
02062   }
02063 
02064   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
02065     // Combine Indices - If the source pointer to this getelementptr instruction
02066     // is a getelementptr instruction, combine the indices of the two
02067     // getelementptr instructions into a single instruction.
02068     //
02069     if (CE->getOpcode() == Instruction::GetElementPtr) {
02070       Type *LastTy = nullptr;
02071       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
02072            I != E; ++I)
02073         LastTy = *I;
02074 
02075       // We cannot combine indices if doing so would take us outside of an
02076       // array or vector.  Doing otherwise could trick us if we evaluated such a
02077       // GEP as part of a load.
02078       //
02079       // e.g. Consider if the original GEP was:
02080       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
02081       //                    i32 0, i32 0, i64 0)
02082       //
02083       // If we then tried to offset it by '8' to get to the third element,
02084       // an i8, we should *not* get:
02085       // i8* getelementptr ({ [2 x i8], i32, i8, [3 x i8] }* @main.c,
02086       //                    i32 0, i32 0, i64 8)
02087       //
02088       // This GEP tries to index array element '8  which runs out-of-bounds.
02089       // Subsequent evaluation would get confused and produce erroneous results.
02090       //
02091       // The following prohibits such a GEP from being formed by checking to see
02092       // if the index is in-range with respect to an array or vector.
02093       bool PerformFold = false;
02094       if (Idx0->isNullValue())
02095         PerformFold = true;
02096       else if (SequentialType *STy = dyn_cast_or_null<SequentialType>(LastTy))
02097         if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx0))
02098           PerformFold = isIndexInRangeOfSequentialType(STy, CI);
02099 
02100       if (PerformFold) {
02101         SmallVector<Value*, 16> NewIndices;
02102         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
02103         NewIndices.append(CE->op_begin() + 1, CE->op_end() - 1);
02104 
02105         // Add the last index of the source with the first index of the new GEP.
02106         // Make sure to handle the case when they are actually different types.
02107         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
02108         // Otherwise it must be an array.
02109         if (!Idx0->isNullValue()) {
02110           Type *IdxTy = Combined->getType();
02111           if (IdxTy != Idx0->getType()) {
02112             unsigned CommonExtendedWidth =
02113                 std::max(IdxTy->getIntegerBitWidth(),
02114                          Idx0->getType()->getIntegerBitWidth());
02115             CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
02116 
02117             Type *CommonTy =
02118                 Type::getIntNTy(IdxTy->getContext(), CommonExtendedWidth);
02119             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
02120             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, CommonTy);
02121             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
02122           } else {
02123             Combined =
02124               ConstantExpr::get(Instruction::Add, Idx0, Combined);
02125           }
02126         }
02127 
02128         NewIndices.push_back(Combined);
02129         NewIndices.append(Idxs.begin() + 1, Idxs.end());
02130         return ConstantExpr::getGetElementPtr(
02131             cast<GEPOperator>(CE)->getSourceElementType(), CE->getOperand(0),
02132             NewIndices, inBounds && cast<GEPOperator>(CE)->isInBounds());
02133       }
02134     }
02135 
02136     // Attempt to fold casts to the same type away.  For example, folding:
02137     //
02138     //   i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
02139     //                       i64 0, i64 0)
02140     // into:
02141     //
02142     //   i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
02143     //
02144     // Don't fold if the cast is changing address spaces.
02145     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
02146       PointerType *SrcPtrTy =
02147         dyn_cast<PointerType>(CE->getOperand(0)->getType());
02148       PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
02149       if (SrcPtrTy && DstPtrTy) {
02150         ArrayType *SrcArrayTy =
02151           dyn_cast<ArrayType>(SrcPtrTy->getElementType());
02152         ArrayType *DstArrayTy =
02153           dyn_cast<ArrayType>(DstPtrTy->getElementType());
02154         if (SrcArrayTy && DstArrayTy
02155             && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
02156             && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
02157           return ConstantExpr::getGetElementPtr(
02158               SrcArrayTy, (Constant *)CE->getOperand(0), Idxs, inBounds);
02159       }
02160     }
02161   }
02162 
02163   // Check to see if any array indices are not within the corresponding
02164   // notional array or vector bounds. If so, try to determine if they can be
02165   // factored out into preceding dimensions.
02166   bool Unknown = false;
02167   SmallVector<Constant *, 8> NewIdxs;
02168   Type *Ty = PointeeTy;
02169   Type *Prev = C->getType();
02170   for (unsigned i = 1, e = Idxs.size(); i != e;
02171        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
02172     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
02173       if (isa<ArrayType>(Ty) || isa<VectorType>(Ty))
02174         if (CI->getSExtValue() > 0 &&
02175             !isIndexInRangeOfSequentialType(cast<SequentialType>(Ty), CI)) {
02176           if (isa<SequentialType>(Prev)) {
02177             // It's out of range, but we can factor it into the prior
02178             // dimension.
02179             NewIdxs.resize(Idxs.size());
02180             uint64_t NumElements = 0;
02181             if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
02182               NumElements = ATy->getNumElements();
02183             else
02184               NumElements = cast<VectorType>(Ty)->getNumElements();
02185 
02186             ConstantInt *Factor = ConstantInt::get(CI->getType(), NumElements);
02187             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
02188 
02189             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
02190             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
02191 
02192             unsigned CommonExtendedWidth =
02193                 std::max(PrevIdx->getType()->getIntegerBitWidth(),
02194                          Div->getType()->getIntegerBitWidth());
02195             CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
02196 
02197             // Before adding, extend both operands to i64 to avoid
02198             // overflow trouble.
02199             if (!PrevIdx->getType()->isIntegerTy(CommonExtendedWidth))
02200               PrevIdx = ConstantExpr::getSExt(
02201                   PrevIdx,
02202                   Type::getIntNTy(Div->getContext(), CommonExtendedWidth));
02203             if (!Div->getType()->isIntegerTy(CommonExtendedWidth))
02204               Div = ConstantExpr::getSExt(
02205                   Div, Type::getIntNTy(Div->getContext(), CommonExtendedWidth));
02206 
02207             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
02208           } else {
02209             // It's out of range, but the prior dimension is a struct
02210             // so we can't do anything about it.
02211             Unknown = true;
02212           }
02213         }
02214     } else {
02215       // We don't know if it's in range or not.
02216       Unknown = true;
02217     }
02218   }
02219 
02220   // If we did any factoring, start over with the adjusted indices.
02221   if (!NewIdxs.empty()) {
02222     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
02223       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
02224     return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, inBounds);
02225   }
02226 
02227   // If all indices are known integers and normalized, we can do a simple
02228   // check for the "inbounds" property.
02229   if (!Unknown && !inBounds)
02230     if (auto *GV = dyn_cast<GlobalVariable>(C))
02231       if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
02232         return ConstantExpr::getInBoundsGetElementPtr(PointeeTy, C, Idxs);
02233 
02234   return nullptr;
02235 }
02236 
02237 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
02238                                           bool inBounds,
02239                                           ArrayRef<Constant *> Idxs) {
02240   return ConstantFoldGetElementPtrImpl(
02241       cast<PointerType>(C->getType()->getScalarType())->getElementType(), C,
02242       inBounds, Idxs);
02243 }
02244 
02245 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
02246                                           bool inBounds,
02247                                           ArrayRef<Value *> Idxs) {
02248   return ConstantFoldGetElementPtrImpl(
02249       cast<PointerType>(C->getType()->getScalarType())->getElementType(), C,
02250       inBounds, Idxs);
02251 }
02252 
02253 Constant *llvm::ConstantFoldGetElementPtr(Type *Ty, Constant *C,
02254                                           bool inBounds,
02255                                           ArrayRef<Constant *> Idxs) {
02256   return ConstantFoldGetElementPtrImpl(Ty, C, inBounds, Idxs);
02257 }
02258 
02259 Constant *llvm::ConstantFoldGetElementPtr(Type *Ty, Constant *C,
02260                                           bool inBounds,
02261                                           ArrayRef<Value *> Idxs) {
02262   return ConstantFoldGetElementPtrImpl(Ty, C, inBounds, Idxs);
02263 }