LLVM API Documentation

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