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