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