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