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