LLVM  mainline
Constants.cpp
Go to the documentation of this file.
00001 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
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 the Constant* classes.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/Constants.h"
00015 #include "ConstantFold.h"
00016 #include "LLVMContextImpl.h"
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/FoldingSet.h"
00019 #include "llvm/ADT/STLExtras.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/ADT/StringExtras.h"
00022 #include "llvm/ADT/StringMap.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/GetElementPtrTypeIterator.h"
00025 #include "llvm/IR/GlobalValue.h"
00026 #include "llvm/IR/Instructions.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/Operator.h"
00029 #include "llvm/Support/Compiler.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/Support/ErrorHandling.h"
00032 #include "llvm/Support/ManagedStatic.h"
00033 #include "llvm/Support/MathExtras.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include <algorithm>
00036 #include <cstdarg>
00037 using namespace llvm;
00038 
00039 //===----------------------------------------------------------------------===//
00040 //                              Constant Class
00041 //===----------------------------------------------------------------------===//
00042 
00043 void Constant::anchor() { }
00044 
00045 bool Constant::isNegativeZeroValue() const {
00046   // Floating point values have an explicit -0.0 value.
00047   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00048     return CFP->isZero() && CFP->isNegative();
00049 
00050   // Equivalent for a vector of -0.0's.
00051   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00052     if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
00053       if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
00054         return true;
00055 
00056   // We've already handled true FP case; any other FP vectors can't represent -0.0.
00057   if (getType()->isFPOrFPVectorTy())
00058     return false;
00059 
00060   // Otherwise, just use +0.0.
00061   return isNullValue();
00062 }
00063 
00064 // Return true iff this constant is positive zero (floating point), negative
00065 // zero (floating point), or a null value.
00066 bool Constant::isZeroValue() const {
00067   // Floating point values have an explicit -0.0 value.
00068   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00069     return CFP->isZero();
00070 
00071   // Otherwise, just use +0.0.
00072   return isNullValue();
00073 }
00074 
00075 bool Constant::isNullValue() const {
00076   // 0 is null.
00077   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00078     return CI->isZero();
00079 
00080   // +0.0 is null.
00081   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00082     return CFP->isZero() && !CFP->isNegative();
00083 
00084   // constant zero is zero for aggregates and cpnull is null for pointers.
00085   return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
00086 }
00087 
00088 bool Constant::isAllOnesValue() const {
00089   // Check for -1 integers
00090   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00091     return CI->isMinusOne();
00092 
00093   // Check for FP which are bitcasted from -1 integers
00094   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00095     return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
00096 
00097   // Check for constant vectors which are splats of -1 values.
00098   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00099     if (Constant *Splat = CV->getSplatValue())
00100       return Splat->isAllOnesValue();
00101 
00102   // Check for constant vectors which are splats of -1 values.
00103   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00104     if (Constant *Splat = CV->getSplatValue())
00105       return Splat->isAllOnesValue();
00106 
00107   return false;
00108 }
00109 
00110 bool Constant::isOneValue() const {
00111   // Check for 1 integers
00112   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00113     return CI->isOne();
00114 
00115   // Check for FP which are bitcasted from 1 integers
00116   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00117     return CFP->getValueAPF().bitcastToAPInt() == 1;
00118 
00119   // Check for constant vectors which are splats of 1 values.
00120   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00121     if (Constant *Splat = CV->getSplatValue())
00122       return Splat->isOneValue();
00123 
00124   // Check for constant vectors which are splats of 1 values.
00125   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00126     if (Constant *Splat = CV->getSplatValue())
00127       return Splat->isOneValue();
00128 
00129   return false;
00130 }
00131 
00132 bool Constant::isMinSignedValue() const {
00133   // Check for INT_MIN integers
00134   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00135     return CI->isMinValue(/*isSigned=*/true);
00136 
00137   // Check for FP which are bitcasted from INT_MIN integers
00138   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00139     return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
00140 
00141   // Check for constant vectors which are splats of INT_MIN values.
00142   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00143     if (Constant *Splat = CV->getSplatValue())
00144       return Splat->isMinSignedValue();
00145 
00146   // Check for constant vectors which are splats of INT_MIN values.
00147   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00148     if (Constant *Splat = CV->getSplatValue())
00149       return Splat->isMinSignedValue();
00150 
00151   return false;
00152 }
00153 
00154 bool Constant::isNotMinSignedValue() const {
00155   // Check for INT_MIN integers
00156   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
00157     return !CI->isMinValue(/*isSigned=*/true);
00158 
00159   // Check for FP which are bitcasted from INT_MIN integers
00160   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
00161     return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
00162 
00163   // Check for constant vectors which are splats of INT_MIN values.
00164   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00165     if (Constant *Splat = CV->getSplatValue())
00166       return Splat->isNotMinSignedValue();
00167 
00168   // Check for constant vectors which are splats of INT_MIN values.
00169   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
00170     if (Constant *Splat = CV->getSplatValue())
00171       return Splat->isNotMinSignedValue();
00172 
00173   // It *may* contain INT_MIN, we can't tell.
00174   return false;
00175 }
00176 
00177 // Constructor to create a '0' constant of arbitrary type...
00178 Constant *Constant::getNullValue(Type *Ty) {
00179   switch (Ty->getTypeID()) {
00180   case Type::IntegerTyID:
00181     return ConstantInt::get(Ty, 0);
00182   case Type::HalfTyID:
00183     return ConstantFP::get(Ty->getContext(),
00184                            APFloat::getZero(APFloat::IEEEhalf));
00185   case Type::FloatTyID:
00186     return ConstantFP::get(Ty->getContext(),
00187                            APFloat::getZero(APFloat::IEEEsingle));
00188   case Type::DoubleTyID:
00189     return ConstantFP::get(Ty->getContext(),
00190                            APFloat::getZero(APFloat::IEEEdouble));
00191   case Type::X86_FP80TyID:
00192     return ConstantFP::get(Ty->getContext(),
00193                            APFloat::getZero(APFloat::x87DoubleExtended));
00194   case Type::FP128TyID:
00195     return ConstantFP::get(Ty->getContext(),
00196                            APFloat::getZero(APFloat::IEEEquad));
00197   case Type::PPC_FP128TyID:
00198     return ConstantFP::get(Ty->getContext(),
00199                            APFloat(APFloat::PPCDoubleDouble,
00200                                    APInt::getNullValue(128)));
00201   case Type::PointerTyID:
00202     return ConstantPointerNull::get(cast<PointerType>(Ty));
00203   case Type::StructTyID:
00204   case Type::ArrayTyID:
00205   case Type::VectorTyID:
00206     return ConstantAggregateZero::get(Ty);
00207   default:
00208     // Function, Label, or Opaque type?
00209     llvm_unreachable("Cannot create a null constant of that type!");
00210   }
00211 }
00212 
00213 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
00214   Type *ScalarTy = Ty->getScalarType();
00215 
00216   // Create the base integer constant.
00217   Constant *C = ConstantInt::get(Ty->getContext(), V);
00218 
00219   // Convert an integer to a pointer, if necessary.
00220   if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
00221     C = ConstantExpr::getIntToPtr(C, PTy);
00222 
00223   // Broadcast a scalar to a vector, if necessary.
00224   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00225     C = ConstantVector::getSplat(VTy->getNumElements(), C);
00226 
00227   return C;
00228 }
00229 
00230 Constant *Constant::getAllOnesValue(Type *Ty) {
00231   if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
00232     return ConstantInt::get(Ty->getContext(),
00233                             APInt::getAllOnesValue(ITy->getBitWidth()));
00234 
00235   if (Ty->isFloatingPointTy()) {
00236     APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
00237                                           !Ty->isPPC_FP128Ty());
00238     return ConstantFP::get(Ty->getContext(), FL);
00239   }
00240 
00241   VectorType *VTy = cast<VectorType>(Ty);
00242   return ConstantVector::getSplat(VTy->getNumElements(),
00243                                   getAllOnesValue(VTy->getElementType()));
00244 }
00245 
00246 /// getAggregateElement - For aggregates (struct/array/vector) return the
00247 /// constant that corresponds to the specified element if possible, or null if
00248 /// not.  This can return null if the element index is a ConstantExpr, or if
00249 /// 'this' is a constant expr.
00250 Constant *Constant::getAggregateElement(unsigned Elt) const {
00251   if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
00252     return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
00253 
00254   if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
00255     return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
00256 
00257   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
00258     return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
00259 
00260   if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
00261     return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
00262 
00263   if (const UndefValue *UV = dyn_cast<UndefValue>(this))
00264     return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
00265 
00266   if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
00267     return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
00268                                        : nullptr;
00269   return nullptr;
00270 }
00271 
00272 Constant *Constant::getAggregateElement(Constant *Elt) const {
00273   assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
00274   if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
00275     return getAggregateElement(CI->getZExtValue());
00276   return nullptr;
00277 }
00278 
00279 
00280 void Constant::destroyConstantImpl() {
00281   // When a Constant is destroyed, there may be lingering
00282   // references to the constant by other constants in the constant pool.  These
00283   // constants are implicitly dependent on the module that is being deleted,
00284   // but they don't know that.  Because we only find out when the CPV is
00285   // deleted, we must now notify all of our users (that should only be
00286   // Constants) that they are, in fact, invalid now and should be deleted.
00287   //
00288   while (!use_empty()) {
00289     Value *V = user_back();
00290 #ifndef NDEBUG      // Only in -g mode...
00291     if (!isa<Constant>(V)) {
00292       dbgs() << "While deleting: " << *this
00293              << "\n\nUse still stuck around after Def is destroyed: "
00294              << *V << "\n\n";
00295     }
00296 #endif
00297     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
00298     cast<Constant>(V)->destroyConstant();
00299 
00300     // The constant should remove itself from our use list...
00301     assert((use_empty() || user_back() != V) && "Constant not removed!");
00302   }
00303 
00304   // Value has no outstanding references it is safe to delete it now...
00305   delete this;
00306 }
00307 
00308 static bool canTrapImpl(const Constant *C,
00309                         SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
00310   assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
00311   // The only thing that could possibly trap are constant exprs.
00312   const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
00313   if (!CE)
00314     return false;
00315 
00316   // ConstantExpr traps if any operands can trap.
00317   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
00318     if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
00319       if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
00320         return true;
00321     }
00322   }
00323 
00324   // Otherwise, only specific operations can trap.
00325   switch (CE->getOpcode()) {
00326   default:
00327     return false;
00328   case Instruction::UDiv:
00329   case Instruction::SDiv:
00330   case Instruction::FDiv:
00331   case Instruction::URem:
00332   case Instruction::SRem:
00333   case Instruction::FRem:
00334     // Div and rem can trap if the RHS is not known to be non-zero.
00335     if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
00336       return true;
00337     return false;
00338   }
00339 }
00340 
00341 /// canTrap - Return true if evaluation of this constant could trap.  This is
00342 /// true for things like constant expressions that could divide by zero.
00343 bool Constant::canTrap() const {
00344   SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
00345   return canTrapImpl(this, NonTrappingOps);
00346 }
00347 
00348 /// Check if C contains a GlobalValue for which Predicate is true.
00349 static bool
00350 ConstHasGlobalValuePredicate(const Constant *C,
00351                              bool (*Predicate)(const GlobalValue *)) {
00352   SmallPtrSet<const Constant *, 8> Visited;
00353   SmallVector<const Constant *, 8> WorkList;
00354   WorkList.push_back(C);
00355   Visited.insert(C);
00356 
00357   while (!WorkList.empty()) {
00358     const Constant *WorkItem = WorkList.pop_back_val();
00359     if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
00360       if (Predicate(GV))
00361         return true;
00362     for (const Value *Op : WorkItem->operands()) {
00363       const Constant *ConstOp = dyn_cast<Constant>(Op);
00364       if (!ConstOp)
00365         continue;
00366       if (Visited.insert(ConstOp).second)
00367         WorkList.push_back(ConstOp);
00368     }
00369   }
00370   return false;
00371 }
00372 
00373 /// Return true if the value can vary between threads.
00374 bool Constant::isThreadDependent() const {
00375   auto DLLImportPredicate = [](const GlobalValue *GV) {
00376     return GV->isThreadLocal();
00377   };
00378   return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
00379 }
00380 
00381 bool Constant::isDLLImportDependent() const {
00382   auto DLLImportPredicate = [](const GlobalValue *GV) {
00383     return GV->hasDLLImportStorageClass();
00384   };
00385   return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
00386 }
00387 
00388 /// Return true if the constant has users other than constant exprs and other
00389 /// dangling things.
00390 bool Constant::isConstantUsed() const {
00391   for (const User *U : users()) {
00392     const Constant *UC = dyn_cast<Constant>(U);
00393     if (!UC || isa<GlobalValue>(UC))
00394       return true;
00395 
00396     if (UC->isConstantUsed())
00397       return true;
00398   }
00399   return false;
00400 }
00401 
00402 
00403 
00404 /// getRelocationInfo - This method classifies the entry according to
00405 /// whether or not it may generate a relocation entry.  This must be
00406 /// conservative, so if it might codegen to a relocatable entry, it should say
00407 /// so.  The return values are:
00408 /// 
00409 ///  NoRelocation: This constant pool entry is guaranteed to never have a
00410 ///     relocation applied to it (because it holds a simple constant like
00411 ///     '4').
00412 ///  LocalRelocation: This entry has relocations, but the entries are
00413 ///     guaranteed to be resolvable by the static linker, so the dynamic
00414 ///     linker will never see them.
00415 ///  GlobalRelocations: This entry may have arbitrary relocations.
00416 ///
00417 /// FIXME: This really should not be in IR.
00418 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
00419   if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
00420     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
00421       return LocalRelocation;  // Local to this file/library.
00422     return GlobalRelocations;    // Global reference.
00423   }
00424   
00425   if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
00426     return BA->getFunction()->getRelocationInfo();
00427   
00428   // While raw uses of blockaddress need to be relocated, differences between
00429   // two of them don't when they are for labels in the same function.  This is a
00430   // common idiom when creating a table for the indirect goto extension, so we
00431   // handle it efficiently here.
00432   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
00433     if (CE->getOpcode() == Instruction::Sub) {
00434       ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
00435       ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
00436       if (LHS && RHS &&
00437           LHS->getOpcode() == Instruction::PtrToInt &&
00438           RHS->getOpcode() == Instruction::PtrToInt &&
00439           isa<BlockAddress>(LHS->getOperand(0)) &&
00440           isa<BlockAddress>(RHS->getOperand(0)) &&
00441           cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
00442             cast<BlockAddress>(RHS->getOperand(0))->getFunction())
00443         return NoRelocation;
00444     }
00445 
00446   PossibleRelocationsTy Result = NoRelocation;
00447   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00448     Result = std::max(Result,
00449                       cast<Constant>(getOperand(i))->getRelocationInfo());
00450 
00451   return Result;
00452 }
00453 
00454 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
00455 /// it.  This involves recursively eliminating any dead users of the
00456 /// constantexpr.
00457 static bool removeDeadUsersOfConstant(const Constant *C) {
00458   if (isa<GlobalValue>(C)) return false; // Cannot remove this
00459 
00460   while (!C->use_empty()) {
00461     const Constant *User = dyn_cast<Constant>(C->user_back());
00462     if (!User) return false; // Non-constant usage;
00463     if (!removeDeadUsersOfConstant(User))
00464       return false; // Constant wasn't dead
00465   }
00466 
00467   const_cast<Constant*>(C)->destroyConstant();
00468   return true;
00469 }
00470 
00471 
00472 /// removeDeadConstantUsers - If there are any dead constant users dangling
00473 /// off of this constant, remove them.  This method is useful for clients
00474 /// that want to check to see if a global is unused, but don't want to deal
00475 /// with potentially dead constants hanging off of the globals.
00476 void Constant::removeDeadConstantUsers() const {
00477   Value::const_user_iterator I = user_begin(), E = user_end();
00478   Value::const_user_iterator LastNonDeadUser = E;
00479   while (I != E) {
00480     const Constant *User = dyn_cast<Constant>(*I);
00481     if (!User) {
00482       LastNonDeadUser = I;
00483       ++I;
00484       continue;
00485     }
00486 
00487     if (!removeDeadUsersOfConstant(User)) {
00488       // If the constant wasn't dead, remember that this was the last live use
00489       // and move on to the next constant.
00490       LastNonDeadUser = I;
00491       ++I;
00492       continue;
00493     }
00494 
00495     // If the constant was dead, then the iterator is invalidated.
00496     if (LastNonDeadUser == E) {
00497       I = user_begin();
00498       if (I == E) break;
00499     } else {
00500       I = LastNonDeadUser;
00501       ++I;
00502     }
00503   }
00504 }
00505 
00506 
00507 
00508 //===----------------------------------------------------------------------===//
00509 //                                ConstantInt
00510 //===----------------------------------------------------------------------===//
00511 
00512 void ConstantInt::anchor() { }
00513 
00514 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
00515   : Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
00516   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
00517 }
00518 
00519 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
00520   LLVMContextImpl *pImpl = Context.pImpl;
00521   if (!pImpl->TheTrueVal)
00522     pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
00523   return pImpl->TheTrueVal;
00524 }
00525 
00526 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
00527   LLVMContextImpl *pImpl = Context.pImpl;
00528   if (!pImpl->TheFalseVal)
00529     pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
00530   return pImpl->TheFalseVal;
00531 }
00532 
00533 Constant *ConstantInt::getTrue(Type *Ty) {
00534   VectorType *VTy = dyn_cast<VectorType>(Ty);
00535   if (!VTy) {
00536     assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
00537     return ConstantInt::getTrue(Ty->getContext());
00538   }
00539   assert(VTy->getElementType()->isIntegerTy(1) &&
00540          "True must be vector of i1 or i1.");
00541   return ConstantVector::getSplat(VTy->getNumElements(),
00542                                   ConstantInt::getTrue(Ty->getContext()));
00543 }
00544 
00545 Constant *ConstantInt::getFalse(Type *Ty) {
00546   VectorType *VTy = dyn_cast<VectorType>(Ty);
00547   if (!VTy) {
00548     assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
00549     return ConstantInt::getFalse(Ty->getContext());
00550   }
00551   assert(VTy->getElementType()->isIntegerTy(1) &&
00552          "False must be vector of i1 or i1.");
00553   return ConstantVector::getSplat(VTy->getNumElements(),
00554                                   ConstantInt::getFalse(Ty->getContext()));
00555 }
00556 
00557 // Get a ConstantInt from an APInt.
00558 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
00559   // get an existing value or the insertion position
00560   LLVMContextImpl *pImpl = Context.pImpl;
00561   ConstantInt *&Slot = pImpl->IntConstants[V];
00562   if (!Slot) {
00563     // Get the corresponding integer type for the bit width of the value.
00564     IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
00565     Slot = new ConstantInt(ITy, V);
00566   }
00567   assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
00568   return Slot;
00569 }
00570 
00571 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
00572   Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
00573 
00574   // For vectors, broadcast the value.
00575   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00576     return ConstantVector::getSplat(VTy->getNumElements(), C);
00577 
00578   return C;
00579 }
00580 
00581 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, 
00582                               bool isSigned) {
00583   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
00584 }
00585 
00586 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
00587   return get(Ty, V, true);
00588 }
00589 
00590 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
00591   return get(Ty, V, true);
00592 }
00593 
00594 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
00595   ConstantInt *C = get(Ty->getContext(), V);
00596   assert(C->getType() == Ty->getScalarType() &&
00597          "ConstantInt type doesn't match the type implied by its value!");
00598 
00599   // For vectors, broadcast the value.
00600   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00601     return ConstantVector::getSplat(VTy->getNumElements(), C);
00602 
00603   return C;
00604 }
00605 
00606 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
00607                               uint8_t radix) {
00608   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
00609 }
00610 
00611 //===----------------------------------------------------------------------===//
00612 //                                ConstantFP
00613 //===----------------------------------------------------------------------===//
00614 
00615 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
00616   if (Ty->isHalfTy())
00617     return &APFloat::IEEEhalf;
00618   if (Ty->isFloatTy())
00619     return &APFloat::IEEEsingle;
00620   if (Ty->isDoubleTy())
00621     return &APFloat::IEEEdouble;
00622   if (Ty->isX86_FP80Ty())
00623     return &APFloat::x87DoubleExtended;
00624   else if (Ty->isFP128Ty())
00625     return &APFloat::IEEEquad;
00626 
00627   assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
00628   return &APFloat::PPCDoubleDouble;
00629 }
00630 
00631 void ConstantFP::anchor() { }
00632 
00633 /// get() - This returns a constant fp for the specified value in the
00634 /// specified type.  This should only be used for simple constant values like
00635 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
00636 Constant *ConstantFP::get(Type *Ty, double V) {
00637   LLVMContext &Context = Ty->getContext();
00638 
00639   APFloat FV(V);
00640   bool ignored;
00641   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
00642              APFloat::rmNearestTiesToEven, &ignored);
00643   Constant *C = get(Context, FV);
00644 
00645   // For vectors, broadcast the value.
00646   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00647     return ConstantVector::getSplat(VTy->getNumElements(), C);
00648 
00649   return C;
00650 }
00651 
00652 
00653 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
00654   LLVMContext &Context = Ty->getContext();
00655 
00656   APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
00657   Constant *C = get(Context, FV);
00658 
00659   // For vectors, broadcast the value.
00660   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00661     return ConstantVector::getSplat(VTy->getNumElements(), C);
00662 
00663   return C; 
00664 }
00665 
00666 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
00667   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
00668   APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
00669   Constant *C = get(Ty->getContext(), NaN);
00670 
00671   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00672     return ConstantVector::getSplat(VTy->getNumElements(), C);
00673 
00674   return C;
00675 }
00676 
00677 Constant *ConstantFP::getNegativeZero(Type *Ty) {
00678   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
00679   APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
00680   Constant *C = get(Ty->getContext(), NegZero);
00681 
00682   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00683     return ConstantVector::getSplat(VTy->getNumElements(), C);
00684 
00685   return C;
00686 }
00687 
00688 
00689 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
00690   if (Ty->isFPOrFPVectorTy())
00691     return getNegativeZero(Ty);
00692 
00693   return Constant::getNullValue(Ty);
00694 }
00695 
00696 
00697 // ConstantFP accessors.
00698 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
00699   LLVMContextImpl* pImpl = Context.pImpl;
00700 
00701   ConstantFP *&Slot = pImpl->FPConstants[V];
00702 
00703   if (!Slot) {
00704     Type *Ty;
00705     if (&V.getSemantics() == &APFloat::IEEEhalf)
00706       Ty = Type::getHalfTy(Context);
00707     else if (&V.getSemantics() == &APFloat::IEEEsingle)
00708       Ty = Type::getFloatTy(Context);
00709     else if (&V.getSemantics() == &APFloat::IEEEdouble)
00710       Ty = Type::getDoubleTy(Context);
00711     else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
00712       Ty = Type::getX86_FP80Ty(Context);
00713     else if (&V.getSemantics() == &APFloat::IEEEquad)
00714       Ty = Type::getFP128Ty(Context);
00715     else {
00716       assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
00717              "Unknown FP format");
00718       Ty = Type::getPPC_FP128Ty(Context);
00719     }
00720     Slot = new ConstantFP(Ty, V);
00721   }
00722 
00723   return Slot;
00724 }
00725 
00726 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
00727   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
00728   Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
00729 
00730   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
00731     return ConstantVector::getSplat(VTy->getNumElements(), C);
00732 
00733   return C;
00734 }
00735 
00736 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
00737   : Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
00738   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
00739          "FP type Mismatch");
00740 }
00741 
00742 bool ConstantFP::isExactlyValue(const APFloat &V) const {
00743   return Val.bitwiseIsEqual(V);
00744 }
00745 
00746 //===----------------------------------------------------------------------===//
00747 //                   ConstantAggregateZero Implementation
00748 //===----------------------------------------------------------------------===//
00749 
00750 /// getSequentialElement - If this CAZ has array or vector type, return a zero
00751 /// with the right element type.
00752 Constant *ConstantAggregateZero::getSequentialElement() const {
00753   return Constant::getNullValue(getType()->getSequentialElementType());
00754 }
00755 
00756 /// getStructElement - If this CAZ has struct type, return a zero with the
00757 /// right element type for the specified element.
00758 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
00759   return Constant::getNullValue(getType()->getStructElementType(Elt));
00760 }
00761 
00762 /// getElementValue - Return a zero of the right value for the specified GEP
00763 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
00764 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
00765   if (isa<SequentialType>(getType()))
00766     return getSequentialElement();
00767   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
00768 }
00769 
00770 /// getElementValue - Return a zero of the right value for the specified GEP
00771 /// index.
00772 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
00773   if (isa<SequentialType>(getType()))
00774     return getSequentialElement();
00775   return getStructElement(Idx);
00776 }
00777 
00778 unsigned ConstantAggregateZero::getNumElements() const {
00779   const Type *Ty = getType();
00780   if (const auto *AT = dyn_cast<ArrayType>(Ty))
00781     return AT->getNumElements();
00782   if (const auto *VT = dyn_cast<VectorType>(Ty))
00783     return VT->getNumElements();
00784   return Ty->getStructNumElements();
00785 }
00786 
00787 //===----------------------------------------------------------------------===//
00788 //                         UndefValue Implementation
00789 //===----------------------------------------------------------------------===//
00790 
00791 /// getSequentialElement - If this undef has array or vector type, return an
00792 /// undef with the right element type.
00793 UndefValue *UndefValue::getSequentialElement() const {
00794   return UndefValue::get(getType()->getSequentialElementType());
00795 }
00796 
00797 /// getStructElement - If this undef has struct type, return a zero with the
00798 /// right element type for the specified element.
00799 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
00800   return UndefValue::get(getType()->getStructElementType(Elt));
00801 }
00802 
00803 /// getElementValue - Return an undef of the right value for the specified GEP
00804 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
00805 UndefValue *UndefValue::getElementValue(Constant *C) const {
00806   if (isa<SequentialType>(getType()))
00807     return getSequentialElement();
00808   return getStructElement(cast<ConstantInt>(C)->getZExtValue());
00809 }
00810 
00811 /// getElementValue - Return an undef of the right value for the specified GEP
00812 /// index.
00813 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
00814   if (isa<SequentialType>(getType()))
00815     return getSequentialElement();
00816   return getStructElement(Idx);
00817 }
00818 
00819 unsigned UndefValue::getNumElements() const {
00820   const Type *Ty = getType();
00821   if (const auto *AT = dyn_cast<ArrayType>(Ty))
00822     return AT->getNumElements();
00823   if (const auto *VT = dyn_cast<VectorType>(Ty))
00824     return VT->getNumElements();
00825   return Ty->getStructNumElements();
00826 }
00827 
00828 //===----------------------------------------------------------------------===//
00829 //                            ConstantXXX Classes
00830 //===----------------------------------------------------------------------===//
00831 
00832 template <typename ItTy, typename EltTy>
00833 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
00834   for (; Start != End; ++Start)
00835     if (*Start != Elt)
00836       return false;
00837   return true;
00838 }
00839 
00840 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
00841   : Constant(T, ConstantArrayVal,
00842              OperandTraits<ConstantArray>::op_end(this) - V.size(),
00843              V.size()) {
00844   assert(V.size() == T->getNumElements() &&
00845          "Invalid initializer vector for constant array");
00846   for (unsigned i = 0, e = V.size(); i != e; ++i)
00847     assert(V[i]->getType() == T->getElementType() &&
00848            "Initializer for array element doesn't match array element type!");
00849   std::copy(V.begin(), V.end(), op_begin());
00850 }
00851 
00852 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
00853   if (Constant *C = getImpl(Ty, V))
00854     return C;
00855   return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
00856 }
00857 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
00858   // Empty arrays are canonicalized to ConstantAggregateZero.
00859   if (V.empty())
00860     return ConstantAggregateZero::get(Ty);
00861 
00862   for (unsigned i = 0, e = V.size(); i != e; ++i) {
00863     assert(V[i]->getType() == Ty->getElementType() &&
00864            "Wrong type in array element initializer");
00865   }
00866 
00867   // If this is an all-zero array, return a ConstantAggregateZero object.  If
00868   // all undef, return an UndefValue, if "all simple", then return a
00869   // ConstantDataArray.
00870   Constant *C = V[0];
00871   if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
00872     return UndefValue::get(Ty);
00873 
00874   if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
00875     return ConstantAggregateZero::get(Ty);
00876 
00877   // Check to see if all of the elements are ConstantFP or ConstantInt and if
00878   // the element type is compatible with ConstantDataVector.  If so, use it.
00879   if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
00880     // We speculatively build the elements here even if it turns out that there
00881     // is a constantexpr or something else weird in the array, since it is so
00882     // uncommon for that to happen.
00883     if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
00884       if (CI->getType()->isIntegerTy(8)) {
00885         SmallVector<uint8_t, 16> Elts;
00886         for (unsigned i = 0, e = V.size(); i != e; ++i)
00887           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
00888             Elts.push_back(CI->getZExtValue());
00889           else
00890             break;
00891         if (Elts.size() == V.size())
00892           return ConstantDataArray::get(C->getContext(), Elts);
00893       } else if (CI->getType()->isIntegerTy(16)) {
00894         SmallVector<uint16_t, 16> Elts;
00895         for (unsigned i = 0, e = V.size(); i != e; ++i)
00896           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
00897             Elts.push_back(CI->getZExtValue());
00898           else
00899             break;
00900         if (Elts.size() == V.size())
00901           return ConstantDataArray::get(C->getContext(), Elts);
00902       } else if (CI->getType()->isIntegerTy(32)) {
00903         SmallVector<uint32_t, 16> Elts;
00904         for (unsigned i = 0, e = V.size(); i != e; ++i)
00905           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
00906             Elts.push_back(CI->getZExtValue());
00907           else
00908             break;
00909         if (Elts.size() == V.size())
00910           return ConstantDataArray::get(C->getContext(), Elts);
00911       } else if (CI->getType()->isIntegerTy(64)) {
00912         SmallVector<uint64_t, 16> Elts;
00913         for (unsigned i = 0, e = V.size(); i != e; ++i)
00914           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
00915             Elts.push_back(CI->getZExtValue());
00916           else
00917             break;
00918         if (Elts.size() == V.size())
00919           return ConstantDataArray::get(C->getContext(), Elts);
00920       }
00921     }
00922 
00923     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
00924       if (CFP->getType()->isFloatTy()) {
00925         SmallVector<uint32_t, 16> Elts;
00926         for (unsigned i = 0, e = V.size(); i != e; ++i)
00927           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
00928             Elts.push_back(
00929                 CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
00930           else
00931             break;
00932         if (Elts.size() == V.size())
00933           return ConstantDataArray::getFP(C->getContext(), Elts);
00934       } else if (CFP->getType()->isDoubleTy()) {
00935         SmallVector<uint64_t, 16> Elts;
00936         for (unsigned i = 0, e = V.size(); i != e; ++i)
00937           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
00938             Elts.push_back(
00939                 CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
00940           else
00941             break;
00942         if (Elts.size() == V.size())
00943           return ConstantDataArray::getFP(C->getContext(), Elts);
00944       }
00945     }
00946   }
00947 
00948   // Otherwise, we really do want to create a ConstantArray.
00949   return nullptr;
00950 }
00951 
00952 /// getTypeForElements - Return an anonymous struct type to use for a constant
00953 /// with the specified set of elements.  The list must not be empty.
00954 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
00955                                                ArrayRef<Constant*> V,
00956                                                bool Packed) {
00957   unsigned VecSize = V.size();
00958   SmallVector<Type*, 16> EltTypes(VecSize);
00959   for (unsigned i = 0; i != VecSize; ++i)
00960     EltTypes[i] = V[i]->getType();
00961 
00962   return StructType::get(Context, EltTypes, Packed);
00963 }
00964 
00965 
00966 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
00967                                                bool Packed) {
00968   assert(!V.empty() &&
00969          "ConstantStruct::getTypeForElements cannot be called on empty list");
00970   return getTypeForElements(V[0]->getContext(), V, Packed);
00971 }
00972 
00973 
00974 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
00975   : Constant(T, ConstantStructVal,
00976              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
00977              V.size()) {
00978   assert(V.size() == T->getNumElements() &&
00979          "Invalid initializer vector for constant structure");
00980   for (unsigned i = 0, e = V.size(); i != e; ++i)
00981     assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
00982            "Initializer for struct element doesn't match struct element type!");
00983   std::copy(V.begin(), V.end(), op_begin());
00984 }
00985 
00986 // ConstantStruct accessors.
00987 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
00988   assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
00989          "Incorrect # elements specified to ConstantStruct::get");
00990 
00991   // Create a ConstantAggregateZero value if all elements are zeros.
00992   bool isZero = true;
00993   bool isUndef = false;
00994   
00995   if (!V.empty()) {
00996     isUndef = isa<UndefValue>(V[0]);
00997     isZero = V[0]->isNullValue();
00998     if (isUndef || isZero) {
00999       for (unsigned i = 0, e = V.size(); i != e; ++i) {
01000         if (!V[i]->isNullValue())
01001           isZero = false;
01002         if (!isa<UndefValue>(V[i]))
01003           isUndef = false;
01004       }
01005     }
01006   }
01007   if (isZero)
01008     return ConstantAggregateZero::get(ST);
01009   if (isUndef)
01010     return UndefValue::get(ST);
01011 
01012   return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
01013 }
01014 
01015 Constant *ConstantStruct::get(StructType *T, ...) {
01016   va_list ap;
01017   SmallVector<Constant*, 8> Values;
01018   va_start(ap, T);
01019   while (Constant *Val = va_arg(ap, llvm::Constant*))
01020     Values.push_back(Val);
01021   va_end(ap);
01022   return get(T, Values);
01023 }
01024 
01025 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
01026   : Constant(T, ConstantVectorVal,
01027              OperandTraits<ConstantVector>::op_end(this) - V.size(),
01028              V.size()) {
01029   for (size_t i = 0, e = V.size(); i != e; i++)
01030     assert(V[i]->getType() == T->getElementType() &&
01031            "Initializer for vector element doesn't match vector element type!");
01032   std::copy(V.begin(), V.end(), op_begin());
01033 }
01034 
01035 // ConstantVector accessors.
01036 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
01037   if (Constant *C = getImpl(V))
01038     return C;
01039   VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
01040   return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
01041 }
01042 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
01043   assert(!V.empty() && "Vectors can't be empty");
01044   VectorType *T = VectorType::get(V.front()->getType(), V.size());
01045 
01046   // If this is an all-undef or all-zero vector, return a
01047   // ConstantAggregateZero or UndefValue.
01048   Constant *C = V[0];
01049   bool isZero = C->isNullValue();
01050   bool isUndef = isa<UndefValue>(C);
01051 
01052   if (isZero || isUndef) {
01053     for (unsigned i = 1, e = V.size(); i != e; ++i)
01054       if (V[i] != C) {
01055         isZero = isUndef = false;
01056         break;
01057       }
01058   }
01059 
01060   if (isZero)
01061     return ConstantAggregateZero::get(T);
01062   if (isUndef)
01063     return UndefValue::get(T);
01064 
01065   // Check to see if all of the elements are ConstantFP or ConstantInt and if
01066   // the element type is compatible with ConstantDataVector.  If so, use it.
01067   if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
01068     // We speculatively build the elements here even if it turns out that there
01069     // is a constantexpr or something else weird in the array, since it is so
01070     // uncommon for that to happen.
01071     if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
01072       if (CI->getType()->isIntegerTy(8)) {
01073         SmallVector<uint8_t, 16> Elts;
01074         for (unsigned i = 0, e = V.size(); i != e; ++i)
01075           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
01076             Elts.push_back(CI->getZExtValue());
01077           else
01078             break;
01079         if (Elts.size() == V.size())
01080           return ConstantDataVector::get(C->getContext(), Elts);
01081       } else if (CI->getType()->isIntegerTy(16)) {
01082         SmallVector<uint16_t, 16> Elts;
01083         for (unsigned i = 0, e = V.size(); i != e; ++i)
01084           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
01085             Elts.push_back(CI->getZExtValue());
01086           else
01087             break;
01088         if (Elts.size() == V.size())
01089           return ConstantDataVector::get(C->getContext(), Elts);
01090       } else if (CI->getType()->isIntegerTy(32)) {
01091         SmallVector<uint32_t, 16> Elts;
01092         for (unsigned i = 0, e = V.size(); i != e; ++i)
01093           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
01094             Elts.push_back(CI->getZExtValue());
01095           else
01096             break;
01097         if (Elts.size() == V.size())
01098           return ConstantDataVector::get(C->getContext(), Elts);
01099       } else if (CI->getType()->isIntegerTy(64)) {
01100         SmallVector<uint64_t, 16> Elts;
01101         for (unsigned i = 0, e = V.size(); i != e; ++i)
01102           if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
01103             Elts.push_back(CI->getZExtValue());
01104           else
01105             break;
01106         if (Elts.size() == V.size())
01107           return ConstantDataVector::get(C->getContext(), Elts);
01108       }
01109     }
01110 
01111     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
01112       if (CFP->getType()->isFloatTy()) {
01113         SmallVector<uint32_t, 16> Elts;
01114         for (unsigned i = 0, e = V.size(); i != e; ++i)
01115           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
01116             Elts.push_back(
01117                 CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
01118           else
01119             break;
01120         if (Elts.size() == V.size())
01121           return ConstantDataVector::getFP(C->getContext(), Elts);
01122       } else if (CFP->getType()->isDoubleTy()) {
01123         SmallVector<uint64_t, 16> Elts;
01124         for (unsigned i = 0, e = V.size(); i != e; ++i)
01125           if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
01126             Elts.push_back(
01127                 CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
01128           else
01129             break;
01130         if (Elts.size() == V.size())
01131           return ConstantDataVector::getFP(C->getContext(), Elts);
01132       }
01133     }
01134   }
01135 
01136   // Otherwise, the element type isn't compatible with ConstantDataVector, or
01137   // the operand list constants a ConstantExpr or something else strange.
01138   return nullptr;
01139 }
01140 
01141 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
01142   // If this splat is compatible with ConstantDataVector, use it instead of
01143   // ConstantVector.
01144   if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
01145       ConstantDataSequential::isElementTypeCompatible(V->getType()))
01146     return ConstantDataVector::getSplat(NumElts, V);
01147 
01148   SmallVector<Constant*, 32> Elts(NumElts, V);
01149   return get(Elts);
01150 }
01151 
01152 
01153 // Utility function for determining if a ConstantExpr is a CastOp or not. This
01154 // can't be inline because we don't want to #include Instruction.h into
01155 // Constant.h
01156 bool ConstantExpr::isCast() const {
01157   return Instruction::isCast(getOpcode());
01158 }
01159 
01160 bool ConstantExpr::isCompare() const {
01161   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
01162 }
01163 
01164 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
01165   if (getOpcode() != Instruction::GetElementPtr) return false;
01166 
01167   gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
01168   User::const_op_iterator OI = std::next(this->op_begin());
01169 
01170   // Skip the first index, as it has no static limit.
01171   ++GEPI;
01172   ++OI;
01173 
01174   // The remaining indices must be compile-time known integers within the
01175   // bounds of the corresponding notional static array types.
01176   for (; GEPI != E; ++GEPI, ++OI) {
01177     ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
01178     if (!CI) return false;
01179     if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
01180       if (CI->getValue().getActiveBits() > 64 ||
01181           CI->getZExtValue() >= ATy->getNumElements())
01182         return false;
01183   }
01184 
01185   // All the indices checked out.
01186   return true;
01187 }
01188 
01189 bool ConstantExpr::hasIndices() const {
01190   return getOpcode() == Instruction::ExtractValue ||
01191          getOpcode() == Instruction::InsertValue;
01192 }
01193 
01194 ArrayRef<unsigned> ConstantExpr::getIndices() const {
01195   if (const ExtractValueConstantExpr *EVCE =
01196         dyn_cast<ExtractValueConstantExpr>(this))
01197     return EVCE->Indices;
01198 
01199   return cast<InsertValueConstantExpr>(this)->Indices;
01200 }
01201 
01202 unsigned ConstantExpr::getPredicate() const {
01203   assert(isCompare());
01204   return ((const CompareConstantExpr*)this)->predicate;
01205 }
01206 
01207 /// getWithOperandReplaced - Return a constant expression identical to this
01208 /// one, but with the specified operand set to the specified value.
01209 Constant *
01210 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
01211   assert(Op->getType() == getOperand(OpNo)->getType() &&
01212          "Replacing operand with value of different type!");
01213   if (getOperand(OpNo) == Op)
01214     return const_cast<ConstantExpr*>(this);
01215 
01216   SmallVector<Constant*, 8> NewOps;
01217   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
01218     NewOps.push_back(i == OpNo ? Op : getOperand(i));
01219 
01220   return getWithOperands(NewOps);
01221 }
01222 
01223 /// getWithOperands - This returns the current constant expression with the
01224 /// operands replaced with the specified values.  The specified array must
01225 /// have the same number of operands as our current one.
01226 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
01227                                         bool OnlyIfReduced) const {
01228   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
01229 
01230   // If no operands changed return self.
01231   if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
01232     return const_cast<ConstantExpr*>(this);
01233 
01234   Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
01235   switch (getOpcode()) {
01236   case Instruction::Trunc:
01237   case Instruction::ZExt:
01238   case Instruction::SExt:
01239   case Instruction::FPTrunc:
01240   case Instruction::FPExt:
01241   case Instruction::UIToFP:
01242   case Instruction::SIToFP:
01243   case Instruction::FPToUI:
01244   case Instruction::FPToSI:
01245   case Instruction::PtrToInt:
01246   case Instruction::IntToPtr:
01247   case Instruction::BitCast:
01248   case Instruction::AddrSpaceCast:
01249     return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
01250   case Instruction::Select:
01251     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
01252   case Instruction::InsertElement:
01253     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
01254                                           OnlyIfReducedTy);
01255   case Instruction::ExtractElement:
01256     return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
01257   case Instruction::InsertValue:
01258     return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
01259                                         OnlyIfReducedTy);
01260   case Instruction::ExtractValue:
01261     return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
01262   case Instruction::ShuffleVector:
01263     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
01264                                           OnlyIfReducedTy);
01265   case Instruction::GetElementPtr:
01266     return ConstantExpr::getGetElementPtr(nullptr, Ops[0], Ops.slice(1),
01267                                           cast<GEPOperator>(this)->isInBounds(),
01268                                           OnlyIfReducedTy);
01269   case Instruction::ICmp:
01270   case Instruction::FCmp:
01271     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
01272                                     OnlyIfReducedTy);
01273   default:
01274     assert(getNumOperands() == 2 && "Must be binary operator?");
01275     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
01276                              OnlyIfReducedTy);
01277   }
01278 }
01279 
01280 
01281 //===----------------------------------------------------------------------===//
01282 //                      isValueValidForType implementations
01283 
01284 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
01285   unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
01286   if (Ty->isIntegerTy(1))
01287     return Val == 0 || Val == 1;
01288   if (NumBits >= 64)
01289     return true; // always true, has to fit in largest type
01290   uint64_t Max = (1ll << NumBits) - 1;
01291   return Val <= Max;
01292 }
01293 
01294 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
01295   unsigned NumBits = Ty->getIntegerBitWidth();
01296   if (Ty->isIntegerTy(1))
01297     return Val == 0 || Val == 1 || Val == -1;
01298   if (NumBits >= 64)
01299     return true; // always true, has to fit in largest type
01300   int64_t Min = -(1ll << (NumBits-1));
01301   int64_t Max = (1ll << (NumBits-1)) - 1;
01302   return (Val >= Min && Val <= Max);
01303 }
01304 
01305 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
01306   // convert modifies in place, so make a copy.
01307   APFloat Val2 = APFloat(Val);
01308   bool losesInfo;
01309   switch (Ty->getTypeID()) {
01310   default:
01311     return false;         // These can't be represented as floating point!
01312 
01313   // FIXME rounding mode needs to be more flexible
01314   case Type::HalfTyID: {
01315     if (&Val2.getSemantics() == &APFloat::IEEEhalf)
01316       return true;
01317     Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
01318     return !losesInfo;
01319   }
01320   case Type::FloatTyID: {
01321     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
01322       return true;
01323     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
01324     return !losesInfo;
01325   }
01326   case Type::DoubleTyID: {
01327     if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
01328         &Val2.getSemantics() == &APFloat::IEEEsingle ||
01329         &Val2.getSemantics() == &APFloat::IEEEdouble)
01330       return true;
01331     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
01332     return !losesInfo;
01333   }
01334   case Type::X86_FP80TyID:
01335     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
01336            &Val2.getSemantics() == &APFloat::IEEEsingle || 
01337            &Val2.getSemantics() == &APFloat::IEEEdouble ||
01338            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
01339   case Type::FP128TyID:
01340     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
01341            &Val2.getSemantics() == &APFloat::IEEEsingle || 
01342            &Val2.getSemantics() == &APFloat::IEEEdouble ||
01343            &Val2.getSemantics() == &APFloat::IEEEquad;
01344   case Type::PPC_FP128TyID:
01345     return &Val2.getSemantics() == &APFloat::IEEEhalf ||
01346            &Val2.getSemantics() == &APFloat::IEEEsingle || 
01347            &Val2.getSemantics() == &APFloat::IEEEdouble ||
01348            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
01349   }
01350 }
01351 
01352 
01353 //===----------------------------------------------------------------------===//
01354 //                      Factory Function Implementation
01355 
01356 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
01357   assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
01358          "Cannot create an aggregate zero of non-aggregate type!");
01359   
01360   ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
01361   if (!Entry)
01362     Entry = new ConstantAggregateZero(Ty);
01363 
01364   return Entry;
01365 }
01366 
01367 /// destroyConstant - Remove the constant from the constant table.
01368 ///
01369 void ConstantAggregateZero::destroyConstant() {
01370   getContext().pImpl->CAZConstants.erase(getType());
01371   destroyConstantImpl();
01372 }
01373 
01374 /// destroyConstant - Remove the constant from the constant table...
01375 ///
01376 void ConstantArray::destroyConstant() {
01377   getType()->getContext().pImpl->ArrayConstants.remove(this);
01378   destroyConstantImpl();
01379 }
01380 
01381 
01382 //---- ConstantStruct::get() implementation...
01383 //
01384 
01385 // destroyConstant - Remove the constant from the constant table...
01386 //
01387 void ConstantStruct::destroyConstant() {
01388   getType()->getContext().pImpl->StructConstants.remove(this);
01389   destroyConstantImpl();
01390 }
01391 
01392 // destroyConstant - Remove the constant from the constant table...
01393 //
01394 void ConstantVector::destroyConstant() {
01395   getType()->getContext().pImpl->VectorConstants.remove(this);
01396   destroyConstantImpl();
01397 }
01398 
01399 /// getSplatValue - If this is a splat vector constant, meaning that all of
01400 /// the elements have the same value, return that value. Otherwise return 0.
01401 Constant *Constant::getSplatValue() const {
01402   assert(this->getType()->isVectorTy() && "Only valid for vectors!");
01403   if (isa<ConstantAggregateZero>(this))
01404     return getNullValue(this->getType()->getVectorElementType());
01405   if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
01406     return CV->getSplatValue();
01407   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
01408     return CV->getSplatValue();
01409   return nullptr;
01410 }
01411 
01412 /// getSplatValue - If this is a splat constant, where all of the
01413 /// elements have the same value, return that value. Otherwise return null.
01414 Constant *ConstantVector::getSplatValue() const {
01415   // Check out first element.
01416   Constant *Elt = getOperand(0);
01417   // Then make sure all remaining elements point to the same value.
01418   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
01419     if (getOperand(I) != Elt)
01420       return nullptr;
01421   return Elt;
01422 }
01423 
01424 /// If C is a constant integer then return its value, otherwise C must be a
01425 /// vector of constant integers, all equal, and the common value is returned.
01426 const APInt &Constant::getUniqueInteger() const {
01427   if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
01428     return CI->getValue();
01429   assert(this->getSplatValue() && "Doesn't contain a unique integer!");
01430   const Constant *C = this->getAggregateElement(0U);
01431   assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
01432   return cast<ConstantInt>(C)->getValue();
01433 }
01434 
01435 
01436 //---- ConstantPointerNull::get() implementation.
01437 //
01438 
01439 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
01440   ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
01441   if (!Entry)
01442     Entry = new ConstantPointerNull(Ty);
01443 
01444   return Entry;
01445 }
01446 
01447 // destroyConstant - Remove the constant from the constant table...
01448 //
01449 void ConstantPointerNull::destroyConstant() {
01450   getContext().pImpl->CPNConstants.erase(getType());
01451   // Free the constant and any dangling references to it.
01452   destroyConstantImpl();
01453 }
01454 
01455 
01456 //---- UndefValue::get() implementation.
01457 //
01458 
01459 UndefValue *UndefValue::get(Type *Ty) {
01460   UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
01461   if (!Entry)
01462     Entry = new UndefValue(Ty);
01463 
01464   return Entry;
01465 }
01466 
01467 // destroyConstant - Remove the constant from the constant table.
01468 //
01469 void UndefValue::destroyConstant() {
01470   // Free the constant and any dangling references to it.
01471   getContext().pImpl->UVConstants.erase(getType());
01472   destroyConstantImpl();
01473 }
01474 
01475 //---- BlockAddress::get() implementation.
01476 //
01477 
01478 BlockAddress *BlockAddress::get(BasicBlock *BB) {
01479   assert(BB->getParent() && "Block must have a parent");
01480   return get(BB->getParent(), BB);
01481 }
01482 
01483 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
01484   BlockAddress *&BA =
01485     F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
01486   if (!BA)
01487     BA = new BlockAddress(F, BB);
01488 
01489   assert(BA->getFunction() == F && "Basic block moved between functions");
01490   return BA;
01491 }
01492 
01493 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
01494 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
01495            &Op<0>(), 2) {
01496   setOperand(0, F);
01497   setOperand(1, BB);
01498   BB->AdjustBlockAddressRefCount(1);
01499 }
01500 
01501 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
01502   if (!BB->hasAddressTaken())
01503     return nullptr;
01504 
01505   const Function *F = BB->getParent();
01506   assert(F && "Block must have a parent");
01507   BlockAddress *BA =
01508       F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
01509   assert(BA && "Refcount and block address map disagree!");
01510   return BA;
01511 }
01512 
01513 // destroyConstant - Remove the constant from the constant table.
01514 //
01515 void BlockAddress::destroyConstant() {
01516   getFunction()->getType()->getContext().pImpl
01517     ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
01518   getBasicBlock()->AdjustBlockAddressRefCount(-1);
01519   destroyConstantImpl();
01520 }
01521 
01522 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
01523   // This could be replacing either the Basic Block or the Function.  In either
01524   // case, we have to remove the map entry.
01525   Function *NewF = getFunction();
01526   BasicBlock *NewBB = getBasicBlock();
01527 
01528   if (U == &Op<0>())
01529     NewF = cast<Function>(To->stripPointerCasts());
01530   else
01531     NewBB = cast<BasicBlock>(To);
01532 
01533   // See if the 'new' entry already exists, if not, just update this in place
01534   // and return early.
01535   BlockAddress *&NewBA =
01536     getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
01537   if (NewBA) {
01538     replaceUsesOfWithOnConstantImpl(NewBA);
01539     return;
01540   }
01541 
01542   getBasicBlock()->AdjustBlockAddressRefCount(-1);
01543 
01544   // Remove the old entry, this can't cause the map to rehash (just a
01545   // tombstone will get added).
01546   getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
01547                                                           getBasicBlock()));
01548   NewBA = this;
01549   setOperand(0, NewF);
01550   setOperand(1, NewBB);
01551   getBasicBlock()->AdjustBlockAddressRefCount(1);
01552 }
01553 
01554 //---- ConstantExpr::get() implementations.
01555 //
01556 
01557 /// This is a utility function to handle folding of casts and lookup of the
01558 /// cast in the ExprConstants map. It is used by the various get* methods below.
01559 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
01560                                bool OnlyIfReduced = false) {
01561   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
01562   // Fold a few common cases
01563   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
01564     return FC;
01565 
01566   if (OnlyIfReduced)
01567     return nullptr;
01568 
01569   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
01570 
01571   // Look up the constant in the table first to ensure uniqueness.
01572   ConstantExprKeyType Key(opc, C);
01573 
01574   return pImpl->ExprConstants.getOrCreate(Ty, Key);
01575 }
01576 
01577 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
01578                                 bool OnlyIfReduced) {
01579   Instruction::CastOps opc = Instruction::CastOps(oc);
01580   assert(Instruction::isCast(opc) && "opcode out of range");
01581   assert(C && Ty && "Null arguments to getCast");
01582   assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
01583 
01584   switch (opc) {
01585   default:
01586     llvm_unreachable("Invalid cast opcode");
01587   case Instruction::Trunc:
01588     return getTrunc(C, Ty, OnlyIfReduced);
01589   case Instruction::ZExt:
01590     return getZExt(C, Ty, OnlyIfReduced);
01591   case Instruction::SExt:
01592     return getSExt(C, Ty, OnlyIfReduced);
01593   case Instruction::FPTrunc:
01594     return getFPTrunc(C, Ty, OnlyIfReduced);
01595   case Instruction::FPExt:
01596     return getFPExtend(C, Ty, OnlyIfReduced);
01597   case Instruction::UIToFP:
01598     return getUIToFP(C, Ty, OnlyIfReduced);
01599   case Instruction::SIToFP:
01600     return getSIToFP(C, Ty, OnlyIfReduced);
01601   case Instruction::FPToUI:
01602     return getFPToUI(C, Ty, OnlyIfReduced);
01603   case Instruction::FPToSI:
01604     return getFPToSI(C, Ty, OnlyIfReduced);
01605   case Instruction::PtrToInt:
01606     return getPtrToInt(C, Ty, OnlyIfReduced);
01607   case Instruction::IntToPtr:
01608     return getIntToPtr(C, Ty, OnlyIfReduced);
01609   case Instruction::BitCast:
01610     return getBitCast(C, Ty, OnlyIfReduced);
01611   case Instruction::AddrSpaceCast:
01612     return getAddrSpaceCast(C, Ty, OnlyIfReduced);
01613   }
01614 }
01615 
01616 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
01617   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01618     return getBitCast(C, Ty);
01619   return getZExt(C, Ty);
01620 }
01621 
01622 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
01623   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01624     return getBitCast(C, Ty);
01625   return getSExt(C, Ty);
01626 }
01627 
01628 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
01629   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01630     return getBitCast(C, Ty);
01631   return getTrunc(C, Ty);
01632 }
01633 
01634 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
01635   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
01636   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
01637           "Invalid cast");
01638 
01639   if (Ty->isIntOrIntVectorTy())
01640     return getPtrToInt(S, Ty);
01641 
01642   unsigned SrcAS = S->getType()->getPointerAddressSpace();
01643   if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
01644     return getAddrSpaceCast(S, Ty);
01645 
01646   return getBitCast(S, Ty);
01647 }
01648 
01649 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
01650                                                          Type *Ty) {
01651   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
01652   assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
01653 
01654   if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
01655     return getAddrSpaceCast(S, Ty);
01656 
01657   return getBitCast(S, Ty);
01658 }
01659 
01660 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
01661                                        bool isSigned) {
01662   assert(C->getType()->isIntOrIntVectorTy() &&
01663          Ty->isIntOrIntVectorTy() && "Invalid cast");
01664   unsigned SrcBits = C->getType()->getScalarSizeInBits();
01665   unsigned DstBits = Ty->getScalarSizeInBits();
01666   Instruction::CastOps opcode =
01667     (SrcBits == DstBits ? Instruction::BitCast :
01668      (SrcBits > DstBits ? Instruction::Trunc :
01669       (isSigned ? Instruction::SExt : Instruction::ZExt)));
01670   return getCast(opcode, C, Ty);
01671 }
01672 
01673 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
01674   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
01675          "Invalid cast");
01676   unsigned SrcBits = C->getType()->getScalarSizeInBits();
01677   unsigned DstBits = Ty->getScalarSizeInBits();
01678   if (SrcBits == DstBits)
01679     return C; // Avoid a useless cast
01680   Instruction::CastOps opcode =
01681     (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
01682   return getCast(opcode, C, Ty);
01683 }
01684 
01685 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
01686 #ifndef NDEBUG
01687   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01688   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01689 #endif
01690   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01691   assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
01692   assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
01693   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
01694          "SrcTy must be larger than DestTy for Trunc!");
01695 
01696   return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
01697 }
01698 
01699 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
01700 #ifndef NDEBUG
01701   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01702   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01703 #endif
01704   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01705   assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
01706   assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
01707   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
01708          "SrcTy must be smaller than DestTy for SExt!");
01709 
01710   return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
01711 }
01712 
01713 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
01714 #ifndef NDEBUG
01715   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01716   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01717 #endif
01718   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01719   assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
01720   assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
01721   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
01722          "SrcTy must be smaller than DestTy for ZExt!");
01723 
01724   return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
01725 }
01726 
01727 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
01728 #ifndef NDEBUG
01729   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01730   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01731 #endif
01732   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01733   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
01734          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
01735          "This is an illegal floating point truncation!");
01736   return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
01737 }
01738 
01739 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
01740 #ifndef NDEBUG
01741   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01742   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01743 #endif
01744   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01745   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
01746          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
01747          "This is an illegal floating point extension!");
01748   return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
01749 }
01750 
01751 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
01752 #ifndef NDEBUG
01753   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01754   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01755 #endif
01756   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01757   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
01758          "This is an illegal uint to floating point cast!");
01759   return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
01760 }
01761 
01762 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
01763 #ifndef NDEBUG
01764   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01765   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01766 #endif
01767   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01768   assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
01769          "This is an illegal sint to floating point cast!");
01770   return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
01771 }
01772 
01773 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
01774 #ifndef NDEBUG
01775   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01776   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01777 #endif
01778   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01779   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
01780          "This is an illegal floating point to uint cast!");
01781   return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
01782 }
01783 
01784 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
01785 #ifndef NDEBUG
01786   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01787   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01788 #endif
01789   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01790   assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
01791          "This is an illegal floating point to sint cast!");
01792   return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
01793 }
01794 
01795 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
01796                                     bool OnlyIfReduced) {
01797   assert(C->getType()->getScalarType()->isPointerTy() &&
01798          "PtrToInt source must be pointer or pointer vector");
01799   assert(DstTy->getScalarType()->isIntegerTy() && 
01800          "PtrToInt destination must be integer or integer vector");
01801   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
01802   if (isa<VectorType>(C->getType()))
01803     assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
01804            "Invalid cast between a different number of vector elements");
01805   return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
01806 }
01807 
01808 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
01809                                     bool OnlyIfReduced) {
01810   assert(C->getType()->getScalarType()->isIntegerTy() &&
01811          "IntToPtr source must be integer or integer vector");
01812   assert(DstTy->getScalarType()->isPointerTy() &&
01813          "IntToPtr destination must be a pointer or pointer vector");
01814   assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
01815   if (isa<VectorType>(C->getType()))
01816     assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
01817            "Invalid cast between a different number of vector elements");
01818   return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
01819 }
01820 
01821 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
01822                                    bool OnlyIfReduced) {
01823   assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
01824          "Invalid constantexpr bitcast!");
01825 
01826   // It is common to ask for a bitcast of a value to its own type, handle this
01827   // speedily.
01828   if (C->getType() == DstTy) return C;
01829 
01830   return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
01831 }
01832 
01833 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
01834                                          bool OnlyIfReduced) {
01835   assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
01836          "Invalid constantexpr addrspacecast!");
01837 
01838   // Canonicalize addrspacecasts between different pointer types by first
01839   // bitcasting the pointer type and then converting the address space.
01840   PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
01841   PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
01842   Type *DstElemTy = DstScalarTy->getElementType();
01843   if (SrcScalarTy->getElementType() != DstElemTy) {
01844     Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
01845     if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
01846       // Handle vectors of pointers.
01847       MidTy = VectorType::get(MidTy, VT->getNumElements());
01848     }
01849     C = getBitCast(C, MidTy);
01850   }
01851   return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
01852 }
01853 
01854 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
01855                             unsigned Flags, Type *OnlyIfReducedTy) {
01856   // Check the operands for consistency first.
01857   assert(Opcode >= Instruction::BinaryOpsBegin &&
01858          Opcode <  Instruction::BinaryOpsEnd   &&
01859          "Invalid opcode in binary constant expression");
01860   assert(C1->getType() == C2->getType() &&
01861          "Operand types in binary constant expression should match");
01862 
01863 #ifndef NDEBUG
01864   switch (Opcode) {
01865   case Instruction::Add:
01866   case Instruction::Sub:
01867   case Instruction::Mul:
01868     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01869     assert(C1->getType()->isIntOrIntVectorTy() &&
01870            "Tried to create an integer operation on a non-integer type!");
01871     break;
01872   case Instruction::FAdd:
01873   case Instruction::FSub:
01874   case Instruction::FMul:
01875     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01876     assert(C1->getType()->isFPOrFPVectorTy() &&
01877            "Tried to create a floating-point operation on a "
01878            "non-floating-point type!");
01879     break;
01880   case Instruction::UDiv: 
01881   case Instruction::SDiv: 
01882     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01883     assert(C1->getType()->isIntOrIntVectorTy() &&
01884            "Tried to create an arithmetic operation on a non-arithmetic type!");
01885     break;
01886   case Instruction::FDiv:
01887     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01888     assert(C1->getType()->isFPOrFPVectorTy() &&
01889            "Tried to create an arithmetic operation on a non-arithmetic type!");
01890     break;
01891   case Instruction::URem: 
01892   case Instruction::SRem: 
01893     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01894     assert(C1->getType()->isIntOrIntVectorTy() &&
01895            "Tried to create an arithmetic operation on a non-arithmetic type!");
01896     break;
01897   case Instruction::FRem:
01898     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01899     assert(C1->getType()->isFPOrFPVectorTy() &&
01900            "Tried to create an arithmetic operation on a non-arithmetic type!");
01901     break;
01902   case Instruction::And:
01903   case Instruction::Or:
01904   case Instruction::Xor:
01905     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01906     assert(C1->getType()->isIntOrIntVectorTy() &&
01907            "Tried to create a logical operation on a non-integral type!");
01908     break;
01909   case Instruction::Shl:
01910   case Instruction::LShr:
01911   case Instruction::AShr:
01912     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01913     assert(C1->getType()->isIntOrIntVectorTy() &&
01914            "Tried to create a shift operation on a non-integer type!");
01915     break;
01916   default:
01917     break;
01918   }
01919 #endif
01920 
01921   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
01922     return FC;          // Fold a few common cases.
01923 
01924   if (OnlyIfReducedTy == C1->getType())
01925     return nullptr;
01926 
01927   Constant *ArgVec[] = { C1, C2 };
01928   ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
01929 
01930   LLVMContextImpl *pImpl = C1->getContext().pImpl;
01931   return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
01932 }
01933 
01934 Constant *ConstantExpr::getSizeOf(Type* Ty) {
01935   // sizeof is implemented as: (i64) gep (Ty*)null, 1
01936   // Note that a non-inbounds gep is used, as null isn't within any object.
01937   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
01938   Constant *GEP = getGetElementPtr(
01939       Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
01940   return getPtrToInt(GEP, 
01941                      Type::getInt64Ty(Ty->getContext()));
01942 }
01943 
01944 Constant *ConstantExpr::getAlignOf(Type* Ty) {
01945   // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
01946   // Note that a non-inbounds gep is used, as null isn't within any object.
01947   Type *AligningTy = 
01948     StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, nullptr);
01949   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
01950   Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
01951   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
01952   Constant *Indices[2] = { Zero, One };
01953   Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
01954   return getPtrToInt(GEP,
01955                      Type::getInt64Ty(Ty->getContext()));
01956 }
01957 
01958 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
01959   return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
01960                                            FieldNo));
01961 }
01962 
01963 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
01964   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
01965   // Note that a non-inbounds gep is used, as null isn't within any object.
01966   Constant *GEPIdx[] = {
01967     ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
01968     FieldNo
01969   };
01970   Constant *GEP = getGetElementPtr(
01971       Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
01972   return getPtrToInt(GEP,
01973                      Type::getInt64Ty(Ty->getContext()));
01974 }
01975 
01976 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
01977                                    Constant *C2, bool OnlyIfReduced) {
01978   assert(C1->getType() == C2->getType() && "Op types should be identical!");
01979 
01980   switch (Predicate) {
01981   default: llvm_unreachable("Invalid CmpInst predicate");
01982   case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
01983   case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
01984   case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
01985   case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
01986   case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
01987   case CmpInst::FCMP_TRUE:
01988     return getFCmp(Predicate, C1, C2, OnlyIfReduced);
01989 
01990   case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
01991   case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
01992   case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
01993   case CmpInst::ICMP_SLE:
01994     return getICmp(Predicate, C1, C2, OnlyIfReduced);
01995   }
01996 }
01997 
01998 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
01999                                   Type *OnlyIfReducedTy) {
02000   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
02001 
02002   if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
02003     return SC;        // Fold common cases
02004 
02005   if (OnlyIfReducedTy == V1->getType())
02006     return nullptr;
02007 
02008   Constant *ArgVec[] = { C, V1, V2 };
02009   ConstantExprKeyType Key(Instruction::Select, ArgVec);
02010 
02011   LLVMContextImpl *pImpl = C->getContext().pImpl;
02012   return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
02013 }
02014 
02015 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
02016                                          ArrayRef<Value *> Idxs, bool InBounds,
02017                                          Type *OnlyIfReducedTy) {
02018   if (!Ty)
02019     Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
02020   else
02021     assert(
02022         Ty ==
02023         cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
02024 
02025   if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InBounds, Idxs))
02026     return FC;          // Fold a few common cases.
02027 
02028   // Get the result type of the getelementptr!
02029   Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
02030   assert(DestTy && "GEP indices invalid!");
02031   unsigned AS = C->getType()->getPointerAddressSpace();
02032   Type *ReqTy = DestTy->getPointerTo(AS);
02033   if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
02034     ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
02035 
02036   if (OnlyIfReducedTy == ReqTy)
02037     return nullptr;
02038 
02039   // Look up the constant in the table first to ensure uniqueness
02040   std::vector<Constant*> ArgVec;
02041   ArgVec.reserve(1 + Idxs.size());
02042   ArgVec.push_back(C);
02043   for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
02044     assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
02045            "getelementptr index type missmatch");
02046     assert((!Idxs[i]->getType()->isVectorTy() ||
02047             ReqTy->getVectorNumElements() ==
02048             Idxs[i]->getType()->getVectorNumElements()) &&
02049            "getelementptr index type missmatch");
02050     ArgVec.push_back(cast<Constant>(Idxs[i]));
02051   }
02052   const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
02053                                 InBounds ? GEPOperator::IsInBounds : 0, None,
02054                                 Ty);
02055 
02056   LLVMContextImpl *pImpl = C->getContext().pImpl;
02057   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
02058 }
02059 
02060 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
02061                                 Constant *RHS, bool OnlyIfReduced) {
02062   assert(LHS->getType() == RHS->getType());
02063   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
02064          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
02065 
02066   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
02067     return FC;          // Fold a few common cases...
02068 
02069   if (OnlyIfReduced)
02070     return nullptr;
02071 
02072   // Look up the constant in the table first to ensure uniqueness
02073   Constant *ArgVec[] = { LHS, RHS };
02074   // Get the key type with both the opcode and predicate
02075   const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
02076 
02077   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
02078   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
02079     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
02080 
02081   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
02082   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
02083 }
02084 
02085 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
02086                                 Constant *RHS, bool OnlyIfReduced) {
02087   assert(LHS->getType() == RHS->getType());
02088   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
02089 
02090   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
02091     return FC;          // Fold a few common cases...
02092 
02093   if (OnlyIfReduced)
02094     return nullptr;
02095 
02096   // Look up the constant in the table first to ensure uniqueness
02097   Constant *ArgVec[] = { LHS, RHS };
02098   // Get the key type with both the opcode and predicate
02099   const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
02100 
02101   Type *ResultTy = Type::getInt1Ty(LHS->getContext());
02102   if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
02103     ResultTy = VectorType::get(ResultTy, VT->getNumElements());
02104 
02105   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
02106   return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
02107 }
02108 
02109 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
02110                                           Type *OnlyIfReducedTy) {
02111   assert(Val->getType()->isVectorTy() &&
02112          "Tried to create extractelement operation on non-vector type!");
02113   assert(Idx->getType()->isIntegerTy() &&
02114          "Extractelement index must be an integer type!");
02115 
02116   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
02117     return FC;          // Fold a few common cases.
02118 
02119   Type *ReqTy = Val->getType()->getVectorElementType();
02120   if (OnlyIfReducedTy == ReqTy)
02121     return nullptr;
02122 
02123   // Look up the constant in the table first to ensure uniqueness
02124   Constant *ArgVec[] = { Val, Idx };
02125   const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
02126 
02127   LLVMContextImpl *pImpl = Val->getContext().pImpl;
02128   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
02129 }
02130 
02131 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
02132                                          Constant *Idx, Type *OnlyIfReducedTy) {
02133   assert(Val->getType()->isVectorTy() &&
02134          "Tried to create insertelement operation on non-vector type!");
02135   assert(Elt->getType() == Val->getType()->getVectorElementType() &&
02136          "Insertelement types must match!");
02137   assert(Idx->getType()->isIntegerTy() &&
02138          "Insertelement index must be i32 type!");
02139 
02140   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
02141     return FC;          // Fold a few common cases.
02142 
02143   if (OnlyIfReducedTy == Val->getType())
02144     return nullptr;
02145 
02146   // Look up the constant in the table first to ensure uniqueness
02147   Constant *ArgVec[] = { Val, Elt, Idx };
02148   const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
02149 
02150   LLVMContextImpl *pImpl = Val->getContext().pImpl;
02151   return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
02152 }
02153 
02154 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
02155                                          Constant *Mask, Type *OnlyIfReducedTy) {
02156   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
02157          "Invalid shuffle vector constant expr operands!");
02158 
02159   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
02160     return FC;          // Fold a few common cases.
02161 
02162   unsigned NElts = Mask->getType()->getVectorNumElements();
02163   Type *EltTy = V1->getType()->getVectorElementType();
02164   Type *ShufTy = VectorType::get(EltTy, NElts);
02165 
02166   if (OnlyIfReducedTy == ShufTy)
02167     return nullptr;
02168 
02169   // Look up the constant in the table first to ensure uniqueness
02170   Constant *ArgVec[] = { V1, V2, Mask };
02171   const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
02172 
02173   LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
02174   return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
02175 }
02176 
02177 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
02178                                        ArrayRef<unsigned> Idxs,
02179                                        Type *OnlyIfReducedTy) {
02180   assert(Agg->getType()->isFirstClassType() &&
02181          "Non-first-class type for constant insertvalue expression");
02182 
02183   assert(ExtractValueInst::getIndexedType(Agg->getType(),
02184                                           Idxs) == Val->getType() &&
02185          "insertvalue indices invalid!");
02186   Type *ReqTy = Val->getType();
02187 
02188   if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
02189     return FC;
02190 
02191   if (OnlyIfReducedTy == ReqTy)
02192     return nullptr;
02193 
02194   Constant *ArgVec[] = { Agg, Val };
02195   const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
02196 
02197   LLVMContextImpl *pImpl = Agg->getContext().pImpl;
02198   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
02199 }
02200 
02201 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
02202                                         Type *OnlyIfReducedTy) {
02203   assert(Agg->getType()->isFirstClassType() &&
02204          "Tried to create extractelement operation on non-first-class type!");
02205 
02206   Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
02207   (void)ReqTy;
02208   assert(ReqTy && "extractvalue indices invalid!");
02209 
02210   assert(Agg->getType()->isFirstClassType() &&
02211          "Non-first-class type for constant extractvalue expression");
02212   if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
02213     return FC;
02214 
02215   if (OnlyIfReducedTy == ReqTy)
02216     return nullptr;
02217 
02218   Constant *ArgVec[] = { Agg };
02219   const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
02220 
02221   LLVMContextImpl *pImpl = Agg->getContext().pImpl;
02222   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
02223 }
02224 
02225 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
02226   assert(C->getType()->isIntOrIntVectorTy() &&
02227          "Cannot NEG a nonintegral value!");
02228   return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
02229                 C, HasNUW, HasNSW);
02230 }
02231 
02232 Constant *ConstantExpr::getFNeg(Constant *C) {
02233   assert(C->getType()->isFPOrFPVectorTy() &&
02234          "Cannot FNEG a non-floating-point value!");
02235   return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
02236 }
02237 
02238 Constant *ConstantExpr::getNot(Constant *C) {
02239   assert(C->getType()->isIntOrIntVectorTy() &&
02240          "Cannot NOT a nonintegral value!");
02241   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
02242 }
02243 
02244 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
02245                                bool HasNUW, bool HasNSW) {
02246   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
02247                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
02248   return get(Instruction::Add, C1, C2, Flags);
02249 }
02250 
02251 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
02252   return get(Instruction::FAdd, C1, C2);
02253 }
02254 
02255 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
02256                                bool HasNUW, bool HasNSW) {
02257   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
02258                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
02259   return get(Instruction::Sub, C1, C2, Flags);
02260 }
02261 
02262 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
02263   return get(Instruction::FSub, C1, C2);
02264 }
02265 
02266 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
02267                                bool HasNUW, bool HasNSW) {
02268   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
02269                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
02270   return get(Instruction::Mul, C1, C2, Flags);
02271 }
02272 
02273 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
02274   return get(Instruction::FMul, C1, C2);
02275 }
02276 
02277 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
02278   return get(Instruction::UDiv, C1, C2,
02279              isExact ? PossiblyExactOperator::IsExact : 0);
02280 }
02281 
02282 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
02283   return get(Instruction::SDiv, C1, C2,
02284              isExact ? PossiblyExactOperator::IsExact : 0);
02285 }
02286 
02287 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
02288   return get(Instruction::FDiv, C1, C2);
02289 }
02290 
02291 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
02292   return get(Instruction::URem, C1, C2);
02293 }
02294 
02295 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
02296   return get(Instruction::SRem, C1, C2);
02297 }
02298 
02299 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
02300   return get(Instruction::FRem, C1, C2);
02301 }
02302 
02303 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
02304   return get(Instruction::And, C1, C2);
02305 }
02306 
02307 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
02308   return get(Instruction::Or, C1, C2);
02309 }
02310 
02311 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
02312   return get(Instruction::Xor, C1, C2);
02313 }
02314 
02315 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
02316                                bool HasNUW, bool HasNSW) {
02317   unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
02318                    (HasNSW ? OverflowingBinaryOperator::NoSignedWrap   : 0);
02319   return get(Instruction::Shl, C1, C2, Flags);
02320 }
02321 
02322 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
02323   return get(Instruction::LShr, C1, C2,
02324              isExact ? PossiblyExactOperator::IsExact : 0);
02325 }
02326 
02327 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
02328   return get(Instruction::AShr, C1, C2,
02329              isExact ? PossiblyExactOperator::IsExact : 0);
02330 }
02331 
02332 /// getBinOpIdentity - Return the identity for the given binary operation,
02333 /// i.e. a constant C such that X op C = X and C op X = X for every X.  It
02334 /// returns null if the operator doesn't have an identity.
02335 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
02336   switch (Opcode) {
02337   default:
02338     // Doesn't have an identity.
02339     return nullptr;
02340 
02341   case Instruction::Add:
02342   case Instruction::Or:
02343   case Instruction::Xor:
02344     return Constant::getNullValue(Ty);
02345 
02346   case Instruction::Mul:
02347     return ConstantInt::get(Ty, 1);
02348 
02349   case Instruction::And:
02350     return Constant::getAllOnesValue(Ty);
02351   }
02352 }
02353 
02354 /// getBinOpAbsorber - Return the absorbing element for the given binary
02355 /// operation, i.e. a constant C such that X op C = C and C op X = C for
02356 /// every X.  For example, this returns zero for integer multiplication.
02357 /// It returns null if the operator doesn't have an absorbing element.
02358 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
02359   switch (Opcode) {
02360   default:
02361     // Doesn't have an absorber.
02362     return nullptr;
02363 
02364   case Instruction::Or:
02365     return Constant::getAllOnesValue(Ty);
02366 
02367   case Instruction::And:
02368   case Instruction::Mul:
02369     return Constant::getNullValue(Ty);
02370   }
02371 }
02372 
02373 // destroyConstant - Remove the constant from the constant table...
02374 //
02375 void ConstantExpr::destroyConstant() {
02376   getType()->getContext().pImpl->ExprConstants.remove(this);
02377   destroyConstantImpl();
02378 }
02379 
02380 const char *ConstantExpr::getOpcodeName() const {
02381   return Instruction::getOpcodeName(getOpcode());
02382 }
02383 
02384 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
02385     Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
02386     : ConstantExpr(DestTy, Instruction::GetElementPtr,
02387                    OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
02388                        (IdxList.size() + 1),
02389                    IdxList.size() + 1),
02390       SrcElementTy(SrcElementTy) {
02391   Op<0>() = C;
02392   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
02393     OperandList[i+1] = IdxList[i];
02394 }
02395 
02396 Type *GetElementPtrConstantExpr::getSourceElementType() const {
02397   return SrcElementTy;
02398 }
02399 
02400 //===----------------------------------------------------------------------===//
02401 //                       ConstantData* implementations
02402 
02403 void ConstantDataArray::anchor() {}
02404 void ConstantDataVector::anchor() {}
02405 
02406 /// getElementType - Return the element type of the array/vector.
02407 Type *ConstantDataSequential::getElementType() const {
02408   return getType()->getElementType();
02409 }
02410 
02411 StringRef ConstantDataSequential::getRawDataValues() const {
02412   return StringRef(DataElements, getNumElements()*getElementByteSize());
02413 }
02414 
02415 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
02416 /// formed with a vector or array of the specified element type.
02417 /// ConstantDataArray only works with normal float and int types that are
02418 /// stored densely in memory, not with things like i42 or x86_f80.
02419 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
02420   if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
02421   if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
02422     switch (IT->getBitWidth()) {
02423     case 8:
02424     case 16:
02425     case 32:
02426     case 64:
02427       return true;
02428     default: break;
02429     }
02430   }
02431   return false;
02432 }
02433 
02434 /// getNumElements - Return the number of elements in the array or vector.
02435 unsigned ConstantDataSequential::getNumElements() const {
02436   if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
02437     return AT->getNumElements();
02438   return getType()->getVectorNumElements();
02439 }
02440 
02441 
02442 /// getElementByteSize - Return the size in bytes of the elements in the data.
02443 uint64_t ConstantDataSequential::getElementByteSize() const {
02444   return getElementType()->getPrimitiveSizeInBits()/8;
02445 }
02446 
02447 /// getElementPointer - Return the start of the specified element.
02448 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
02449   assert(Elt < getNumElements() && "Invalid Elt");
02450   return DataElements+Elt*getElementByteSize();
02451 }
02452 
02453 
02454 /// isAllZeros - return true if the array is empty or all zeros.
02455 static bool isAllZeros(StringRef Arr) {
02456   for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
02457     if (*I != 0)
02458       return false;
02459   return true;
02460 }
02461 
02462 /// getImpl - This is the underlying implementation of all of the
02463 /// ConstantDataSequential::get methods.  They all thunk down to here, providing
02464 /// the correct element type.  We take the bytes in as a StringRef because
02465 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
02466 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
02467   assert(isElementTypeCompatible(Ty->getSequentialElementType()));
02468   // If the elements are all zero or there are no elements, return a CAZ, which
02469   // is more dense and canonical.
02470   if (isAllZeros(Elements))
02471     return ConstantAggregateZero::get(Ty);
02472 
02473   // Do a lookup to see if we have already formed one of these.
02474   auto &Slot =
02475       *Ty->getContext()
02476            .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
02477            .first;
02478 
02479   // The bucket can point to a linked list of different CDS's that have the same
02480   // body but different types.  For example, 0,0,0,1 could be a 4 element array
02481   // of i8, or a 1-element array of i32.  They'll both end up in the same
02482   /// StringMap bucket, linked up by their Next pointers.  Walk the list.
02483   ConstantDataSequential **Entry = &Slot.second;
02484   for (ConstantDataSequential *Node = *Entry; Node;
02485        Entry = &Node->Next, Node = *Entry)
02486     if (Node->getType() == Ty)
02487       return Node;
02488 
02489   // Okay, we didn't get a hit.  Create a node of the right class, link it in,
02490   // and return it.
02491   if (isa<ArrayType>(Ty))
02492     return *Entry = new ConstantDataArray(Ty, Slot.first().data());
02493 
02494   assert(isa<VectorType>(Ty));
02495   return *Entry = new ConstantDataVector(Ty, Slot.first().data());
02496 }
02497 
02498 void ConstantDataSequential::destroyConstant() {
02499   // Remove the constant from the StringMap.
02500   StringMap<ConstantDataSequential*> &CDSConstants = 
02501     getType()->getContext().pImpl->CDSConstants;
02502 
02503   StringMap<ConstantDataSequential*>::iterator Slot =
02504     CDSConstants.find(getRawDataValues());
02505 
02506   assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
02507 
02508   ConstantDataSequential **Entry = &Slot->getValue();
02509 
02510   // Remove the entry from the hash table.
02511   if (!(*Entry)->Next) {
02512     // If there is only one value in the bucket (common case) it must be this
02513     // entry, and removing the entry should remove the bucket completely.
02514     assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
02515     getContext().pImpl->CDSConstants.erase(Slot);
02516   } else {
02517     // Otherwise, there are multiple entries linked off the bucket, unlink the 
02518     // node we care about but keep the bucket around.
02519     for (ConstantDataSequential *Node = *Entry; ;
02520          Entry = &Node->Next, Node = *Entry) {
02521       assert(Node && "Didn't find entry in its uniquing hash table!");
02522       // If we found our entry, unlink it from the list and we're done.
02523       if (Node == this) {
02524         *Entry = Node->Next;
02525         break;
02526       }
02527     }
02528   }
02529 
02530   // If we were part of a list, make sure that we don't delete the list that is
02531   // still owned by the uniquing map.
02532   Next = nullptr;
02533 
02534   // Finally, actually delete it.
02535   destroyConstantImpl();
02536 }
02537 
02538 /// get() constructors - Return a constant with array type with an element
02539 /// count and element type matching the ArrayRef passed in.  Note that this
02540 /// can return a ConstantAggregateZero object.
02541 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
02542   Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
02543   const char *Data = reinterpret_cast<const char *>(Elts.data());
02544   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
02545 }
02546 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
02547   Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
02548   const char *Data = reinterpret_cast<const char *>(Elts.data());
02549   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
02550 }
02551 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
02552   Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
02553   const char *Data = reinterpret_cast<const char *>(Elts.data());
02554   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
02555 }
02556 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
02557   Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
02558   const char *Data = reinterpret_cast<const char *>(Elts.data());
02559   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
02560 }
02561 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
02562   Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
02563   const char *Data = reinterpret_cast<const char *>(Elts.data());
02564   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
02565 }
02566 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
02567   Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
02568   const char *Data = reinterpret_cast<const char *>(Elts.data());
02569   return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
02570 }
02571 
02572 /// getFP() constructors - Return a constant with array type with an element
02573 /// count and element type of float with precision matching the number of
02574 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
02575 /// double for 64bits) Note that this can return a ConstantAggregateZero
02576 /// object.
02577 Constant *ConstantDataArray::getFP(LLVMContext &Context,
02578                                    ArrayRef<uint16_t> Elts) {
02579   Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
02580   const char *Data = reinterpret_cast<const char *>(Elts.data());
02581   return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
02582 }
02583 Constant *ConstantDataArray::getFP(LLVMContext &Context,
02584                                    ArrayRef<uint32_t> Elts) {
02585   Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
02586   const char *Data = reinterpret_cast<const char *>(Elts.data());
02587   return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
02588 }
02589 Constant *ConstantDataArray::getFP(LLVMContext &Context,
02590                                    ArrayRef<uint64_t> Elts) {
02591   Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
02592   const char *Data = reinterpret_cast<const char *>(Elts.data());
02593   return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
02594 }
02595 
02596 /// getString - This method constructs a CDS and initializes it with a text
02597 /// string. The default behavior (AddNull==true) causes a null terminator to
02598 /// be placed at the end of the array (increasing the length of the string by
02599 /// one more than the StringRef would normally indicate.  Pass AddNull=false
02600 /// to disable this behavior.
02601 Constant *ConstantDataArray::getString(LLVMContext &Context,
02602                                        StringRef Str, bool AddNull) {
02603   if (!AddNull) {
02604     const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
02605     return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
02606                Str.size()));
02607   }
02608 
02609   SmallVector<uint8_t, 64> ElementVals;
02610   ElementVals.append(Str.begin(), Str.end());
02611   ElementVals.push_back(0);
02612   return get(Context, ElementVals);
02613 }
02614 
02615 /// get() constructors - Return a constant with vector type with an element
02616 /// count and element type matching the ArrayRef passed in.  Note that this
02617 /// can return a ConstantAggregateZero object.
02618 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
02619   Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
02620   const char *Data = reinterpret_cast<const char *>(Elts.data());
02621   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
02622 }
02623 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
02624   Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
02625   const char *Data = reinterpret_cast<const char *>(Elts.data());
02626   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
02627 }
02628 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
02629   Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
02630   const char *Data = reinterpret_cast<const char *>(Elts.data());
02631   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
02632 }
02633 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
02634   Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
02635   const char *Data = reinterpret_cast<const char *>(Elts.data());
02636   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
02637 }
02638 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
02639   Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
02640   const char *Data = reinterpret_cast<const char *>(Elts.data());
02641   return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
02642 }
02643 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
02644   Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
02645   const char *Data = reinterpret_cast<const char *>(Elts.data());
02646   return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
02647 }
02648 
02649 /// getFP() constructors - Return a constant with vector type with an element
02650 /// count and element type of float with the precision matching the number of
02651 /// bits in the ArrayRef passed in.  (i.e. half for 16bits, float for 32bits,
02652 /// double for 64bits) Note that this can return a ConstantAggregateZero
02653 /// object.
02654 Constant *ConstantDataVector::getFP(LLVMContext &Context,
02655                                     ArrayRef<uint16_t> Elts) {
02656   Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
02657   const char *Data = reinterpret_cast<const char *>(Elts.data());
02658   return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
02659 }
02660 Constant *ConstantDataVector::getFP(LLVMContext &Context,
02661                                     ArrayRef<uint32_t> Elts) {
02662   Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
02663   const char *Data = reinterpret_cast<const char *>(Elts.data());
02664   return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
02665 }
02666 Constant *ConstantDataVector::getFP(LLVMContext &Context,
02667                                     ArrayRef<uint64_t> Elts) {
02668   Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
02669   const char *Data = reinterpret_cast<const char *>(Elts.data());
02670   return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
02671 }
02672 
02673 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
02674   assert(isElementTypeCompatible(V->getType()) &&
02675          "Element type not compatible with ConstantData");
02676   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
02677     if (CI->getType()->isIntegerTy(8)) {
02678       SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
02679       return get(V->getContext(), Elts);
02680     }
02681     if (CI->getType()->isIntegerTy(16)) {
02682       SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
02683       return get(V->getContext(), Elts);
02684     }
02685     if (CI->getType()->isIntegerTy(32)) {
02686       SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
02687       return get(V->getContext(), Elts);
02688     }
02689     assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
02690     SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
02691     return get(V->getContext(), Elts);
02692   }
02693 
02694   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
02695     if (CFP->getType()->isFloatTy()) {
02696       SmallVector<uint32_t, 16> Elts(
02697           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
02698       return getFP(V->getContext(), Elts);
02699     }
02700     if (CFP->getType()->isDoubleTy()) {
02701       SmallVector<uint64_t, 16> Elts(
02702           NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
02703       return getFP(V->getContext(), Elts);
02704     }
02705   }
02706   return ConstantVector::getSplat(NumElts, V);
02707 }
02708 
02709 
02710 /// getElementAsInteger - If this is a sequential container of integers (of
02711 /// any size), return the specified element in the low bits of a uint64_t.
02712 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
02713   assert(isa<IntegerType>(getElementType()) &&
02714          "Accessor can only be used when element is an integer");
02715   const char *EltPtr = getElementPointer(Elt);
02716 
02717   // The data is stored in host byte order, make sure to cast back to the right
02718   // type to load with the right endianness.
02719   switch (getElementType()->getIntegerBitWidth()) {
02720   default: llvm_unreachable("Invalid bitwidth for CDS");
02721   case 8:
02722     return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
02723   case 16:
02724     return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
02725   case 32:
02726     return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
02727   case 64:
02728     return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
02729   }
02730 }
02731 
02732 /// getElementAsAPFloat - If this is a sequential container of floating point
02733 /// type, return the specified element as an APFloat.
02734 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
02735   const char *EltPtr = getElementPointer(Elt);
02736 
02737   switch (getElementType()->getTypeID()) {
02738   default:
02739     llvm_unreachable("Accessor can only be used when element is float/double!");
02740   case Type::FloatTyID: {
02741     auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
02742     return APFloat(APFloat::IEEEsingle, APInt(32, EltVal));
02743   }
02744   case Type::DoubleTyID: {
02745     auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
02746     return APFloat(APFloat::IEEEdouble, APInt(64, EltVal));
02747   }
02748   }
02749 }
02750 
02751 /// getElementAsFloat - If this is an sequential container of floats, return
02752 /// the specified element as a float.
02753 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
02754   assert(getElementType()->isFloatTy() &&
02755          "Accessor can only be used when element is a 'float'");
02756   const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
02757   return *const_cast<float *>(EltPtr);
02758 }
02759 
02760 /// getElementAsDouble - If this is an sequential container of doubles, return
02761 /// the specified element as a float.
02762 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
02763   assert(getElementType()->isDoubleTy() &&
02764          "Accessor can only be used when element is a 'float'");
02765   const double *EltPtr =
02766       reinterpret_cast<const double *>(getElementPointer(Elt));
02767   return *const_cast<double *>(EltPtr);
02768 }
02769 
02770 /// getElementAsConstant - Return a Constant for a specified index's element.
02771 /// Note that this has to compute a new constant to return, so it isn't as
02772 /// efficient as getElementAsInteger/Float/Double.
02773 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
02774   if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
02775     return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
02776 
02777   return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
02778 }
02779 
02780 /// isString - This method returns true if this is an array of i8.
02781 bool ConstantDataSequential::isString() const {
02782   return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
02783 }
02784 
02785 /// isCString - This method returns true if the array "isString", ends with a
02786 /// nul byte, and does not contains any other nul bytes.
02787 bool ConstantDataSequential::isCString() const {
02788   if (!isString())
02789     return false;
02790 
02791   StringRef Str = getAsString();
02792 
02793   // The last value must be nul.
02794   if (Str.back() != 0) return false;
02795 
02796   // Other elements must be non-nul.
02797   return Str.drop_back().find(0) == StringRef::npos;
02798 }
02799 
02800 /// getSplatValue - If this is a splat constant, meaning that all of the
02801 /// elements have the same value, return that value. Otherwise return nullptr.
02802 Constant *ConstantDataVector::getSplatValue() const {
02803   const char *Base = getRawDataValues().data();
02804 
02805   // Compare elements 1+ to the 0'th element.
02806   unsigned EltSize = getElementByteSize();
02807   for (unsigned i = 1, e = getNumElements(); i != e; ++i)
02808     if (memcmp(Base, Base+i*EltSize, EltSize))
02809       return nullptr;
02810 
02811   // If they're all the same, return the 0th one as a representative.
02812   return getElementAsConstant(0);
02813 }
02814 
02815 //===----------------------------------------------------------------------===//
02816 //                replaceUsesOfWithOnConstant implementations
02817 
02818 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
02819 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
02820 /// etc.
02821 ///
02822 /// Note that we intentionally replace all uses of From with To here.  Consider
02823 /// a large array that uses 'From' 1000 times.  By handling this case all here,
02824 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
02825 /// single invocation handles all 1000 uses.  Handling them one at a time would
02826 /// work, but would be really slow because it would have to unique each updated
02827 /// array instance.
02828 ///
02829 void Constant::replaceUsesOfWithOnConstantImpl(Constant *Replacement) {
02830   // I do need to replace this with an existing value.
02831   assert(Replacement != this && "I didn't contain From!");
02832 
02833   // Everyone using this now uses the replacement.
02834   replaceAllUsesWith(Replacement);
02835 
02836   // Delete the old constant!
02837   destroyConstant();
02838 }
02839 
02840 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
02841                                                 Use *U) {
02842   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
02843   Constant *ToC = cast<Constant>(To);
02844 
02845   SmallVector<Constant*, 8> Values;
02846   Values.reserve(getNumOperands());  // Build replacement array.
02847 
02848   // Fill values with the modified operands of the constant array.  Also,
02849   // compute whether this turns into an all-zeros array.
02850   unsigned NumUpdated = 0;
02851 
02852   // Keep track of whether all the values in the array are "ToC".
02853   bool AllSame = true;
02854   for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
02855     Constant *Val = cast<Constant>(O->get());
02856     if (Val == From) {
02857       Val = ToC;
02858       ++NumUpdated;
02859     }
02860     Values.push_back(Val);
02861     AllSame &= Val == ToC;
02862   }
02863 
02864   if (AllSame && ToC->isNullValue()) {
02865     replaceUsesOfWithOnConstantImpl(ConstantAggregateZero::get(getType()));
02866     return;
02867   }
02868   if (AllSame && isa<UndefValue>(ToC)) {
02869     replaceUsesOfWithOnConstantImpl(UndefValue::get(getType()));
02870     return;
02871   }
02872 
02873   // Check for any other type of constant-folding.
02874   if (Constant *C = getImpl(getType(), Values)) {
02875     replaceUsesOfWithOnConstantImpl(C);
02876     return;
02877   }
02878 
02879   // Update to the new value.
02880   if (Constant *C = getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
02881           Values, this, From, ToC, NumUpdated, U - OperandList))
02882     replaceUsesOfWithOnConstantImpl(C);
02883 }
02884 
02885 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
02886                                                  Use *U) {
02887   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
02888   Constant *ToC = cast<Constant>(To);
02889 
02890   unsigned OperandToUpdate = U-OperandList;
02891   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
02892 
02893   SmallVector<Constant*, 8> Values;
02894   Values.reserve(getNumOperands());  // Build replacement struct.
02895 
02896   // Fill values with the modified operands of the constant struct.  Also,
02897   // compute whether this turns into an all-zeros struct.
02898   bool isAllZeros = false;
02899   bool isAllUndef = false;
02900   if (ToC->isNullValue()) {
02901     isAllZeros = true;
02902     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
02903       Constant *Val = cast<Constant>(O->get());
02904       Values.push_back(Val);
02905       if (isAllZeros) isAllZeros = Val->isNullValue();
02906     }
02907   } else if (isa<UndefValue>(ToC)) {
02908     isAllUndef = true;
02909     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
02910       Constant *Val = cast<Constant>(O->get());
02911       Values.push_back(Val);
02912       if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
02913     }
02914   } else {
02915     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
02916       Values.push_back(cast<Constant>(O->get()));
02917   }
02918   Values[OperandToUpdate] = ToC;
02919 
02920   if (isAllZeros) {
02921     replaceUsesOfWithOnConstantImpl(ConstantAggregateZero::get(getType()));
02922     return;
02923   }
02924   if (isAllUndef) {
02925     replaceUsesOfWithOnConstantImpl(UndefValue::get(getType()));
02926     return;
02927   }
02928 
02929   // Update to the new value.
02930   if (Constant *C = getContext().pImpl->StructConstants.replaceOperandsInPlace(
02931           Values, this, From, ToC))
02932     replaceUsesOfWithOnConstantImpl(C);
02933 }
02934 
02935 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
02936                                                  Use *U) {
02937   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
02938   Constant *ToC = cast<Constant>(To);
02939 
02940   SmallVector<Constant*, 8> Values;
02941   Values.reserve(getNumOperands());  // Build replacement array...
02942   unsigned NumUpdated = 0;
02943   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
02944     Constant *Val = getOperand(i);
02945     if (Val == From) {
02946       ++NumUpdated;
02947       Val = ToC;
02948     }
02949     Values.push_back(Val);
02950   }
02951 
02952   if (Constant *C = getImpl(Values)) {
02953     replaceUsesOfWithOnConstantImpl(C);
02954     return;
02955   }
02956 
02957   // Update to the new value.
02958   if (Constant *C = getContext().pImpl->VectorConstants.replaceOperandsInPlace(
02959           Values, this, From, ToC, NumUpdated, U - OperandList))
02960     replaceUsesOfWithOnConstantImpl(C);
02961 }
02962 
02963 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
02964                                                Use *U) {
02965   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
02966   Constant *To = cast<Constant>(ToV);
02967 
02968   SmallVector<Constant*, 8> NewOps;
02969   unsigned NumUpdated = 0;
02970   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
02971     Constant *Op = getOperand(i);
02972     if (Op == From) {
02973       ++NumUpdated;
02974       Op = To;
02975     }
02976     NewOps.push_back(Op);
02977   }
02978   assert(NumUpdated && "I didn't contain From!");
02979 
02980   if (Constant *C = getWithOperands(NewOps, getType(), true)) {
02981     replaceUsesOfWithOnConstantImpl(C);
02982     return;
02983   }
02984 
02985   // Update to the new value.
02986   if (Constant *C = getContext().pImpl->ExprConstants.replaceOperandsInPlace(
02987           NewOps, this, From, To, NumUpdated, U - OperandList))
02988     replaceUsesOfWithOnConstantImpl(C);
02989 }
02990 
02991 Instruction *ConstantExpr::getAsInstruction() {
02992   SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
02993   ArrayRef<Value*> Ops(ValueOperands);
02994 
02995   switch (getOpcode()) {
02996   case Instruction::Trunc:
02997   case Instruction::ZExt:
02998   case Instruction::SExt:
02999   case Instruction::FPTrunc:
03000   case Instruction::FPExt:
03001   case Instruction::UIToFP:
03002   case Instruction::SIToFP:
03003   case Instruction::FPToUI:
03004   case Instruction::FPToSI:
03005   case Instruction::PtrToInt:
03006   case Instruction::IntToPtr:
03007   case Instruction::BitCast:
03008   case Instruction::AddrSpaceCast:
03009     return CastInst::Create((Instruction::CastOps)getOpcode(),
03010                             Ops[0], getType());
03011   case Instruction::Select:
03012     return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
03013   case Instruction::InsertElement:
03014     return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
03015   case Instruction::ExtractElement:
03016     return ExtractElementInst::Create(Ops[0], Ops[1]);
03017   case Instruction::InsertValue:
03018     return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
03019   case Instruction::ExtractValue:
03020     return ExtractValueInst::Create(Ops[0], getIndices());
03021   case Instruction::ShuffleVector:
03022     return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
03023 
03024   case Instruction::GetElementPtr: {
03025     const auto *GO = cast<GEPOperator>(this);
03026     if (GO->isInBounds())
03027       return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
03028                                                Ops[0], Ops.slice(1));
03029     return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
03030                                      Ops.slice(1));
03031   }
03032   case Instruction::ICmp:
03033   case Instruction::FCmp:
03034     return CmpInst::Create((Instruction::OtherOps)getOpcode(),
03035                            getPredicate(), Ops[0], Ops[1]);
03036 
03037   default:
03038     assert(getNumOperands() == 2 && "Must be binary operator?");
03039     BinaryOperator *BO =
03040       BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
03041                              Ops[0], Ops[1]);
03042     if (isa<OverflowingBinaryOperator>(BO)) {
03043       BO->setHasNoUnsignedWrap(SubclassOptionalData &
03044                                OverflowingBinaryOperator::NoUnsignedWrap);
03045       BO->setHasNoSignedWrap(SubclassOptionalData &
03046                              OverflowingBinaryOperator::NoSignedWrap);
03047     }
03048     if (isa<PossiblyExactOperator>(BO))
03049       BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
03050     return BO;
03051   }
03052 }