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