Home | History | Annotate | Download | only in VMCore
      1 //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements folding of constants for LLVM.  This implements the
     11 // (internal) ConstantFold.h interface, which is used by the
     12 // ConstantExpr::get* methods to automatically fold constants when possible.
     13 //
     14 // The current constant folding implementation is implemented in two pieces: the
     15 // pieces that don't need TargetData, and the pieces that do. This is to avoid
     16 // a dependence in VMCore on Target.
     17 //
     18 //===----------------------------------------------------------------------===//
     19 
     20 #include "ConstantFold.h"
     21 #include "llvm/Constants.h"
     22 #include "llvm/Instructions.h"
     23 #include "llvm/DerivedTypes.h"
     24 #include "llvm/Function.h"
     25 #include "llvm/GlobalAlias.h"
     26 #include "llvm/GlobalVariable.h"
     27 #include "llvm/Operator.h"
     28 #include "llvm/ADT/SmallVector.h"
     29 #include "llvm/Support/Compiler.h"
     30 #include "llvm/Support/ErrorHandling.h"
     31 #include "llvm/Support/GetElementPtrTypeIterator.h"
     32 #include "llvm/Support/ManagedStatic.h"
     33 #include "llvm/Support/MathExtras.h"
     34 #include <limits>
     35 using namespace llvm;
     36 
     37 //===----------------------------------------------------------------------===//
     38 //                ConstantFold*Instruction Implementations
     39 //===----------------------------------------------------------------------===//
     40 
     41 /// BitCastConstantVector - Convert the specified vector Constant node to the
     42 /// specified vector type.  At this point, we know that the elements of the
     43 /// input vector constant are all simple integer or FP values.
     44 static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
     45 
     46   if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
     47   if (CV->isNullValue()) return Constant::getNullValue(DstTy);
     48 
     49   // If this cast changes element count then we can't handle it here:
     50   // doing so requires endianness information.  This should be handled by
     51   // Analysis/ConstantFolding.cpp
     52   unsigned NumElts = DstTy->getNumElements();
     53   if (NumElts != CV->getType()->getVectorNumElements())
     54     return 0;
     55 
     56   Type *DstEltTy = DstTy->getElementType();
     57 
     58   // Check to verify that all elements of the input are simple.
     59   SmallVector<Constant*, 16> Result;
     60   for (unsigned i = 0; i != NumElts; ++i) {
     61     Constant *C = CV->getAggregateElement(i);
     62     if (C == 0) return 0;
     63     C = ConstantExpr::getBitCast(C, DstEltTy);
     64     if (isa<ConstantExpr>(C)) return 0;
     65     Result.push_back(C);
     66   }
     67 
     68   return ConstantVector::get(Result);
     69 }
     70 
     71 /// This function determines which opcode to use to fold two constant cast
     72 /// expressions together. It uses CastInst::isEliminableCastPair to determine
     73 /// the opcode. Consequently its just a wrapper around that function.
     74 /// @brief Determine if it is valid to fold a cast of a cast
     75 static unsigned
     76 foldConstantCastPair(
     77   unsigned opc,          ///< opcode of the second cast constant expression
     78   ConstantExpr *Op,      ///< the first cast constant expression
     79   Type *DstTy      ///< desintation type of the first cast
     80 ) {
     81   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
     82   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
     83   assert(CastInst::isCast(opc) && "Invalid cast opcode");
     84 
     85   // The the types and opcodes for the two Cast constant expressions
     86   Type *SrcTy = Op->getOperand(0)->getType();
     87   Type *MidTy = Op->getType();
     88   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
     89   Instruction::CastOps secondOp = Instruction::CastOps(opc);
     90 
     91   // Let CastInst::isEliminableCastPair do the heavy lifting.
     92   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
     93                                         Type::getInt64Ty(DstTy->getContext()));
     94 }
     95 
     96 static Constant *FoldBitCast(Constant *V, Type *DestTy) {
     97   Type *SrcTy = V->getType();
     98   if (SrcTy == DestTy)
     99     return V; // no-op cast
    100 
    101   // Check to see if we are casting a pointer to an aggregate to a pointer to
    102   // the first element.  If so, return the appropriate GEP instruction.
    103   if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
    104     if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
    105       if (PTy->getAddressSpace() == DPTy->getAddressSpace()
    106           && DPTy->getElementType()->isSized()) {
    107         SmallVector<Value*, 8> IdxList;
    108         Value *Zero =
    109           Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
    110         IdxList.push_back(Zero);
    111         Type *ElTy = PTy->getElementType();
    112         while (ElTy != DPTy->getElementType()) {
    113           if (StructType *STy = dyn_cast<StructType>(ElTy)) {
    114             if (STy->getNumElements() == 0) break;
    115             ElTy = STy->getElementType(0);
    116             IdxList.push_back(Zero);
    117           } else if (SequentialType *STy =
    118                      dyn_cast<SequentialType>(ElTy)) {
    119             if (ElTy->isPointerTy()) break;  // Can't index into pointers!
    120             ElTy = STy->getElementType();
    121             IdxList.push_back(Zero);
    122           } else {
    123             break;
    124           }
    125         }
    126 
    127         if (ElTy == DPTy->getElementType())
    128           // This GEP is inbounds because all indices are zero.
    129           return ConstantExpr::getInBoundsGetElementPtr(V, IdxList);
    130       }
    131 
    132   // Handle casts from one vector constant to another.  We know that the src
    133   // and dest type have the same size (otherwise its an illegal cast).
    134   if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
    135     if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
    136       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
    137              "Not cast between same sized vectors!");
    138       SrcTy = NULL;
    139       // First, check for null.  Undef is already handled.
    140       if (isa<ConstantAggregateZero>(V))
    141         return Constant::getNullValue(DestTy);
    142 
    143       // Handle ConstantVector and ConstantAggregateVector.
    144       return BitCastConstantVector(V, DestPTy);
    145     }
    146 
    147     // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
    148     // This allows for other simplifications (although some of them
    149     // can only be handled by Analysis/ConstantFolding.cpp).
    150     if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
    151       return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
    152   }
    153 
    154   // Finally, implement bitcast folding now.   The code below doesn't handle
    155   // bitcast right.
    156   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
    157     return ConstantPointerNull::get(cast<PointerType>(DestTy));
    158 
    159   // Handle integral constant input.
    160   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    161     if (DestTy->isIntegerTy())
    162       // Integral -> Integral. This is a no-op because the bit widths must
    163       // be the same. Consequently, we just fold to V.
    164       return V;
    165 
    166     if (DestTy->isFloatingPointTy())
    167       return ConstantFP::get(DestTy->getContext(),
    168                              APFloat(CI->getValue(),
    169                                      !DestTy->isPPC_FP128Ty()));
    170 
    171     // Otherwise, can't fold this (vector?)
    172     return 0;
    173   }
    174 
    175   // Handle ConstantFP input: FP -> Integral.
    176   if (ConstantFP *FP = dyn_cast<ConstantFP>(V))
    177     return ConstantInt::get(FP->getContext(),
    178                             FP->getValueAPF().bitcastToAPInt());
    179 
    180   return 0;
    181 }
    182 
    183 
    184 /// ExtractConstantBytes - V is an integer constant which only has a subset of
    185 /// its bytes used.  The bytes used are indicated by ByteStart (which is the
    186 /// first byte used, counting from the least significant byte) and ByteSize,
    187 /// which is the number of bytes used.
    188 ///
    189 /// This function analyzes the specified constant to see if the specified byte
    190 /// range can be returned as a simplified constant.  If so, the constant is
    191 /// returned, otherwise null is returned.
    192 ///
    193 static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
    194                                       unsigned ByteSize) {
    195   assert(C->getType()->isIntegerTy() &&
    196          (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
    197          "Non-byte sized integer input");
    198   unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
    199   assert(ByteSize && "Must be accessing some piece");
    200   assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
    201   assert(ByteSize != CSize && "Should not extract everything");
    202 
    203   // Constant Integers are simple.
    204   if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
    205     APInt V = CI->getValue();
    206     if (ByteStart)
    207       V = V.lshr(ByteStart*8);
    208     V = V.trunc(ByteSize*8);
    209     return ConstantInt::get(CI->getContext(), V);
    210   }
    211 
    212   // In the input is a constant expr, we might be able to recursively simplify.
    213   // If not, we definitely can't do anything.
    214   ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
    215   if (CE == 0) return 0;
    216 
    217   switch (CE->getOpcode()) {
    218   default: return 0;
    219   case Instruction::Or: {
    220     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
    221     if (RHS == 0)
    222       return 0;
    223 
    224     // X | -1 -> -1.
    225     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
    226       if (RHSC->isAllOnesValue())
    227         return RHSC;
    228 
    229     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
    230     if (LHS == 0)
    231       return 0;
    232     return ConstantExpr::getOr(LHS, RHS);
    233   }
    234   case Instruction::And: {
    235     Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
    236     if (RHS == 0)
    237       return 0;
    238 
    239     // X & 0 -> 0.
    240     if (RHS->isNullValue())
    241       return RHS;
    242 
    243     Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
    244     if (LHS == 0)
    245       return 0;
    246     return ConstantExpr::getAnd(LHS, RHS);
    247   }
    248   case Instruction::LShr: {
    249     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
    250     if (Amt == 0)
    251       return 0;
    252     unsigned ShAmt = Amt->getZExtValue();
    253     // Cannot analyze non-byte shifts.
    254     if ((ShAmt & 7) != 0)
    255       return 0;
    256     ShAmt >>= 3;
    257 
    258     // If the extract is known to be all zeros, return zero.
    259     if (ByteStart >= CSize-ShAmt)
    260       return Constant::getNullValue(IntegerType::get(CE->getContext(),
    261                                                      ByteSize*8));
    262     // If the extract is known to be fully in the input, extract it.
    263     if (ByteStart+ByteSize+ShAmt <= CSize)
    264       return ExtractConstantBytes(CE->getOperand(0), ByteStart+ShAmt, ByteSize);
    265 
    266     // TODO: Handle the 'partially zero' case.
    267     return 0;
    268   }
    269 
    270   case Instruction::Shl: {
    271     ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
    272     if (Amt == 0)
    273       return 0;
    274     unsigned ShAmt = Amt->getZExtValue();
    275     // Cannot analyze non-byte shifts.
    276     if ((ShAmt & 7) != 0)
    277       return 0;
    278     ShAmt >>= 3;
    279 
    280     // If the extract is known to be all zeros, return zero.
    281     if (ByteStart+ByteSize <= ShAmt)
    282       return Constant::getNullValue(IntegerType::get(CE->getContext(),
    283                                                      ByteSize*8));
    284     // If the extract is known to be fully in the input, extract it.
    285     if (ByteStart >= ShAmt)
    286       return ExtractConstantBytes(CE->getOperand(0), ByteStart-ShAmt, ByteSize);
    287 
    288     // TODO: Handle the 'partially zero' case.
    289     return 0;
    290   }
    291 
    292   case Instruction::ZExt: {
    293     unsigned SrcBitSize =
    294       cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
    295 
    296     // If extracting something that is completely zero, return 0.
    297     if (ByteStart*8 >= SrcBitSize)
    298       return Constant::getNullValue(IntegerType::get(CE->getContext(),
    299                                                      ByteSize*8));
    300 
    301     // If exactly extracting the input, return it.
    302     if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
    303       return CE->getOperand(0);
    304 
    305     // If extracting something completely in the input, if if the input is a
    306     // multiple of 8 bits, recurse.
    307     if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
    308       return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
    309 
    310     // Otherwise, if extracting a subset of the input, which is not multiple of
    311     // 8 bits, do a shift and trunc to get the bits.
    312     if ((ByteStart+ByteSize)*8 < SrcBitSize) {
    313       assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
    314       Constant *Res = CE->getOperand(0);
    315       if (ByteStart)
    316         Res = ConstantExpr::getLShr(Res,
    317                                  ConstantInt::get(Res->getType(), ByteStart*8));
    318       return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
    319                                                           ByteSize*8));
    320     }
    321 
    322     // TODO: Handle the 'partially zero' case.
    323     return 0;
    324   }
    325   }
    326 }
    327 
    328 /// getFoldedSizeOf - Return a ConstantExpr with type DestTy for sizeof
    329 /// on Ty, with any known factors factored out. If Folded is false,
    330 /// return null if no factoring was possible, to avoid endlessly
    331 /// bouncing an unfoldable expression back into the top-level folder.
    332 ///
    333 static Constant *getFoldedSizeOf(Type *Ty, Type *DestTy,
    334                                  bool Folded) {
    335   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
    336     Constant *N = ConstantInt::get(DestTy, ATy->getNumElements());
    337     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
    338     return ConstantExpr::getNUWMul(E, N);
    339   }
    340 
    341   if (StructType *STy = dyn_cast<StructType>(Ty))
    342     if (!STy->isPacked()) {
    343       unsigned NumElems = STy->getNumElements();
    344       // An empty struct has size zero.
    345       if (NumElems == 0)
    346         return ConstantExpr::getNullValue(DestTy);
    347       // Check for a struct with all members having the same size.
    348       Constant *MemberSize =
    349         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
    350       bool AllSame = true;
    351       for (unsigned i = 1; i != NumElems; ++i)
    352         if (MemberSize !=
    353             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
    354           AllSame = false;
    355           break;
    356         }
    357       if (AllSame) {
    358         Constant *N = ConstantInt::get(DestTy, NumElems);
    359         return ConstantExpr::getNUWMul(MemberSize, N);
    360       }
    361     }
    362 
    363   // Pointer size doesn't depend on the pointee type, so canonicalize them
    364   // to an arbitrary pointee.
    365   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
    366     if (!PTy->getElementType()->isIntegerTy(1))
    367       return
    368         getFoldedSizeOf(PointerType::get(IntegerType::get(PTy->getContext(), 1),
    369                                          PTy->getAddressSpace()),
    370                         DestTy, true);
    371 
    372   // If there's no interesting folding happening, bail so that we don't create
    373   // a constant that looks like it needs folding but really doesn't.
    374   if (!Folded)
    375     return 0;
    376 
    377   // Base case: Get a regular sizeof expression.
    378   Constant *C = ConstantExpr::getSizeOf(Ty);
    379   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    380                                                     DestTy, false),
    381                             C, DestTy);
    382   return C;
    383 }
    384 
    385 /// getFoldedAlignOf - Return a ConstantExpr with type DestTy for alignof
    386 /// on Ty, with any known factors factored out. If Folded is false,
    387 /// return null if no factoring was possible, to avoid endlessly
    388 /// bouncing an unfoldable expression back into the top-level folder.
    389 ///
    390 static Constant *getFoldedAlignOf(Type *Ty, Type *DestTy,
    391                                   bool Folded) {
    392   // The alignment of an array is equal to the alignment of the
    393   // array element. Note that this is not always true for vectors.
    394   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
    395     Constant *C = ConstantExpr::getAlignOf(ATy->getElementType());
    396     C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    397                                                       DestTy,
    398                                                       false),
    399                               C, DestTy);
    400     return C;
    401   }
    402 
    403   if (StructType *STy = dyn_cast<StructType>(Ty)) {
    404     // Packed structs always have an alignment of 1.
    405     if (STy->isPacked())
    406       return ConstantInt::get(DestTy, 1);
    407 
    408     // Otherwise, struct alignment is the maximum alignment of any member.
    409     // Without target data, we can't compare much, but we can check to see
    410     // if all the members have the same alignment.
    411     unsigned NumElems = STy->getNumElements();
    412     // An empty struct has minimal alignment.
    413     if (NumElems == 0)
    414       return ConstantInt::get(DestTy, 1);
    415     // Check for a struct with all members having the same alignment.
    416     Constant *MemberAlign =
    417       getFoldedAlignOf(STy->getElementType(0), DestTy, true);
    418     bool AllSame = true;
    419     for (unsigned i = 1; i != NumElems; ++i)
    420       if (MemberAlign != getFoldedAlignOf(STy->getElementType(i), DestTy, true)) {
    421         AllSame = false;
    422         break;
    423       }
    424     if (AllSame)
    425       return MemberAlign;
    426   }
    427 
    428   // Pointer alignment doesn't depend on the pointee type, so canonicalize them
    429   // to an arbitrary pointee.
    430   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
    431     if (!PTy->getElementType()->isIntegerTy(1))
    432       return
    433         getFoldedAlignOf(PointerType::get(IntegerType::get(PTy->getContext(),
    434                                                            1),
    435                                           PTy->getAddressSpace()),
    436                          DestTy, true);
    437 
    438   // If there's no interesting folding happening, bail so that we don't create
    439   // a constant that looks like it needs folding but really doesn't.
    440   if (!Folded)
    441     return 0;
    442 
    443   // Base case: Get a regular alignof expression.
    444   Constant *C = ConstantExpr::getAlignOf(Ty);
    445   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    446                                                     DestTy, false),
    447                             C, DestTy);
    448   return C;
    449 }
    450 
    451 /// getFoldedOffsetOf - Return a ConstantExpr with type DestTy for offsetof
    452 /// on Ty and FieldNo, with any known factors factored out. If Folded is false,
    453 /// return null if no factoring was possible, to avoid endlessly
    454 /// bouncing an unfoldable expression back into the top-level folder.
    455 ///
    456 static Constant *getFoldedOffsetOf(Type *Ty, Constant *FieldNo,
    457                                    Type *DestTy,
    458                                    bool Folded) {
    459   if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
    460     Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo, false,
    461                                                                 DestTy, false),
    462                                         FieldNo, DestTy);
    463     Constant *E = getFoldedSizeOf(ATy->getElementType(), DestTy, true);
    464     return ConstantExpr::getNUWMul(E, N);
    465   }
    466 
    467   if (StructType *STy = dyn_cast<StructType>(Ty))
    468     if (!STy->isPacked()) {
    469       unsigned NumElems = STy->getNumElements();
    470       // An empty struct has no members.
    471       if (NumElems == 0)
    472         return 0;
    473       // Check for a struct with all members having the same size.
    474       Constant *MemberSize =
    475         getFoldedSizeOf(STy->getElementType(0), DestTy, true);
    476       bool AllSame = true;
    477       for (unsigned i = 1; i != NumElems; ++i)
    478         if (MemberSize !=
    479             getFoldedSizeOf(STy->getElementType(i), DestTy, true)) {
    480           AllSame = false;
    481           break;
    482         }
    483       if (AllSame) {
    484         Constant *N = ConstantExpr::getCast(CastInst::getCastOpcode(FieldNo,
    485                                                                     false,
    486                                                                     DestTy,
    487                                                                     false),
    488                                             FieldNo, DestTy);
    489         return ConstantExpr::getNUWMul(MemberSize, N);
    490       }
    491     }
    492 
    493   // If there's no interesting folding happening, bail so that we don't create
    494   // a constant that looks like it needs folding but really doesn't.
    495   if (!Folded)
    496     return 0;
    497 
    498   // Base case: Get a regular offsetof expression.
    499   Constant *C = ConstantExpr::getOffsetOf(Ty, FieldNo);
    500   C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    501                                                     DestTy, false),
    502                             C, DestTy);
    503   return C;
    504 }
    505 
    506 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
    507                                             Type *DestTy) {
    508   if (isa<UndefValue>(V)) {
    509     // zext(undef) = 0, because the top bits will be zero.
    510     // sext(undef) = 0, because the top bits will all be the same.
    511     // [us]itofp(undef) = 0, because the result value is bounded.
    512     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
    513         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
    514       return Constant::getNullValue(DestTy);
    515     return UndefValue::get(DestTy);
    516   }
    517 
    518   // No compile-time operations on this type yet.
    519   if (V->getType()->isPPC_FP128Ty() || DestTy->isPPC_FP128Ty())
    520     return 0;
    521 
    522   if (V->isNullValue() && !DestTy->isX86_MMXTy())
    523     return Constant::getNullValue(DestTy);
    524 
    525   // If the cast operand is a constant expression, there's a few things we can
    526   // do to try to simplify it.
    527   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
    528     if (CE->isCast()) {
    529       // Try hard to fold cast of cast because they are often eliminable.
    530       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
    531         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
    532     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
    533       // If all of the indexes in the GEP are null values, there is no pointer
    534       // adjustment going on.  We might as well cast the source pointer.
    535       bool isAllNull = true;
    536       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
    537         if (!CE->getOperand(i)->isNullValue()) {
    538           isAllNull = false;
    539           break;
    540         }
    541       if (isAllNull)
    542         // This is casting one pointer type to another, always BitCast
    543         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
    544     }
    545   }
    546 
    547   // If the cast operand is a constant vector, perform the cast by
    548   // operating on each element. In the cast of bitcasts, the element
    549   // count may be mismatched; don't attempt to handle that here.
    550   if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
    551       DestTy->isVectorTy() &&
    552       DestTy->getVectorNumElements() == V->getType()->getVectorNumElements()) {
    553     SmallVector<Constant*, 16> res;
    554     VectorType *DestVecTy = cast<VectorType>(DestTy);
    555     Type *DstEltTy = DestVecTy->getElementType();
    556     for (unsigned i = 0, e = V->getType()->getVectorNumElements(); i != e; ++i)
    557       res.push_back(ConstantExpr::getCast(opc,
    558                                           V->getAggregateElement(i), DstEltTy));
    559     return ConstantVector::get(res);
    560   }
    561 
    562   // We actually have to do a cast now. Perform the cast according to the
    563   // opcode specified.
    564   switch (opc) {
    565   default:
    566     llvm_unreachable("Failed to cast constant expression");
    567   case Instruction::FPTrunc:
    568   case Instruction::FPExt:
    569     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
    570       bool ignored;
    571       APFloat Val = FPC->getValueAPF();
    572       Val.convert(DestTy->isHalfTy() ? APFloat::IEEEhalf :
    573                   DestTy->isFloatTy() ? APFloat::IEEEsingle :
    574                   DestTy->isDoubleTy() ? APFloat::IEEEdouble :
    575                   DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended :
    576                   DestTy->isFP128Ty() ? APFloat::IEEEquad :
    577                   APFloat::Bogus,
    578                   APFloat::rmNearestTiesToEven, &ignored);
    579       return ConstantFP::get(V->getContext(), Val);
    580     }
    581     return 0; // Can't fold.
    582   case Instruction::FPToUI:
    583   case Instruction::FPToSI:
    584     if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
    585       const APFloat &V = FPC->getValueAPF();
    586       bool ignored;
    587       uint64_t x[2];
    588       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
    589       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
    590                                 APFloat::rmTowardZero, &ignored);
    591       APInt Val(DestBitWidth, x);
    592       return ConstantInt::get(FPC->getContext(), Val);
    593     }
    594     return 0; // Can't fold.
    595   case Instruction::IntToPtr:   //always treated as unsigned
    596     if (V->isNullValue())       // Is it an integral null value?
    597       return ConstantPointerNull::get(cast<PointerType>(DestTy));
    598     return 0;                   // Other pointer types cannot be casted
    599   case Instruction::PtrToInt:   // always treated as unsigned
    600     // Is it a null pointer value?
    601     if (V->isNullValue())
    602       return ConstantInt::get(DestTy, 0);
    603     // If this is a sizeof-like expression, pull out multiplications by
    604     // known factors to expose them to subsequent folding. If it's an
    605     // alignof-like expression, factor out known factors.
    606     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
    607       if (CE->getOpcode() == Instruction::GetElementPtr &&
    608           CE->getOperand(0)->isNullValue()) {
    609         Type *Ty =
    610           cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
    611         if (CE->getNumOperands() == 2) {
    612           // Handle a sizeof-like expression.
    613           Constant *Idx = CE->getOperand(1);
    614           bool isOne = isa<ConstantInt>(Idx) && cast<ConstantInt>(Idx)->isOne();
    615           if (Constant *C = getFoldedSizeOf(Ty, DestTy, !isOne)) {
    616             Idx = ConstantExpr::getCast(CastInst::getCastOpcode(Idx, true,
    617                                                                 DestTy, false),
    618                                         Idx, DestTy);
    619             return ConstantExpr::getMul(C, Idx);
    620           }
    621         } else if (CE->getNumOperands() == 3 &&
    622                    CE->getOperand(1)->isNullValue()) {
    623           // Handle an alignof-like expression.
    624           if (StructType *STy = dyn_cast<StructType>(Ty))
    625             if (!STy->isPacked()) {
    626               ConstantInt *CI = cast<ConstantInt>(CE->getOperand(2));
    627               if (CI->isOne() &&
    628                   STy->getNumElements() == 2 &&
    629                   STy->getElementType(0)->isIntegerTy(1)) {
    630                 return getFoldedAlignOf(STy->getElementType(1), DestTy, false);
    631               }
    632             }
    633           // Handle an offsetof-like expression.
    634           if (Ty->isStructTy() || Ty->isArrayTy()) {
    635             if (Constant *C = getFoldedOffsetOf(Ty, CE->getOperand(2),
    636                                                 DestTy, false))
    637               return C;
    638           }
    639         }
    640       }
    641     // Other pointer types cannot be casted
    642     return 0;
    643   case Instruction::UIToFP:
    644   case Instruction::SIToFP:
    645     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    646       APInt api = CI->getValue();
    647       APFloat apf(APInt::getNullValue(DestTy->getPrimitiveSizeInBits()), true);
    648       (void)apf.convertFromAPInt(api,
    649                                  opc==Instruction::SIToFP,
    650                                  APFloat::rmNearestTiesToEven);
    651       return ConstantFP::get(V->getContext(), apf);
    652     }
    653     return 0;
    654   case Instruction::ZExt:
    655     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    656       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
    657       return ConstantInt::get(V->getContext(),
    658                               CI->getValue().zext(BitWidth));
    659     }
    660     return 0;
    661   case Instruction::SExt:
    662     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    663       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
    664       return ConstantInt::get(V->getContext(),
    665                               CI->getValue().sext(BitWidth));
    666     }
    667     return 0;
    668   case Instruction::Trunc: {
    669     uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
    670     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    671       return ConstantInt::get(V->getContext(),
    672                               CI->getValue().trunc(DestBitWidth));
    673     }
    674 
    675     // The input must be a constantexpr.  See if we can simplify this based on
    676     // the bytes we are demanding.  Only do this if the source and dest are an
    677     // even multiple of a byte.
    678     if ((DestBitWidth & 7) == 0 &&
    679         (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
    680       if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
    681         return Res;
    682 
    683     return 0;
    684   }
    685   case Instruction::BitCast:
    686     return FoldBitCast(V, DestTy);
    687   }
    688 }
    689 
    690 Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
    691                                               Constant *V1, Constant *V2) {
    692   // Check for i1 and vector true/false conditions.
    693   if (Cond->isNullValue()) return V2;
    694   if (Cond->isAllOnesValue()) return V1;
    695 
    696   // If the condition is a vector constant, fold the result elementwise.
    697   if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
    698     SmallVector<Constant*, 16> Result;
    699     for (unsigned i = 0, e = V1->getType()->getVectorNumElements(); i != e;++i){
    700       ConstantInt *Cond = dyn_cast<ConstantInt>(CondV->getOperand(i));
    701       if (Cond == 0) break;
    702 
    703       Constant *Res = (Cond->getZExtValue() ? V2 : V1)->getAggregateElement(i);
    704       if (Res == 0) break;
    705       Result.push_back(Res);
    706     }
    707 
    708     // If we were able to build the vector, return it.
    709     if (Result.size() == V1->getType()->getVectorNumElements())
    710       return ConstantVector::get(Result);
    711   }
    712 
    713   if (isa<UndefValue>(Cond)) {
    714     if (isa<UndefValue>(V1)) return V1;
    715     return V2;
    716   }
    717   if (isa<UndefValue>(V1)) return V2;
    718   if (isa<UndefValue>(V2)) return V1;
    719   if (V1 == V2) return V1;
    720 
    721   if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
    722     if (TrueVal->getOpcode() == Instruction::Select)
    723       if (TrueVal->getOperand(0) == Cond)
    724 	return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
    725   }
    726   if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
    727     if (FalseVal->getOpcode() == Instruction::Select)
    728       if (FalseVal->getOperand(0) == Cond)
    729 	return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
    730   }
    731 
    732   return 0;
    733 }
    734 
    735 Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
    736                                                       Constant *Idx) {
    737   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
    738     return UndefValue::get(Val->getType()->getVectorElementType());
    739   if (Val->isNullValue())  // ee(zero, x) -> zero
    740     return Constant::getNullValue(Val->getType()->getVectorElementType());
    741   // ee({w,x,y,z}, undef) -> undef
    742   if (isa<UndefValue>(Idx))
    743     return UndefValue::get(Val->getType()->getVectorElementType());
    744 
    745   if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
    746     uint64_t Index = CIdx->getZExtValue();
    747     // ee({w,x,y,z}, wrong_value) -> undef
    748     if (Index >= Val->getType()->getVectorNumElements())
    749       return UndefValue::get(Val->getType()->getVectorElementType());
    750     return Val->getAggregateElement(Index);
    751   }
    752   return 0;
    753 }
    754 
    755 Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
    756                                                      Constant *Elt,
    757                                                      Constant *Idx) {
    758   ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
    759   if (!CIdx) return 0;
    760   const APInt &IdxVal = CIdx->getValue();
    761 
    762   SmallVector<Constant*, 16> Result;
    763   for (unsigned i = 0, e = Val->getType()->getVectorNumElements(); i != e; ++i){
    764     if (i == IdxVal) {
    765       Result.push_back(Elt);
    766       continue;
    767     }
    768 
    769     if (Constant *C = Val->getAggregateElement(i))
    770       Result.push_back(C);
    771     else
    772       return 0;
    773   }
    774 
    775   return ConstantVector::get(Result);
    776 }
    777 
    778 Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1,
    779                                                      Constant *V2,
    780                                                      Constant *Mask) {
    781   unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
    782   Type *EltTy = V1->getType()->getVectorElementType();
    783 
    784   // Undefined shuffle mask -> undefined value.
    785   if (isa<UndefValue>(Mask))
    786     return UndefValue::get(VectorType::get(EltTy, MaskNumElts));
    787 
    788   // Don't break the bitcode reader hack.
    789   if (isa<ConstantExpr>(Mask)) return 0;
    790 
    791   unsigned SrcNumElts = V1->getType()->getVectorNumElements();
    792 
    793   // Loop over the shuffle mask, evaluating each element.
    794   SmallVector<Constant*, 32> Result;
    795   for (unsigned i = 0; i != MaskNumElts; ++i) {
    796     int Elt = ShuffleVectorInst::getMaskValue(Mask, i);
    797     if (Elt == -1) {
    798       Result.push_back(UndefValue::get(EltTy));
    799       continue;
    800     }
    801     Constant *InElt;
    802     if (unsigned(Elt) >= SrcNumElts*2)
    803       InElt = UndefValue::get(EltTy);
    804     else if (unsigned(Elt) >= SrcNumElts)
    805       InElt = V2->getAggregateElement(Elt - SrcNumElts);
    806     else
    807       InElt = V1->getAggregateElement(Elt);
    808     if (InElt == 0) return 0;
    809     Result.push_back(InElt);
    810   }
    811 
    812   return ConstantVector::get(Result);
    813 }
    814 
    815 Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
    816                                                     ArrayRef<unsigned> Idxs) {
    817   // Base case: no indices, so return the entire value.
    818   if (Idxs.empty())
    819     return Agg;
    820 
    821   if (Constant *C = Agg->getAggregateElement(Idxs[0]))
    822     return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
    823 
    824   return 0;
    825 }
    826 
    827 Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
    828                                                    Constant *Val,
    829                                                    ArrayRef<unsigned> Idxs) {
    830   // Base case: no indices, so replace the entire value.
    831   if (Idxs.empty())
    832     return Val;
    833 
    834   unsigned NumElts;
    835   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
    836     NumElts = ST->getNumElements();
    837   else if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
    838     NumElts = AT->getNumElements();
    839   else
    840     NumElts = AT->getVectorNumElements();
    841 
    842   SmallVector<Constant*, 32> Result;
    843   for (unsigned i = 0; i != NumElts; ++i) {
    844     Constant *C = Agg->getAggregateElement(i);
    845     if (C == 0) return 0;
    846 
    847     if (Idxs[0] == i)
    848       C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
    849 
    850     Result.push_back(C);
    851   }
    852 
    853   if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
    854     return ConstantStruct::get(ST, Result);
    855   if (ArrayType *AT = dyn_cast<ArrayType>(Agg->getType()))
    856     return ConstantArray::get(AT, Result);
    857   return ConstantVector::get(Result);
    858 }
    859 
    860 
    861 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
    862                                               Constant *C1, Constant *C2) {
    863   // No compile-time operations on this type yet.
    864   if (C1->getType()->isPPC_FP128Ty())
    865     return 0;
    866 
    867   // Handle UndefValue up front.
    868   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
    869     switch (Opcode) {
    870     case Instruction::Xor:
    871       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
    872         // Handle undef ^ undef -> 0 special case. This is a common
    873         // idiom (misuse).
    874         return Constant::getNullValue(C1->getType());
    875       // Fallthrough
    876     case Instruction::Add:
    877     case Instruction::Sub:
    878       return UndefValue::get(C1->getType());
    879     case Instruction::And:
    880       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
    881         return C1;
    882       return Constant::getNullValue(C1->getType());   // undef & X -> 0
    883     case Instruction::Mul: {
    884       ConstantInt *CI;
    885       // X * undef -> undef   if X is odd or undef
    886       if (((CI = dyn_cast<ConstantInt>(C1)) && CI->getValue()[0]) ||
    887           ((CI = dyn_cast<ConstantInt>(C2)) && CI->getValue()[0]) ||
    888           (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
    889         return UndefValue::get(C1->getType());
    890 
    891       // X * undef -> 0       otherwise
    892       return Constant::getNullValue(C1->getType());
    893     }
    894     case Instruction::UDiv:
    895     case Instruction::SDiv:
    896       // undef / 1 -> undef
    897       if (Opcode == Instruction::UDiv || Opcode == Instruction::SDiv)
    898         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2))
    899           if (CI2->isOne())
    900             return C1;
    901       // FALL THROUGH
    902     case Instruction::URem:
    903     case Instruction::SRem:
    904       if (!isa<UndefValue>(C2))                    // undef / X -> 0
    905         return Constant::getNullValue(C1->getType());
    906       return C2;                                   // X / undef -> undef
    907     case Instruction::Or:                          // X | undef -> -1
    908       if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
    909         return C1;
    910       return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
    911     case Instruction::LShr:
    912       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
    913         return C1;                                  // undef lshr undef -> undef
    914       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
    915                                                     // undef lshr X -> 0
    916     case Instruction::AShr:
    917       if (!isa<UndefValue>(C2))                     // undef ashr X --> all ones
    918         return Constant::getAllOnesValue(C1->getType());
    919       else if (isa<UndefValue>(C1))
    920         return C1;                                  // undef ashr undef -> undef
    921       else
    922         return C1;                                  // X ashr undef --> X
    923     case Instruction::Shl:
    924       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
    925         return C1;                                  // undef shl undef -> undef
    926       // undef << X -> 0   or   X << undef -> 0
    927       return Constant::getNullValue(C1->getType());
    928     }
    929   }
    930 
    931   // Handle simplifications when the RHS is a constant int.
    932   if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
    933     switch (Opcode) {
    934     case Instruction::Add:
    935       if (CI2->equalsInt(0)) return C1;                         // X + 0 == X
    936       break;
    937     case Instruction::Sub:
    938       if (CI2->equalsInt(0)) return C1;                         // X - 0 == X
    939       break;
    940     case Instruction::Mul:
    941       if (CI2->equalsInt(0)) return C2;                         // X * 0 == 0
    942       if (CI2->equalsInt(1))
    943         return C1;                                              // X * 1 == X
    944       break;
    945     case Instruction::UDiv:
    946     case Instruction::SDiv:
    947       if (CI2->equalsInt(1))
    948         return C1;                                            // X / 1 == X
    949       if (CI2->equalsInt(0))
    950         return UndefValue::get(CI2->getType());               // X / 0 == undef
    951       break;
    952     case Instruction::URem:
    953     case Instruction::SRem:
    954       if (CI2->equalsInt(1))
    955         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
    956       if (CI2->equalsInt(0))
    957         return UndefValue::get(CI2->getType());               // X % 0 == undef
    958       break;
    959     case Instruction::And:
    960       if (CI2->isZero()) return C2;                           // X & 0 == 0
    961       if (CI2->isAllOnesValue())
    962         return C1;                                            // X & -1 == X
    963 
    964       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
    965         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
    966         if (CE1->getOpcode() == Instruction::ZExt) {
    967           unsigned DstWidth = CI2->getType()->getBitWidth();
    968           unsigned SrcWidth =
    969             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
    970           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
    971           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
    972             return C1;
    973         }
    974 
    975         // If and'ing the address of a global with a constant, fold it.
    976         if (CE1->getOpcode() == Instruction::PtrToInt &&
    977             isa<GlobalValue>(CE1->getOperand(0))) {
    978           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
    979 
    980           // Functions are at least 4-byte aligned.
    981           unsigned GVAlign = GV->getAlignment();
    982           if (isa<Function>(GV))
    983             GVAlign = std::max(GVAlign, 4U);
    984 
    985           if (GVAlign > 1) {
    986             unsigned DstWidth = CI2->getType()->getBitWidth();
    987             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
    988             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
    989 
    990             // If checking bits we know are clear, return zero.
    991             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
    992               return Constant::getNullValue(CI2->getType());
    993           }
    994         }
    995       }
    996       break;
    997     case Instruction::Or:
    998       if (CI2->equalsInt(0)) return C1;    // X | 0 == X
    999       if (CI2->isAllOnesValue())
   1000         return C2;                         // X | -1 == -1
   1001       break;
   1002     case Instruction::Xor:
   1003       if (CI2->equalsInt(0)) return C1;    // X ^ 0 == X
   1004 
   1005       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
   1006         switch (CE1->getOpcode()) {
   1007         default: break;
   1008         case Instruction::ICmp:
   1009         case Instruction::FCmp:
   1010           // cmp pred ^ true -> cmp !pred
   1011           assert(CI2->equalsInt(1));
   1012           CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
   1013           pred = CmpInst::getInversePredicate(pred);
   1014           return ConstantExpr::getCompare(pred, CE1->getOperand(0),
   1015                                           CE1->getOperand(1));
   1016         }
   1017       }
   1018       break;
   1019     case Instruction::AShr:
   1020       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
   1021       if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
   1022         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
   1023           return ConstantExpr::getLShr(C1, C2);
   1024       break;
   1025     }
   1026   } else if (isa<ConstantInt>(C1)) {
   1027     // If C1 is a ConstantInt and C2 is not, swap the operands.
   1028     if (Instruction::isCommutative(Opcode))
   1029       return ConstantExpr::get(Opcode, C2, C1);
   1030   }
   1031 
   1032   // At this point we know neither constant is an UndefValue.
   1033   if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
   1034     if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
   1035       const APInt &C1V = CI1->getValue();
   1036       const APInt &C2V = CI2->getValue();
   1037       switch (Opcode) {
   1038       default:
   1039         break;
   1040       case Instruction::Add:
   1041         return ConstantInt::get(CI1->getContext(), C1V + C2V);
   1042       case Instruction::Sub:
   1043         return ConstantInt::get(CI1->getContext(), C1V - C2V);
   1044       case Instruction::Mul:
   1045         return ConstantInt::get(CI1->getContext(), C1V * C2V);
   1046       case Instruction::UDiv:
   1047         assert(!CI2->isNullValue() && "Div by zero handled above");
   1048         return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
   1049       case Instruction::SDiv:
   1050         assert(!CI2->isNullValue() && "Div by zero handled above");
   1051         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
   1052           return UndefValue::get(CI1->getType());   // MIN_INT / -1 -> undef
   1053         return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
   1054       case Instruction::URem:
   1055         assert(!CI2->isNullValue() && "Div by zero handled above");
   1056         return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
   1057       case Instruction::SRem:
   1058         assert(!CI2->isNullValue() && "Div by zero handled above");
   1059         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
   1060           return UndefValue::get(CI1->getType());   // MIN_INT % -1 -> undef
   1061         return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
   1062       case Instruction::And:
   1063         return ConstantInt::get(CI1->getContext(), C1V & C2V);
   1064       case Instruction::Or:
   1065         return ConstantInt::get(CI1->getContext(), C1V | C2V);
   1066       case Instruction::Xor:
   1067         return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
   1068       case Instruction::Shl: {
   1069         uint32_t shiftAmt = C2V.getZExtValue();
   1070         if (shiftAmt < C1V.getBitWidth())
   1071           return ConstantInt::get(CI1->getContext(), C1V.shl(shiftAmt));
   1072         else
   1073           return UndefValue::get(C1->getType()); // too big shift is undef
   1074       }
   1075       case Instruction::LShr: {
   1076         uint32_t shiftAmt = C2V.getZExtValue();
   1077         if (shiftAmt < C1V.getBitWidth())
   1078           return ConstantInt::get(CI1->getContext(), C1V.lshr(shiftAmt));
   1079         else
   1080           return UndefValue::get(C1->getType()); // too big shift is undef
   1081       }
   1082       case Instruction::AShr: {
   1083         uint32_t shiftAmt = C2V.getZExtValue();
   1084         if (shiftAmt < C1V.getBitWidth())
   1085           return ConstantInt::get(CI1->getContext(), C1V.ashr(shiftAmt));
   1086         else
   1087           return UndefValue::get(C1->getType()); // too big shift is undef
   1088       }
   1089       }
   1090     }
   1091 
   1092     switch (Opcode) {
   1093     case Instruction::SDiv:
   1094     case Instruction::UDiv:
   1095     case Instruction::URem:
   1096     case Instruction::SRem:
   1097     case Instruction::LShr:
   1098     case Instruction::AShr:
   1099     case Instruction::Shl:
   1100       if (CI1->equalsInt(0)) return C1;
   1101       break;
   1102     default:
   1103       break;
   1104     }
   1105   } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
   1106     if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
   1107       APFloat C1V = CFP1->getValueAPF();
   1108       APFloat C2V = CFP2->getValueAPF();
   1109       APFloat C3V = C1V;  // copy for modification
   1110       switch (Opcode) {
   1111       default:
   1112         break;
   1113       case Instruction::FAdd:
   1114         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
   1115         return ConstantFP::get(C1->getContext(), C3V);
   1116       case Instruction::FSub:
   1117         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
   1118         return ConstantFP::get(C1->getContext(), C3V);
   1119       case Instruction::FMul:
   1120         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
   1121         return ConstantFP::get(C1->getContext(), C3V);
   1122       case Instruction::FDiv:
   1123         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
   1124         return ConstantFP::get(C1->getContext(), C3V);
   1125       case Instruction::FRem:
   1126         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
   1127         return ConstantFP::get(C1->getContext(), C3V);
   1128       }
   1129     }
   1130   } else if (VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
   1131     // Perform elementwise folding.
   1132     SmallVector<Constant*, 16> Result;
   1133     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
   1134       Constant *LHS = C1->getAggregateElement(i);
   1135       Constant *RHS = C2->getAggregateElement(i);
   1136       if (LHS == 0 || RHS == 0) break;
   1137 
   1138       Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
   1139     }
   1140 
   1141     if (Result.size() == VTy->getNumElements())
   1142       return ConstantVector::get(Result);
   1143   }
   1144 
   1145   if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
   1146     // There are many possible foldings we could do here.  We should probably
   1147     // at least fold add of a pointer with an integer into the appropriate
   1148     // getelementptr.  This will improve alias analysis a bit.
   1149 
   1150     // Given ((a + b) + c), if (b + c) folds to something interesting, return
   1151     // (a + (b + c)).
   1152     if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
   1153       Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
   1154       if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
   1155         return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
   1156     }
   1157   } else if (isa<ConstantExpr>(C2)) {
   1158     // If C2 is a constant expr and C1 isn't, flop them around and fold the
   1159     // other way if possible.
   1160     if (Instruction::isCommutative(Opcode))
   1161       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
   1162   }
   1163 
   1164   // i1 can be simplified in many cases.
   1165   if (C1->getType()->isIntegerTy(1)) {
   1166     switch (Opcode) {
   1167     case Instruction::Add:
   1168     case Instruction::Sub:
   1169       return ConstantExpr::getXor(C1, C2);
   1170     case Instruction::Mul:
   1171       return ConstantExpr::getAnd(C1, C2);
   1172     case Instruction::Shl:
   1173     case Instruction::LShr:
   1174     case Instruction::AShr:
   1175       // We can assume that C2 == 0.  If it were one the result would be
   1176       // undefined because the shift value is as large as the bitwidth.
   1177       return C1;
   1178     case Instruction::SDiv:
   1179     case Instruction::UDiv:
   1180       // We can assume that C2 == 1.  If it were zero the result would be
   1181       // undefined through division by zero.
   1182       return C1;
   1183     case Instruction::URem:
   1184     case Instruction::SRem:
   1185       // We can assume that C2 == 1.  If it were zero the result would be
   1186       // undefined through division by zero.
   1187       return ConstantInt::getFalse(C1->getContext());
   1188     default:
   1189       break;
   1190     }
   1191   }
   1192 
   1193   // We don't know how to fold this.
   1194   return 0;
   1195 }
   1196 
   1197 /// isZeroSizedType - This type is zero sized if its an array or structure of
   1198 /// zero sized types.  The only leaf zero sized type is an empty structure.
   1199 static bool isMaybeZeroSizedType(Type *Ty) {
   1200   if (StructType *STy = dyn_cast<StructType>(Ty)) {
   1201     if (STy->isOpaque()) return true;  // Can't say.
   1202 
   1203     // If all of elements have zero size, this does too.
   1204     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
   1205       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
   1206     return true;
   1207 
   1208   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
   1209     return isMaybeZeroSizedType(ATy->getElementType());
   1210   }
   1211   return false;
   1212 }
   1213 
   1214 /// IdxCompare - Compare the two constants as though they were getelementptr
   1215 /// indices.  This allows coersion of the types to be the same thing.
   1216 ///
   1217 /// If the two constants are the "same" (after coersion), return 0.  If the
   1218 /// first is less than the second, return -1, if the second is less than the
   1219 /// first, return 1.  If the constants are not integral, return -2.
   1220 ///
   1221 static int IdxCompare(Constant *C1, Constant *C2, Type *ElTy) {
   1222   if (C1 == C2) return 0;
   1223 
   1224   // Ok, we found a different index.  If they are not ConstantInt, we can't do
   1225   // anything with them.
   1226   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
   1227     return -2; // don't know!
   1228 
   1229   // Ok, we have two differing integer indices.  Sign extend them to be the same
   1230   // type.  Long is always big enough, so we use it.
   1231   if (!C1->getType()->isIntegerTy(64))
   1232     C1 = ConstantExpr::getSExt(C1, Type::getInt64Ty(C1->getContext()));
   1233 
   1234   if (!C2->getType()->isIntegerTy(64))
   1235     C2 = ConstantExpr::getSExt(C2, Type::getInt64Ty(C1->getContext()));
   1236 
   1237   if (C1 == C2) return 0;  // They are equal
   1238 
   1239   // If the type being indexed over is really just a zero sized type, there is
   1240   // no pointer difference being made here.
   1241   if (isMaybeZeroSizedType(ElTy))
   1242     return -2; // dunno.
   1243 
   1244   // If they are really different, now that they are the same type, then we
   1245   // found a difference!
   1246   if (cast<ConstantInt>(C1)->getSExtValue() <
   1247       cast<ConstantInt>(C2)->getSExtValue())
   1248     return -1;
   1249   else
   1250     return 1;
   1251 }
   1252 
   1253 /// evaluateFCmpRelation - This function determines if there is anything we can
   1254 /// decide about the two constants provided.  This doesn't need to handle simple
   1255 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
   1256 /// If we can determine that the two constants have a particular relation to
   1257 /// each other, we should return the corresponding FCmpInst predicate,
   1258 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
   1259 /// ConstantFoldCompareInstruction.
   1260 ///
   1261 /// To simplify this code we canonicalize the relation so that the first
   1262 /// operand is always the most "complex" of the two.  We consider ConstantFP
   1263 /// to be the simplest, and ConstantExprs to be the most complex.
   1264 static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
   1265   assert(V1->getType() == V2->getType() &&
   1266          "Cannot compare values of different types!");
   1267 
   1268   // No compile-time operations on this type yet.
   1269   if (V1->getType()->isPPC_FP128Ty())
   1270     return FCmpInst::BAD_FCMP_PREDICATE;
   1271 
   1272   // Handle degenerate case quickly
   1273   if (V1 == V2) return FCmpInst::FCMP_OEQ;
   1274 
   1275   if (!isa<ConstantExpr>(V1)) {
   1276     if (!isa<ConstantExpr>(V2)) {
   1277       // We distilled thisUse the standard constant folder for a few cases
   1278       ConstantInt *R = 0;
   1279       R = dyn_cast<ConstantInt>(
   1280                       ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
   1281       if (R && !R->isZero())
   1282         return FCmpInst::FCMP_OEQ;
   1283       R = dyn_cast<ConstantInt>(
   1284                       ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
   1285       if (R && !R->isZero())
   1286         return FCmpInst::FCMP_OLT;
   1287       R = dyn_cast<ConstantInt>(
   1288                       ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
   1289       if (R && !R->isZero())
   1290         return FCmpInst::FCMP_OGT;
   1291 
   1292       // Nothing more we can do
   1293       return FCmpInst::BAD_FCMP_PREDICATE;
   1294     }
   1295 
   1296     // If the first operand is simple and second is ConstantExpr, swap operands.
   1297     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
   1298     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
   1299       return FCmpInst::getSwappedPredicate(SwappedRelation);
   1300   } else {
   1301     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
   1302     // constantexpr or a simple constant.
   1303     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
   1304     switch (CE1->getOpcode()) {
   1305     case Instruction::FPTrunc:
   1306     case Instruction::FPExt:
   1307     case Instruction::UIToFP:
   1308     case Instruction::SIToFP:
   1309       // We might be able to do something with these but we don't right now.
   1310       break;
   1311     default:
   1312       break;
   1313     }
   1314   }
   1315   // There are MANY other foldings that we could perform here.  They will
   1316   // probably be added on demand, as they seem needed.
   1317   return FCmpInst::BAD_FCMP_PREDICATE;
   1318 }
   1319 
   1320 /// evaluateICmpRelation - This function determines if there is anything we can
   1321 /// decide about the two constants provided.  This doesn't need to handle simple
   1322 /// things like integer comparisons, but should instead handle ConstantExprs
   1323 /// and GlobalValues.  If we can determine that the two constants have a
   1324 /// particular relation to each other, we should return the corresponding ICmp
   1325 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
   1326 ///
   1327 /// To simplify this code we canonicalize the relation so that the first
   1328 /// operand is always the most "complex" of the two.  We consider simple
   1329 /// constants (like ConstantInt) to be the simplest, followed by
   1330 /// GlobalValues, followed by ConstantExpr's (the most complex).
   1331 ///
   1332 static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
   1333                                                 bool isSigned) {
   1334   assert(V1->getType() == V2->getType() &&
   1335          "Cannot compare different types of values!");
   1336   if (V1 == V2) return ICmpInst::ICMP_EQ;
   1337 
   1338   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
   1339       !isa<BlockAddress>(V1)) {
   1340     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
   1341         !isa<BlockAddress>(V2)) {
   1342       // We distilled this down to a simple case, use the standard constant
   1343       // folder.
   1344       ConstantInt *R = 0;
   1345       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
   1346       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
   1347       if (R && !R->isZero())
   1348         return pred;
   1349       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
   1350       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
   1351       if (R && !R->isZero())
   1352         return pred;
   1353       pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1354       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
   1355       if (R && !R->isZero())
   1356         return pred;
   1357 
   1358       // If we couldn't figure it out, bail.
   1359       return ICmpInst::BAD_ICMP_PREDICATE;
   1360     }
   1361 
   1362     // If the first operand is simple, swap operands.
   1363     ICmpInst::Predicate SwappedRelation =
   1364       evaluateICmpRelation(V2, V1, isSigned);
   1365     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
   1366       return ICmpInst::getSwappedPredicate(SwappedRelation);
   1367 
   1368   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
   1369     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
   1370       ICmpInst::Predicate SwappedRelation =
   1371         evaluateICmpRelation(V2, V1, isSigned);
   1372       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
   1373         return ICmpInst::getSwappedPredicate(SwappedRelation);
   1374       return ICmpInst::BAD_ICMP_PREDICATE;
   1375     }
   1376 
   1377     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
   1378     // constant (which, since the types must match, means that it's a
   1379     // ConstantPointerNull).
   1380     if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
   1381       // Don't try to decide equality of aliases.
   1382       if (!isa<GlobalAlias>(GV) && !isa<GlobalAlias>(GV2))
   1383         if (!GV->hasExternalWeakLinkage() || !GV2->hasExternalWeakLinkage())
   1384           return ICmpInst::ICMP_NE;
   1385     } else if (isa<BlockAddress>(V2)) {
   1386       return ICmpInst::ICMP_NE; // Globals never equal labels.
   1387     } else {
   1388       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
   1389       // GlobalVals can never be null unless they have external weak linkage.
   1390       // We don't try to evaluate aliases here.
   1391       if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV))
   1392         return ICmpInst::ICMP_NE;
   1393     }
   1394   } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
   1395     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
   1396       ICmpInst::Predicate SwappedRelation =
   1397         evaluateICmpRelation(V2, V1, isSigned);
   1398       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
   1399         return ICmpInst::getSwappedPredicate(SwappedRelation);
   1400       return ICmpInst::BAD_ICMP_PREDICATE;
   1401     }
   1402 
   1403     // Now we know that the RHS is a GlobalValue, BlockAddress or simple
   1404     // constant (which, since the types must match, means that it is a
   1405     // ConstantPointerNull).
   1406     if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
   1407       // Block address in another function can't equal this one, but block
   1408       // addresses in the current function might be the same if blocks are
   1409       // empty.
   1410       if (BA2->getFunction() != BA->getFunction())
   1411         return ICmpInst::ICMP_NE;
   1412     } else {
   1413       // Block addresses aren't null, don't equal the address of globals.
   1414       assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
   1415              "Canonicalization guarantee!");
   1416       return ICmpInst::ICMP_NE;
   1417     }
   1418   } else {
   1419     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
   1420     // constantexpr, a global, block address, or a simple constant.
   1421     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
   1422     Constant *CE1Op0 = CE1->getOperand(0);
   1423 
   1424     switch (CE1->getOpcode()) {
   1425     case Instruction::Trunc:
   1426     case Instruction::FPTrunc:
   1427     case Instruction::FPExt:
   1428     case Instruction::FPToUI:
   1429     case Instruction::FPToSI:
   1430       break; // We can't evaluate floating point casts or truncations.
   1431 
   1432     case Instruction::UIToFP:
   1433     case Instruction::SIToFP:
   1434     case Instruction::BitCast:
   1435     case Instruction::ZExt:
   1436     case Instruction::SExt:
   1437       // If the cast is not actually changing bits, and the second operand is a
   1438       // null pointer, do the comparison with the pre-casted value.
   1439       if (V2->isNullValue() &&
   1440           (CE1->getType()->isPointerTy() || CE1->getType()->isIntegerTy())) {
   1441         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
   1442         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
   1443         return evaluateICmpRelation(CE1Op0,
   1444                                     Constant::getNullValue(CE1Op0->getType()),
   1445                                     isSigned);
   1446       }
   1447       break;
   1448 
   1449     case Instruction::GetElementPtr:
   1450       // Ok, since this is a getelementptr, we know that the constant has a
   1451       // pointer type.  Check the various cases.
   1452       if (isa<ConstantPointerNull>(V2)) {
   1453         // If we are comparing a GEP to a null pointer, check to see if the base
   1454         // of the GEP equals the null pointer.
   1455         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
   1456           if (GV->hasExternalWeakLinkage())
   1457             // Weak linkage GVals could be zero or not. We're comparing that
   1458             // to null pointer so its greater-or-equal
   1459             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
   1460           else
   1461             // If its not weak linkage, the GVal must have a non-zero address
   1462             // so the result is greater-than
   1463             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1464         } else if (isa<ConstantPointerNull>(CE1Op0)) {
   1465           // If we are indexing from a null pointer, check to see if we have any
   1466           // non-zero indices.
   1467           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
   1468             if (!CE1->getOperand(i)->isNullValue())
   1469               // Offsetting from null, must not be equal.
   1470               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1471           // Only zero indexes from null, must still be zero.
   1472           return ICmpInst::ICMP_EQ;
   1473         }
   1474         // Otherwise, we can't really say if the first operand is null or not.
   1475       } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
   1476         if (isa<ConstantPointerNull>(CE1Op0)) {
   1477           if (GV2->hasExternalWeakLinkage())
   1478             // Weak linkage GVals could be zero or not. We're comparing it to
   1479             // a null pointer, so its less-or-equal
   1480             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
   1481           else
   1482             // If its not weak linkage, the GVal must have a non-zero address
   1483             // so the result is less-than
   1484             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
   1485         } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
   1486           if (GV == GV2) {
   1487             // If this is a getelementptr of the same global, then it must be
   1488             // different.  Because the types must match, the getelementptr could
   1489             // only have at most one index, and because we fold getelementptr's
   1490             // with a single zero index, it must be nonzero.
   1491             assert(CE1->getNumOperands() == 2 &&
   1492                    !CE1->getOperand(1)->isNullValue() &&
   1493                    "Surprising getelementptr!");
   1494             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1495           } else {
   1496             // If they are different globals, we don't know what the value is,
   1497             // but they can't be equal.
   1498             return ICmpInst::ICMP_NE;
   1499           }
   1500         }
   1501       } else {
   1502         ConstantExpr *CE2 = cast<ConstantExpr>(V2);
   1503         Constant *CE2Op0 = CE2->getOperand(0);
   1504 
   1505         // There are MANY other foldings that we could perform here.  They will
   1506         // probably be added on demand, as they seem needed.
   1507         switch (CE2->getOpcode()) {
   1508         default: break;
   1509         case Instruction::GetElementPtr:
   1510           // By far the most common case to handle is when the base pointers are
   1511           // obviously to the same or different globals.
   1512           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
   1513             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
   1514               return ICmpInst::ICMP_NE;
   1515             // Ok, we know that both getelementptr instructions are based on the
   1516             // same global.  From this, we can precisely determine the relative
   1517             // ordering of the resultant pointers.
   1518             unsigned i = 1;
   1519 
   1520             // The logic below assumes that the result of the comparison
   1521             // can be determined by finding the first index that differs.
   1522             // This doesn't work if there is over-indexing in any
   1523             // subsequent indices, so check for that case first.
   1524             if (!CE1->isGEPWithNoNotionalOverIndexing() ||
   1525                 !CE2->isGEPWithNoNotionalOverIndexing())
   1526                return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
   1527 
   1528             // Compare all of the operands the GEP's have in common.
   1529             gep_type_iterator GTI = gep_type_begin(CE1);
   1530             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
   1531                  ++i, ++GTI)
   1532               switch (IdxCompare(CE1->getOperand(i),
   1533                                  CE2->getOperand(i), GTI.getIndexedType())) {
   1534               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
   1535               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
   1536               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
   1537               }
   1538 
   1539             // Ok, we ran out of things they have in common.  If any leftovers
   1540             // are non-zero then we have a difference, otherwise we are equal.
   1541             for (; i < CE1->getNumOperands(); ++i)
   1542               if (!CE1->getOperand(i)->isNullValue()) {
   1543                 if (isa<ConstantInt>(CE1->getOperand(i)))
   1544                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
   1545                 else
   1546                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
   1547               }
   1548 
   1549             for (; i < CE2->getNumOperands(); ++i)
   1550               if (!CE2->getOperand(i)->isNullValue()) {
   1551                 if (isa<ConstantInt>(CE2->getOperand(i)))
   1552                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
   1553                 else
   1554                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
   1555               }
   1556             return ICmpInst::ICMP_EQ;
   1557           }
   1558         }
   1559       }
   1560     default:
   1561       break;
   1562     }
   1563   }
   1564 
   1565   return ICmpInst::BAD_ICMP_PREDICATE;
   1566 }
   1567 
   1568 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred,
   1569                                                Constant *C1, Constant *C2) {
   1570   Type *ResultTy;
   1571   if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
   1572     ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
   1573                                VT->getNumElements());
   1574   else
   1575     ResultTy = Type::getInt1Ty(C1->getContext());
   1576 
   1577   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
   1578   if (pred == FCmpInst::FCMP_FALSE)
   1579     return Constant::getNullValue(ResultTy);
   1580 
   1581   if (pred == FCmpInst::FCMP_TRUE)
   1582     return Constant::getAllOnesValue(ResultTy);
   1583 
   1584   // Handle some degenerate cases first
   1585   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
   1586     // For EQ and NE, we can always pick a value for the undef to make the
   1587     // predicate pass or fail, so we can return undef.
   1588     // Also, if both operands are undef, we can return undef.
   1589     if (ICmpInst::isEquality(ICmpInst::Predicate(pred)) ||
   1590         (isa<UndefValue>(C1) && isa<UndefValue>(C2)))
   1591       return UndefValue::get(ResultTy);
   1592     // Otherwise, pick the same value as the non-undef operand, and fold
   1593     // it to true or false.
   1594     return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(pred));
   1595   }
   1596 
   1597   // No compile-time operations on this type yet.
   1598   if (C1->getType()->isPPC_FP128Ty())
   1599     return 0;
   1600 
   1601   // icmp eq/ne(null,GV) -> false/true
   1602   if (C1->isNullValue()) {
   1603     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
   1604       // Don't try to evaluate aliases.  External weak GV can be null.
   1605       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
   1606         if (pred == ICmpInst::ICMP_EQ)
   1607           return ConstantInt::getFalse(C1->getContext());
   1608         else if (pred == ICmpInst::ICMP_NE)
   1609           return ConstantInt::getTrue(C1->getContext());
   1610       }
   1611   // icmp eq/ne(GV,null) -> false/true
   1612   } else if (C2->isNullValue()) {
   1613     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
   1614       // Don't try to evaluate aliases.  External weak GV can be null.
   1615       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
   1616         if (pred == ICmpInst::ICMP_EQ)
   1617           return ConstantInt::getFalse(C1->getContext());
   1618         else if (pred == ICmpInst::ICMP_NE)
   1619           return ConstantInt::getTrue(C1->getContext());
   1620       }
   1621   }
   1622 
   1623   // If the comparison is a comparison between two i1's, simplify it.
   1624   if (C1->getType()->isIntegerTy(1)) {
   1625     switch(pred) {
   1626     case ICmpInst::ICMP_EQ:
   1627       if (isa<ConstantInt>(C2))
   1628         return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
   1629       return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
   1630     case ICmpInst::ICMP_NE:
   1631       return ConstantExpr::getXor(C1, C2);
   1632     default:
   1633       break;
   1634     }
   1635   }
   1636 
   1637   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
   1638     APInt V1 = cast<ConstantInt>(C1)->getValue();
   1639     APInt V2 = cast<ConstantInt>(C2)->getValue();
   1640     switch (pred) {
   1641     default: llvm_unreachable("Invalid ICmp Predicate");
   1642     case ICmpInst::ICMP_EQ:  return ConstantInt::get(ResultTy, V1 == V2);
   1643     case ICmpInst::ICMP_NE:  return ConstantInt::get(ResultTy, V1 != V2);
   1644     case ICmpInst::ICMP_SLT: return ConstantInt::get(ResultTy, V1.slt(V2));
   1645     case ICmpInst::ICMP_SGT: return ConstantInt::get(ResultTy, V1.sgt(V2));
   1646     case ICmpInst::ICMP_SLE: return ConstantInt::get(ResultTy, V1.sle(V2));
   1647     case ICmpInst::ICMP_SGE: return ConstantInt::get(ResultTy, V1.sge(V2));
   1648     case ICmpInst::ICMP_ULT: return ConstantInt::get(ResultTy, V1.ult(V2));
   1649     case ICmpInst::ICMP_UGT: return ConstantInt::get(ResultTy, V1.ugt(V2));
   1650     case ICmpInst::ICMP_ULE: return ConstantInt::get(ResultTy, V1.ule(V2));
   1651     case ICmpInst::ICMP_UGE: return ConstantInt::get(ResultTy, V1.uge(V2));
   1652     }
   1653   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
   1654     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
   1655     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
   1656     APFloat::cmpResult R = C1V.compare(C2V);
   1657     switch (pred) {
   1658     default: llvm_unreachable("Invalid FCmp Predicate");
   1659     case FCmpInst::FCMP_FALSE: return Constant::getNullValue(ResultTy);
   1660     case FCmpInst::FCMP_TRUE:  return Constant::getAllOnesValue(ResultTy);
   1661     case FCmpInst::FCMP_UNO:
   1662       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered);
   1663     case FCmpInst::FCMP_ORD:
   1664       return ConstantInt::get(ResultTy, R!=APFloat::cmpUnordered);
   1665     case FCmpInst::FCMP_UEQ:
   1666       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
   1667                                         R==APFloat::cmpEqual);
   1668     case FCmpInst::FCMP_OEQ:
   1669       return ConstantInt::get(ResultTy, R==APFloat::cmpEqual);
   1670     case FCmpInst::FCMP_UNE:
   1671       return ConstantInt::get(ResultTy, R!=APFloat::cmpEqual);
   1672     case FCmpInst::FCMP_ONE:
   1673       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
   1674                                         R==APFloat::cmpGreaterThan);
   1675     case FCmpInst::FCMP_ULT:
   1676       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
   1677                                         R==APFloat::cmpLessThan);
   1678     case FCmpInst::FCMP_OLT:
   1679       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan);
   1680     case FCmpInst::FCMP_UGT:
   1681       return ConstantInt::get(ResultTy, R==APFloat::cmpUnordered ||
   1682                                         R==APFloat::cmpGreaterThan);
   1683     case FCmpInst::FCMP_OGT:
   1684       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan);
   1685     case FCmpInst::FCMP_ULE:
   1686       return ConstantInt::get(ResultTy, R!=APFloat::cmpGreaterThan);
   1687     case FCmpInst::FCMP_OLE:
   1688       return ConstantInt::get(ResultTy, R==APFloat::cmpLessThan ||
   1689                                         R==APFloat::cmpEqual);
   1690     case FCmpInst::FCMP_UGE:
   1691       return ConstantInt::get(ResultTy, R!=APFloat::cmpLessThan);
   1692     case FCmpInst::FCMP_OGE:
   1693       return ConstantInt::get(ResultTy, R==APFloat::cmpGreaterThan ||
   1694                                         R==APFloat::cmpEqual);
   1695     }
   1696   } else if (C1->getType()->isVectorTy()) {
   1697     // If we can constant fold the comparison of each element, constant fold
   1698     // the whole vector comparison.
   1699     SmallVector<Constant*, 4> ResElts;
   1700     // Compare the elements, producing an i1 result or constant expr.
   1701     for (unsigned i = 0, e = C1->getType()->getVectorNumElements(); i != e;++i){
   1702       Constant *C1E = C1->getAggregateElement(i);
   1703       Constant *C2E = C2->getAggregateElement(i);
   1704       if (C1E == 0 || C2E == 0) break;
   1705 
   1706       ResElts.push_back(ConstantExpr::getCompare(pred, C1E, C2E));
   1707     }
   1708 
   1709     if (ResElts.size() == C1->getType()->getVectorNumElements())
   1710       return ConstantVector::get(ResElts);
   1711   }
   1712 
   1713   if (C1->getType()->isFloatingPointTy()) {
   1714     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
   1715     switch (evaluateFCmpRelation(C1, C2)) {
   1716     default: llvm_unreachable("Unknown relation!");
   1717     case FCmpInst::FCMP_UNO:
   1718     case FCmpInst::FCMP_ORD:
   1719     case FCmpInst::FCMP_UEQ:
   1720     case FCmpInst::FCMP_UNE:
   1721     case FCmpInst::FCMP_ULT:
   1722     case FCmpInst::FCMP_UGT:
   1723     case FCmpInst::FCMP_ULE:
   1724     case FCmpInst::FCMP_UGE:
   1725     case FCmpInst::FCMP_TRUE:
   1726     case FCmpInst::FCMP_FALSE:
   1727     case FCmpInst::BAD_FCMP_PREDICATE:
   1728       break; // Couldn't determine anything about these constants.
   1729     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
   1730       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
   1731                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
   1732                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
   1733       break;
   1734     case FCmpInst::FCMP_OLT: // We know that C1 < C2
   1735       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
   1736                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
   1737                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
   1738       break;
   1739     case FCmpInst::FCMP_OGT: // We know that C1 > C2
   1740       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
   1741                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
   1742                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
   1743       break;
   1744     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
   1745       // We can only partially decide this relation.
   1746       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
   1747         Result = 0;
   1748       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
   1749         Result = 1;
   1750       break;
   1751     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
   1752       // We can only partially decide this relation.
   1753       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT)
   1754         Result = 0;
   1755       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT)
   1756         Result = 1;
   1757       break;
   1758     case FCmpInst::FCMP_ONE: // We know that C1 != C2
   1759       // We can only partially decide this relation.
   1760       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ)
   1761         Result = 0;
   1762       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE)
   1763         Result = 1;
   1764       break;
   1765     }
   1766 
   1767     // If we evaluated the result, return it now.
   1768     if (Result != -1)
   1769       return ConstantInt::get(ResultTy, Result);
   1770 
   1771   } else {
   1772     // Evaluate the relation between the two constants, per the predicate.
   1773     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
   1774     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
   1775     default: llvm_unreachable("Unknown relational!");
   1776     case ICmpInst::BAD_ICMP_PREDICATE:
   1777       break;  // Couldn't determine anything about these constants.
   1778     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
   1779       // If we know the constants are equal, we can decide the result of this
   1780       // computation precisely.
   1781       Result = ICmpInst::isTrueWhenEqual((ICmpInst::Predicate)pred);
   1782       break;
   1783     case ICmpInst::ICMP_ULT:
   1784       switch (pred) {
   1785       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
   1786         Result = 1; break;
   1787       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
   1788         Result = 0; break;
   1789       }
   1790       break;
   1791     case ICmpInst::ICMP_SLT:
   1792       switch (pred) {
   1793       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
   1794         Result = 1; break;
   1795       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
   1796         Result = 0; break;
   1797       }
   1798       break;
   1799     case ICmpInst::ICMP_UGT:
   1800       switch (pred) {
   1801       case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
   1802         Result = 1; break;
   1803       case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
   1804         Result = 0; break;
   1805       }
   1806       break;
   1807     case ICmpInst::ICMP_SGT:
   1808       switch (pred) {
   1809       case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
   1810         Result = 1; break;
   1811       case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
   1812         Result = 0; break;
   1813       }
   1814       break;
   1815     case ICmpInst::ICMP_ULE:
   1816       if (pred == ICmpInst::ICMP_UGT) Result = 0;
   1817       if (pred == ICmpInst::ICMP_ULT || pred == ICmpInst::ICMP_ULE) Result = 1;
   1818       break;
   1819     case ICmpInst::ICMP_SLE:
   1820       if (pred == ICmpInst::ICMP_SGT) Result = 0;
   1821       if (pred == ICmpInst::ICMP_SLT || pred == ICmpInst::ICMP_SLE) Result = 1;
   1822       break;
   1823     case ICmpInst::ICMP_UGE:
   1824       if (pred == ICmpInst::ICMP_ULT) Result = 0;
   1825       if (pred == ICmpInst::ICMP_UGT || pred == ICmpInst::ICMP_UGE) Result = 1;
   1826       break;
   1827     case ICmpInst::ICMP_SGE:
   1828       if (pred == ICmpInst::ICMP_SLT) Result = 0;
   1829       if (pred == ICmpInst::ICMP_SGT || pred == ICmpInst::ICMP_SGE) Result = 1;
   1830       break;
   1831     case ICmpInst::ICMP_NE:
   1832       if (pred == ICmpInst::ICMP_EQ) Result = 0;
   1833       if (pred == ICmpInst::ICMP_NE) Result = 1;
   1834       break;
   1835     }
   1836 
   1837     // If we evaluated the result, return it now.
   1838     if (Result != -1)
   1839       return ConstantInt::get(ResultTy, Result);
   1840 
   1841     // If the right hand side is a bitcast, try using its inverse to simplify
   1842     // it by moving it to the left hand side.  We can't do this if it would turn
   1843     // a vector compare into a scalar compare or visa versa.
   1844     if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
   1845       Constant *CE2Op0 = CE2->getOperand(0);
   1846       if (CE2->getOpcode() == Instruction::BitCast &&
   1847           CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy()) {
   1848         Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
   1849         return ConstantExpr::getICmp(pred, Inverse, CE2Op0);
   1850       }
   1851     }
   1852 
   1853     // If the left hand side is an extension, try eliminating it.
   1854     if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
   1855       if ((CE1->getOpcode() == Instruction::SExt && ICmpInst::isSigned(pred)) ||
   1856           (CE1->getOpcode() == Instruction::ZExt && !ICmpInst::isSigned(pred))){
   1857         Constant *CE1Op0 = CE1->getOperand(0);
   1858         Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
   1859         if (CE1Inverse == CE1Op0) {
   1860           // Check whether we can safely truncate the right hand side.
   1861           Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
   1862           if (ConstantExpr::getZExt(C2Inverse, C2->getType()) == C2) {
   1863             return ConstantExpr::getICmp(pred, CE1Inverse, C2Inverse);
   1864           }
   1865         }
   1866       }
   1867     }
   1868 
   1869     if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
   1870         (C1->isNullValue() && !C2->isNullValue())) {
   1871       // If C2 is a constant expr and C1 isn't, flip them around and fold the
   1872       // other way if possible.
   1873       // Also, if C1 is null and C2 isn't, flip them around.
   1874       pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
   1875       return ConstantExpr::getICmp(pred, C2, C1);
   1876     }
   1877   }
   1878   return 0;
   1879 }
   1880 
   1881 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
   1882 /// is "inbounds".
   1883 template<typename IndexTy>
   1884 static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
   1885   // No indices means nothing that could be out of bounds.
   1886   if (Idxs.empty()) return true;
   1887 
   1888   // If the first index is zero, it's in bounds.
   1889   if (cast<Constant>(Idxs[0])->isNullValue()) return true;
   1890 
   1891   // If the first index is one and all the rest are zero, it's in bounds,
   1892   // by the one-past-the-end rule.
   1893   if (!cast<ConstantInt>(Idxs[0])->isOne())
   1894     return false;
   1895   for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
   1896     if (!cast<Constant>(Idxs[i])->isNullValue())
   1897       return false;
   1898   return true;
   1899 }
   1900 
   1901 template<typename IndexTy>
   1902 static Constant *ConstantFoldGetElementPtrImpl(Constant *C,
   1903                                                bool inBounds,
   1904                                                ArrayRef<IndexTy> Idxs) {
   1905   if (Idxs.empty()) return C;
   1906   Constant *Idx0 = cast<Constant>(Idxs[0]);
   1907   if ((Idxs.size() == 1 && Idx0->isNullValue()))
   1908     return C;
   1909 
   1910   if (isa<UndefValue>(C)) {
   1911     PointerType *Ptr = cast<PointerType>(C->getType());
   1912     Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
   1913     assert(Ty != 0 && "Invalid indices for GEP!");
   1914     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
   1915   }
   1916 
   1917   if (C->isNullValue()) {
   1918     bool isNull = true;
   1919     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
   1920       if (!cast<Constant>(Idxs[i])->isNullValue()) {
   1921         isNull = false;
   1922         break;
   1923       }
   1924     if (isNull) {
   1925       PointerType *Ptr = cast<PointerType>(C->getType());
   1926       Type *Ty = GetElementPtrInst::getIndexedType(Ptr, Idxs);
   1927       assert(Ty != 0 && "Invalid indices for GEP!");
   1928       return ConstantPointerNull::get(PointerType::get(Ty,
   1929                                                        Ptr->getAddressSpace()));
   1930     }
   1931   }
   1932 
   1933   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
   1934     // Combine Indices - If the source pointer to this getelementptr instruction
   1935     // is a getelementptr instruction, combine the indices of the two
   1936     // getelementptr instructions into a single instruction.
   1937     //
   1938     if (CE->getOpcode() == Instruction::GetElementPtr) {
   1939       Type *LastTy = 0;
   1940       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
   1941            I != E; ++I)
   1942         LastTy = *I;
   1943 
   1944       if ((LastTy && isa<SequentialType>(LastTy)) || Idx0->isNullValue()) {
   1945         SmallVector<Value*, 16> NewIndices;
   1946         NewIndices.reserve(Idxs.size() + CE->getNumOperands());
   1947         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
   1948           NewIndices.push_back(CE->getOperand(i));
   1949 
   1950         // Add the last index of the source with the first index of the new GEP.
   1951         // Make sure to handle the case when they are actually different types.
   1952         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
   1953         // Otherwise it must be an array.
   1954         if (!Idx0->isNullValue()) {
   1955           Type *IdxTy = Combined->getType();
   1956           if (IdxTy != Idx0->getType()) {
   1957             Type *Int64Ty = Type::getInt64Ty(IdxTy->getContext());
   1958             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Int64Ty);
   1959             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, Int64Ty);
   1960             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
   1961           } else {
   1962             Combined =
   1963               ConstantExpr::get(Instruction::Add, Idx0, Combined);
   1964           }
   1965         }
   1966 
   1967         NewIndices.push_back(Combined);
   1968         NewIndices.append(Idxs.begin() + 1, Idxs.end());
   1969         return
   1970           ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices,
   1971                                          inBounds &&
   1972                                            cast<GEPOperator>(CE)->isInBounds());
   1973       }
   1974     }
   1975 
   1976     // Implement folding of:
   1977     //    i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
   1978     //                        i64 0, i64 0)
   1979     // To: i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
   1980     //
   1981     if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
   1982       if (PointerType *SPT =
   1983           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
   1984         if (ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
   1985           if (ArrayType *CAT =
   1986         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
   1987             if (CAT->getElementType() == SAT->getElementType())
   1988               return
   1989                 ConstantExpr::getGetElementPtr((Constant*)CE->getOperand(0),
   1990                                                Idxs, inBounds);
   1991     }
   1992   }
   1993 
   1994   // Check to see if any array indices are not within the corresponding
   1995   // notional array bounds. If so, try to determine if they can be factored
   1996   // out into preceding dimensions.
   1997   bool Unknown = false;
   1998   SmallVector<Constant *, 8> NewIdxs;
   1999   Type *Ty = C->getType();
   2000   Type *Prev = 0;
   2001   for (unsigned i = 0, e = Idxs.size(); i != e;
   2002        Prev = Ty, Ty = cast<CompositeType>(Ty)->getTypeAtIndex(Idxs[i]), ++i) {
   2003     if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
   2004       if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
   2005         if (ATy->getNumElements() <= INT64_MAX &&
   2006             ATy->getNumElements() != 0 &&
   2007             CI->getSExtValue() >= (int64_t)ATy->getNumElements()) {
   2008           if (isa<SequentialType>(Prev)) {
   2009             // It's out of range, but we can factor it into the prior
   2010             // dimension.
   2011             NewIdxs.resize(Idxs.size());
   2012             ConstantInt *Factor = ConstantInt::get(CI->getType(),
   2013                                                    ATy->getNumElements());
   2014             NewIdxs[i] = ConstantExpr::getSRem(CI, Factor);
   2015 
   2016             Constant *PrevIdx = cast<Constant>(Idxs[i-1]);
   2017             Constant *Div = ConstantExpr::getSDiv(CI, Factor);
   2018 
   2019             // Before adding, extend both operands to i64 to avoid
   2020             // overflow trouble.
   2021             if (!PrevIdx->getType()->isIntegerTy(64))
   2022               PrevIdx = ConstantExpr::getSExt(PrevIdx,
   2023                                            Type::getInt64Ty(Div->getContext()));
   2024             if (!Div->getType()->isIntegerTy(64))
   2025               Div = ConstantExpr::getSExt(Div,
   2026                                           Type::getInt64Ty(Div->getContext()));
   2027 
   2028             NewIdxs[i-1] = ConstantExpr::getAdd(PrevIdx, Div);
   2029           } else {
   2030             // It's out of range, but the prior dimension is a struct
   2031             // so we can't do anything about it.
   2032             Unknown = true;
   2033           }
   2034         }
   2035     } else {
   2036       // We don't know if it's in range or not.
   2037       Unknown = true;
   2038     }
   2039   }
   2040 
   2041   // If we did any factoring, start over with the adjusted indices.
   2042   if (!NewIdxs.empty()) {
   2043     for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
   2044       if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
   2045     return ConstantExpr::getGetElementPtr(C, NewIdxs, inBounds);
   2046   }
   2047 
   2048   // If all indices are known integers and normalized, we can do a simple
   2049   // check for the "inbounds" property.
   2050   if (!Unknown && !inBounds &&
   2051       isa<GlobalVariable>(C) && isInBoundsIndices(Idxs))
   2052     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs);
   2053 
   2054   return 0;
   2055 }
   2056 
   2057 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
   2058                                           bool inBounds,
   2059                                           ArrayRef<Constant *> Idxs) {
   2060   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
   2061 }
   2062 
   2063 Constant *llvm::ConstantFoldGetElementPtr(Constant *C,
   2064                                           bool inBounds,
   2065                                           ArrayRef<Value *> Idxs) {
   2066   return ConstantFoldGetElementPtrImpl(C, inBounds, Idxs);
   2067 }
   2068