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