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