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