LLVM API Documentation

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