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 "LLVMContextImpl.h"
00015 #include "llvm/Constants.h"
00016 #include "ConstantFold.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/GlobalValue.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Module.h"
00021 #include "llvm/Operator.h"
00022 #include "llvm/ADT/FoldingSet.h"
00023 #include "llvm/ADT/StringExtras.h"
00024 #include "llvm/ADT/StringMap.h"
00025 #include "llvm/Support/Compiler.h"
00026 #include "llvm/Support/Debug.h"
00027 #include "llvm/Support/ErrorHandling.h"
00028 #include "llvm/Support/ManagedStatic.h"
00029 #include "llvm/Support/MathExtras.h"
00030 #include "llvm/System/Mutex.h"
00031 #include "llvm/System/RWMutex.h"
00032 #include "llvm/System/Threading.h"
00033 #include "llvm/ADT/DenseMap.h"
00034 #include "llvm/ADT/SmallVector.h"
00035 #include <algorithm>
00036 #include <map>
00037 using namespace llvm;
00038 
00039 //===----------------------------------------------------------------------===//
00040 //                              Constant Class
00041 //===----------------------------------------------------------------------===//
00042 
00043 // Constructor to create a '0' constant of arbitrary type...
00044 static const uint64_t zero[2] = {0, 0};
00045 Constant* Constant::getNullValue(const Type* Ty) {
00046   switch (Ty->getTypeID()) {
00047   case Type::IntegerTyID:
00048     return ConstantInt::get(Ty, 0);
00049   case Type::FloatTyID:
00050     return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
00051   case Type::DoubleTyID:
00052     return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
00053   case Type::X86_FP80TyID:
00054     return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
00055   case Type::FP128TyID:
00056     return ConstantFP::get(Ty->getContext(),
00057                            APFloat(APInt(128, 2, zero), true));
00058   case Type::PPC_FP128TyID:
00059     return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
00060   case Type::PointerTyID:
00061     return ConstantPointerNull::get(cast<PointerType>(Ty));
00062   case Type::StructTyID:
00063   case Type::ArrayTyID:
00064   case Type::VectorTyID:
00065     return ConstantAggregateZero::get(Ty);
00066   default:
00067     // Function, Label, or Opaque type?
00068     assert(!"Cannot create a null constant of that type!");
00069     return 0;
00070   }
00071 }
00072 
00073 Constant* Constant::getIntegerValue(const Type* Ty, const APInt &V) {
00074   const Type *ScalarTy = Ty->getScalarType();
00075 
00076   // Create the base integer constant.
00077   Constant *C = ConstantInt::get(Ty->getContext(), V);
00078 
00079   // Convert an integer to a pointer, if necessary.
00080   if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
00081     C = ConstantExpr::getIntToPtr(C, PTy);
00082 
00083   // Broadcast a scalar to a vector, if necessary.
00084   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
00085     C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
00086 
00087   return C;
00088 }
00089 
00090 Constant* Constant::getAllOnesValue(const Type* Ty) {
00091   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
00092     return ConstantInt::get(Ty->getContext(),
00093                             APInt::getAllOnesValue(ITy->getBitWidth()));
00094   
00095   std::vector<Constant*> Elts;
00096   const VectorType* VTy = cast<VectorType>(Ty);
00097   Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
00098   assert(Elts[0] && "Not a vector integer type!");
00099   return cast<ConstantVector>(ConstantVector::get(Elts));
00100 }
00101 
00102 void Constant::destroyConstantImpl() {
00103   // When a Constant is destroyed, there may be lingering
00104   // references to the constant by other constants in the constant pool.  These
00105   // constants are implicitly dependent on the module that is being deleted,
00106   // but they don't know that.  Because we only find out when the CPV is
00107   // deleted, we must now notify all of our users (that should only be
00108   // Constants) that they are, in fact, invalid now and should be deleted.
00109   //
00110   while (!use_empty()) {
00111     Value *V = use_back();
00112 #ifndef NDEBUG      // Only in -g mode...
00113     if (!isa<Constant>(V))
00114       DOUT << "While deleting: " << *this
00115            << "\n\nUse still stuck around after Def is destroyed: "
00116            << *V << "\n\n";
00117 #endif
00118     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
00119     Constant *CV = cast<Constant>(V);
00120     CV->destroyConstant();
00121 
00122     // The constant should remove itself from our use list...
00123     assert((use_empty() || use_back() != V) && "Constant not removed!");
00124   }
00125 
00126   // Value has no outstanding references it is safe to delete it now...
00127   delete this;
00128 }
00129 
00130 /// canTrap - Return true if evaluation of this constant could trap.  This is
00131 /// true for things like constant expressions that could divide by zero.
00132 bool Constant::canTrap() const {
00133   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
00134   // The only thing that could possibly trap are constant exprs.
00135   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
00136   if (!CE) return false;
00137   
00138   // ConstantExpr traps if any operands can trap. 
00139   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00140     if (getOperand(i)->canTrap()) 
00141       return true;
00142 
00143   // Otherwise, only specific operations can trap.
00144   switch (CE->getOpcode()) {
00145   default:
00146     return false;
00147   case Instruction::UDiv:
00148   case Instruction::SDiv:
00149   case Instruction::FDiv:
00150   case Instruction::URem:
00151   case Instruction::SRem:
00152   case Instruction::FRem:
00153     // Div and rem can trap if the RHS is not known to be non-zero.
00154     if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
00155       return true;
00156     return false;
00157   }
00158 }
00159 
00160 
00161 /// getRelocationInfo - This method classifies the entry according to
00162 /// whether or not it may generate a relocation entry.  This must be
00163 /// conservative, so if it might codegen to a relocatable entry, it should say
00164 /// so.  The return values are:
00165 /// 
00166 ///  NoRelocation: This constant pool entry is guaranteed to never have a
00167 ///     relocation applied to it (because it holds a simple constant like
00168 ///     '4').
00169 ///  LocalRelocation: This entry has relocations, but the entries are
00170 ///     guaranteed to be resolvable by the static linker, so the dynamic
00171 ///     linker will never see them.
00172 ///  GlobalRelocations: This entry may have arbitrary relocations.
00173 ///
00174 /// FIXME: This really should not be in VMCore.
00175 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
00176   if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
00177     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
00178       return LocalRelocation;  // Local to this file/library.
00179     return GlobalRelocations;    // Global reference.
00180   }
00181   
00182   PossibleRelocationsTy Result = NoRelocation;
00183   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00184     Result = std::max(Result, getOperand(i)->getRelocationInfo());
00185   
00186   return Result;
00187 }
00188 
00189 
00190 /// getVectorElements - This method, which is only valid on constant of vector
00191 /// type, returns the elements of the vector in the specified smallvector.
00192 /// This handles breaking down a vector undef into undef elements, etc.  For
00193 /// constant exprs and other cases we can't handle, we return an empty vector.
00194 void Constant::getVectorElements(LLVMContext &Context,
00195                                  SmallVectorImpl<Constant*> &Elts) const {
00196   assert(isa<VectorType>(getType()) && "Not a vector constant!");
00197   
00198   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
00199     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
00200       Elts.push_back(CV->getOperand(i));
00201     return;
00202   }
00203   
00204   const VectorType *VT = cast<VectorType>(getType());
00205   if (isa<ConstantAggregateZero>(this)) {
00206     Elts.assign(VT->getNumElements(), 
00207                 Constant::getNullValue(VT->getElementType()));
00208     return;
00209   }
00210   
00211   if (isa<UndefValue>(this)) {
00212     Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
00213     return;
00214   }
00215   
00216   // Unknown type, must be constant expr etc.
00217 }
00218 
00219 
00220 
00221 //===----------------------------------------------------------------------===//
00222 //                                ConstantInt
00223 //===----------------------------------------------------------------------===//
00224 
00225 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
00226   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
00227   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
00228 }
00229 
00230 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
00231   LLVMContextImpl *pImpl = Context.pImpl;
00232   sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
00233   if (pImpl->TheTrueVal)
00234     return pImpl->TheTrueVal;
00235   else
00236     return (pImpl->TheTrueVal =
00237               ConstantInt::get(IntegerType::get(Context, 1), 1));
00238 }
00239 
00240 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
00241   LLVMContextImpl *pImpl = Context.pImpl;
00242   sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
00243   if (pImpl->TheFalseVal)
00244     return pImpl->TheFalseVal;
00245   else
00246     return (pImpl->TheFalseVal =
00247               ConstantInt::get(IntegerType::get(Context, 1), 0));
00248 }
00249 
00250 
00251 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
00252 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
00253 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
00254 // compare APInt's of different widths, which would violate an APInt class
00255 // invariant which generates an assertion.
00256 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
00257   // Get the corresponding integer type for the bit width of the value.
00258   const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
00259   // get an existing value or the insertion position
00260   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
00261   
00262   Context.pImpl->ConstantsLock.reader_acquire();
00263   ConstantInt *&Slot = Context.pImpl->IntConstants[Key]; 
00264   Context.pImpl->ConstantsLock.reader_release();
00265     
00266   if (!Slot) {
00267     sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
00268     ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key]; 
00269     if (!Slot) {
00270       NewSlot = new ConstantInt(ITy, V);
00271     }
00272     
00273     return NewSlot;
00274   } else {
00275     return Slot;
00276   }
00277 }
00278 
00279 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
00280   Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
00281                                V, isSigned);
00282 
00283   // For vectors, broadcast the value.
00284   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
00285     return ConstantVector::get(
00286       std::vector<Constant *>(VTy->getNumElements(), C));
00287 
00288   return C;
00289 }
00290 
00291 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V, 
00292                               bool isSigned) {
00293   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
00294 }
00295 
00296 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
00297   return get(Ty, V, true);
00298 }
00299 
00300 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
00301   return get(Ty, V, true);
00302 }
00303 
00304 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
00305   ConstantInt *C = get(Ty->getContext(), V);
00306   assert(C->getType() == Ty->getScalarType() &&
00307          "ConstantInt type doesn't match the type implied by its value!");
00308 
00309   // For vectors, broadcast the value.
00310   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
00311     return ConstantVector::get(
00312       std::vector<Constant *>(VTy->getNumElements(), C));
00313 
00314   return C;
00315 }
00316 
00317 ConstantInt* ConstantInt::get(const IntegerType* Ty, const StringRef& Str,
00318                               uint8_t radix) {
00319   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
00320 }
00321 
00322 //===----------------------------------------------------------------------===//
00323 //                                ConstantFP
00324 //===----------------------------------------------------------------------===//
00325 
00326 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
00327   if (Ty == Type::getFloatTy(Ty->getContext()))
00328     return &APFloat::IEEEsingle;
00329   if (Ty == Type::getDoubleTy(Ty->getContext()))
00330     return &APFloat::IEEEdouble;
00331   if (Ty == Type::getX86_FP80Ty(Ty->getContext()))
00332     return &APFloat::x87DoubleExtended;
00333   else if (Ty == Type::getFP128Ty(Ty->getContext()))
00334     return &APFloat::IEEEquad;
00335   
00336   assert(Ty == Type::getPPC_FP128Ty(Ty->getContext()) && "Unknown FP format");
00337   return &APFloat::PPCDoubleDouble;
00338 }
00339 
00340 /// get() - This returns a constant fp for the specified value in the
00341 /// specified type.  This should only be used for simple constant values like
00342 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
00343 Constant* ConstantFP::get(const Type* Ty, double V) {
00344   LLVMContext &Context = Ty->getContext();
00345   
00346   APFloat FV(V);
00347   bool ignored;
00348   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
00349              APFloat::rmNearestTiesToEven, &ignored);
00350   Constant *C = get(Context, FV);
00351 
00352   // For vectors, broadcast the value.
00353   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
00354     return ConstantVector::get(
00355       std::vector<Constant *>(VTy->getNumElements(), C));
00356 
00357   return C;
00358 }
00359 
00360 
00361 Constant* ConstantFP::get(const Type* Ty, const StringRef& Str) {
00362   LLVMContext &Context = Ty->getContext();
00363 
00364   APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
00365   Constant *C = get(Context, FV);
00366 
00367   // For vectors, broadcast the value.
00368   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
00369     return ConstantVector::get(
00370       std::vector<Constant *>(VTy->getNumElements(), C));
00371 
00372   return C; 
00373 }
00374 
00375 
00376 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
00377   LLVMContext &Context = Ty->getContext();
00378   APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
00379   apf.changeSign();
00380   return get(Context, apf);
00381 }
00382 
00383 
00384 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
00385   if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
00386     if (PTy->getElementType()->isFloatingPoint()) {
00387       std::vector<Constant*> zeros(PTy->getNumElements(),
00388                            getNegativeZero(PTy->getElementType()));
00389       return ConstantVector::get(PTy, zeros);
00390     }
00391 
00392   if (Ty->isFloatingPoint()) 
00393     return getNegativeZero(Ty);
00394 
00395   return Constant::getNullValue(Ty);
00396 }
00397 
00398 
00399 // ConstantFP accessors.
00400 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
00401   DenseMapAPFloatKeyInfo::KeyTy Key(V);
00402   
00403   LLVMContextImpl* pImpl = Context.pImpl;
00404   
00405   pImpl->ConstantsLock.reader_acquire();
00406   ConstantFP *&Slot = pImpl->FPConstants[Key];
00407   pImpl->ConstantsLock.reader_release();
00408     
00409   if (!Slot) {
00410     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
00411     ConstantFP *&NewSlot = pImpl->FPConstants[Key];
00412     if (!NewSlot) {
00413       const Type *Ty;
00414       if (&V.getSemantics() == &APFloat::IEEEsingle)
00415         Ty = Type::getFloatTy(Context);
00416       else if (&V.getSemantics() == &APFloat::IEEEdouble)
00417         Ty = Type::getDoubleTy(Context);
00418       else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
00419         Ty = Type::getX86_FP80Ty(Context);
00420       else if (&V.getSemantics() == &APFloat::IEEEquad)
00421         Ty = Type::getFP128Ty(Context);
00422       else {
00423         assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
00424                "Unknown FP format");
00425         Ty = Type::getPPC_FP128Ty(Context);
00426       }
00427       NewSlot = new ConstantFP(Ty, V);
00428     }
00429     
00430     return NewSlot;
00431   }
00432   
00433   return Slot;
00434 }
00435 
00436 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
00437   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
00438   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
00439          "FP type Mismatch");
00440 }
00441 
00442 bool ConstantFP::isNullValue() const {
00443   return Val.isZero() && !Val.isNegative();
00444 }
00445 
00446 bool ConstantFP::isExactlyValue(const APFloat& V) const {
00447   return Val.bitwiseIsEqual(V);
00448 }
00449 
00450 //===----------------------------------------------------------------------===//
00451 //                            ConstantXXX Classes
00452 //===----------------------------------------------------------------------===//
00453 
00454 
00455 ConstantArray::ConstantArray(const ArrayType *T,
00456                              const std::vector<Constant*> &V)
00457   : Constant(T, ConstantArrayVal,
00458              OperandTraits<ConstantArray>::op_end(this) - V.size(),
00459              V.size()) {
00460   assert(V.size() == T->getNumElements() &&
00461          "Invalid initializer vector for constant array");
00462   Use *OL = OperandList;
00463   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
00464        I != E; ++I, ++OL) {
00465     Constant *C = *I;
00466     assert((C->getType() == T->getElementType() ||
00467             (T->isAbstract() &&
00468              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
00469            "Initializer for array element doesn't match array element type!");
00470     *OL = C;
00471   }
00472 }
00473 
00474 Constant *ConstantArray::get(const ArrayType *Ty, 
00475                              const std::vector<Constant*> &V) {
00476   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
00477   // If this is an all-zero array, return a ConstantAggregateZero object
00478   if (!V.empty()) {
00479     Constant *C = V[0];
00480     if (!C->isNullValue()) {
00481       // Implicitly locked.
00482       return pImpl->ArrayConstants.getOrCreate(Ty, V);
00483     }
00484     for (unsigned i = 1, e = V.size(); i != e; ++i)
00485       if (V[i] != C) {
00486         // Implicitly locked.
00487         return pImpl->ArrayConstants.getOrCreate(Ty, V);
00488       }
00489   }
00490   
00491   return ConstantAggregateZero::get(Ty);
00492 }
00493 
00494 
00495 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
00496                              unsigned NumVals) {
00497   // FIXME: make this the primary ctor method.
00498   return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
00499 }
00500 
00501 /// ConstantArray::get(const string&) - Return an array that is initialized to
00502 /// contain the specified string.  If length is zero then a null terminator is 
00503 /// added to the specified string so that it may be used in a natural way. 
00504 /// Otherwise, the length parameter specifies how much of the string to use 
00505 /// and it won't be null terminated.
00506 ///
00507 Constant* ConstantArray::get(LLVMContext &Context, const StringRef &Str,
00508                              bool AddNull) {
00509   std::vector<Constant*> ElementVals;
00510   for (unsigned i = 0; i < Str.size(); ++i)
00511     ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
00512 
00513   // Add a null terminator to the string...
00514   if (AddNull) {
00515     ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
00516   }
00517 
00518   ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
00519   return get(ATy, ElementVals);
00520 }
00521 
00522 
00523 
00524 ConstantStruct::ConstantStruct(const StructType *T,
00525                                const std::vector<Constant*> &V)
00526   : Constant(T, ConstantStructVal,
00527              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
00528              V.size()) {
00529   assert(V.size() == T->getNumElements() &&
00530          "Invalid initializer vector for constant structure");
00531   Use *OL = OperandList;
00532   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
00533        I != E; ++I, ++OL) {
00534     Constant *C = *I;
00535     assert((C->getType() == T->getElementType(I-V.begin()) ||
00536             ((T->getElementType(I-V.begin())->isAbstract() ||
00537               C->getType()->isAbstract()) &&
00538              T->getElementType(I-V.begin())->getTypeID() == 
00539                    C->getType()->getTypeID())) &&
00540            "Initializer for struct element doesn't match struct element type!");
00541     *OL = C;
00542   }
00543 }
00544 
00545 // ConstantStruct accessors.
00546 Constant* ConstantStruct::get(const StructType* T,
00547                               const std::vector<Constant*>& V) {
00548   LLVMContextImpl* pImpl = T->getContext().pImpl;
00549   
00550   // Create a ConstantAggregateZero value if all elements are zeros...
00551   for (unsigned i = 0, e = V.size(); i != e; ++i)
00552     if (!V[i]->isNullValue())
00553       // Implicitly locked.
00554       return pImpl->StructConstants.getOrCreate(T, V);
00555 
00556   return ConstantAggregateZero::get(T);
00557 }
00558 
00559 Constant* ConstantStruct::get(LLVMContext &Context,
00560                               const std::vector<Constant*>& V, bool packed) {
00561   std::vector<const Type*> StructEls;
00562   StructEls.reserve(V.size());
00563   for (unsigned i = 0, e = V.size(); i != e; ++i)
00564     StructEls.push_back(V[i]->getType());
00565   return get(StructType::get(Context, StructEls, packed), V);
00566 }
00567 
00568 Constant* ConstantStruct::get(LLVMContext &Context,
00569                               Constant* const *Vals, unsigned NumVals,
00570                               bool Packed) {
00571   // FIXME: make this the primary ctor method.
00572   return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
00573 }
00574 
00575 ConstantVector::ConstantVector(const VectorType *T,
00576                                const std::vector<Constant*> &V)
00577   : Constant(T, ConstantVectorVal,
00578              OperandTraits<ConstantVector>::op_end(this) - V.size(),
00579              V.size()) {
00580   Use *OL = OperandList;
00581     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
00582          I != E; ++I, ++OL) {
00583       Constant *C = *I;
00584       assert((C->getType() == T->getElementType() ||
00585             (T->isAbstract() &&
00586              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
00587            "Initializer for vector element doesn't match vector element type!");
00588     *OL = C;
00589   }
00590 }
00591 
00592 // ConstantVector accessors.
00593 Constant* ConstantVector::get(const VectorType* T,
00594                               const std::vector<Constant*>& V) {
00595    assert(!V.empty() && "Vectors can't be empty");
00596    LLVMContext &Context = T->getContext();
00597    LLVMContextImpl *pImpl = Context.pImpl;
00598    
00599   // If this is an all-undef or alll-zero vector, return a
00600   // ConstantAggregateZero or UndefValue.
00601   Constant *C = V[0];
00602   bool isZero = C->isNullValue();
00603   bool isUndef = isa<UndefValue>(C);
00604 
00605   if (isZero || isUndef) {
00606     for (unsigned i = 1, e = V.size(); i != e; ++i)
00607       if (V[i] != C) {
00608         isZero = isUndef = false;
00609         break;
00610       }
00611   }
00612   
00613   if (isZero)
00614     return ConstantAggregateZero::get(T);
00615   if (isUndef)
00616     return UndefValue::get(T);
00617     
00618   // Implicitly locked.
00619   return pImpl->VectorConstants.getOrCreate(T, V);
00620 }
00621 
00622 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
00623   assert(!V.empty() && "Cannot infer type if V is empty");
00624   return get(VectorType::get(V.front()->getType(),V.size()), V);
00625 }
00626 
00627 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
00628   // FIXME: make this the primary ctor method.
00629   return get(std::vector<Constant*>(Vals, Vals+NumVals));
00630 }
00631 
00632 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
00633   Constant *C = getAdd(C1, C2);
00634   // Set nsw attribute, assuming constant folding didn't eliminate the
00635   // Add.
00636   if (AddOperator *Add = dyn_cast<AddOperator>(C))
00637     Add->setHasNoSignedWrap(true);
00638   return C;
00639 }
00640 
00641 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
00642   Constant *C = getSDiv(C1, C2);
00643   // Set exact attribute, assuming constant folding didn't eliminate the
00644   // SDiv.
00645   if (SDivOperator *SDiv = dyn_cast<SDivOperator>(C))
00646     SDiv->setIsExact(true);
00647   return C;
00648 }
00649 
00650 // Utility function for determining if a ConstantExpr is a CastOp or not. This
00651 // can't be inline because we don't want to #include Instruction.h into
00652 // Constant.h
00653 bool ConstantExpr::isCast() const {
00654   return Instruction::isCast(getOpcode());
00655 }
00656 
00657 bool ConstantExpr::isCompare() const {
00658   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
00659 }
00660 
00661 bool ConstantExpr::hasIndices() const {
00662   return getOpcode() == Instruction::ExtractValue ||
00663          getOpcode() == Instruction::InsertValue;
00664 }
00665 
00666 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
00667   if (const ExtractValueConstantExpr *EVCE =
00668         dyn_cast<ExtractValueConstantExpr>(this))
00669     return EVCE->Indices;
00670 
00671   return cast<InsertValueConstantExpr>(this)->Indices;
00672 }
00673 
00674 unsigned ConstantExpr::getPredicate() const {
00675   assert(getOpcode() == Instruction::FCmp || 
00676          getOpcode() == Instruction::ICmp);
00677   return ((const CompareConstantExpr*)this)->predicate;
00678 }
00679 
00680 /// getWithOperandReplaced - Return a constant expression identical to this
00681 /// one, but with the specified operand set to the specified value.
00682 Constant *
00683 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
00684   assert(OpNo < getNumOperands() && "Operand num is out of range!");
00685   assert(Op->getType() == getOperand(OpNo)->getType() &&
00686          "Replacing operand with value of different type!");
00687   if (getOperand(OpNo) == Op)
00688     return const_cast<ConstantExpr*>(this);
00689   
00690   Constant *Op0, *Op1, *Op2;
00691   switch (getOpcode()) {
00692   case Instruction::Trunc:
00693   case Instruction::ZExt:
00694   case Instruction::SExt:
00695   case Instruction::FPTrunc:
00696   case Instruction::FPExt:
00697   case Instruction::UIToFP:
00698   case Instruction::SIToFP:
00699   case Instruction::FPToUI:
00700   case Instruction::FPToSI:
00701   case Instruction::PtrToInt:
00702   case Instruction::IntToPtr:
00703   case Instruction::BitCast:
00704     return ConstantExpr::getCast(getOpcode(), Op, getType());
00705   case Instruction::Select:
00706     Op0 = (OpNo == 0) ? Op : getOperand(0);
00707     Op1 = (OpNo == 1) ? Op : getOperand(1);
00708     Op2 = (OpNo == 2) ? Op : getOperand(2);
00709     return ConstantExpr::getSelect(Op0, Op1, Op2);
00710   case Instruction::InsertElement:
00711     Op0 = (OpNo == 0) ? Op : getOperand(0);
00712     Op1 = (OpNo == 1) ? Op : getOperand(1);
00713     Op2 = (OpNo == 2) ? Op : getOperand(2);
00714     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
00715   case Instruction::ExtractElement:
00716     Op0 = (OpNo == 0) ? Op : getOperand(0);
00717     Op1 = (OpNo == 1) ? Op : getOperand(1);
00718     return ConstantExpr::getExtractElement(Op0, Op1);
00719   case Instruction::ShuffleVector:
00720     Op0 = (OpNo == 0) ? Op : getOperand(0);
00721     Op1 = (OpNo == 1) ? Op : getOperand(1);
00722     Op2 = (OpNo == 2) ? Op : getOperand(2);
00723     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
00724   case Instruction::GetElementPtr: {
00725     SmallVector<Constant*, 8> Ops;
00726     Ops.resize(getNumOperands()-1);
00727     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
00728       Ops[i-1] = getOperand(i);
00729     if (OpNo == 0)
00730       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
00731     Ops[OpNo-1] = Op;
00732     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
00733   }
00734   default:
00735     assert(getNumOperands() == 2 && "Must be binary operator?");
00736     Op0 = (OpNo == 0) ? Op : getOperand(0);
00737     Op1 = (OpNo == 1) ? Op : getOperand(1);
00738     return ConstantExpr::get(getOpcode(), Op0, Op1);
00739   }
00740 }
00741 
00742 /// getWithOperands - This returns the current constant expression with the
00743 /// operands replaced with the specified values.  The specified operands must
00744 /// match count and type with the existing ones.
00745 Constant *ConstantExpr::
00746 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
00747   assert(NumOps == getNumOperands() && "Operand count mismatch!");
00748   bool AnyChange = false;
00749   for (unsigned i = 0; i != NumOps; ++i) {
00750     assert(Ops[i]->getType() == getOperand(i)->getType() &&
00751            "Operand type mismatch!");
00752     AnyChange |= Ops[i] != getOperand(i);
00753   }
00754   if (!AnyChange)  // No operands changed, return self.
00755     return const_cast<ConstantExpr*>(this);
00756 
00757   switch (getOpcode()) {
00758   case Instruction::Trunc:
00759   case Instruction::ZExt:
00760   case Instruction::SExt:
00761   case Instruction::FPTrunc:
00762   case Instruction::FPExt:
00763   case Instruction::UIToFP:
00764   case Instruction::SIToFP:
00765   case Instruction::FPToUI:
00766   case Instruction::FPToSI:
00767   case Instruction::PtrToInt:
00768   case Instruction::IntToPtr:
00769   case Instruction::BitCast:
00770     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
00771   case Instruction::Select:
00772     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
00773   case Instruction::InsertElement:
00774     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
00775   case Instruction::ExtractElement:
00776     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
00777   case Instruction::ShuffleVector:
00778     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
00779   case Instruction::GetElementPtr:
00780     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
00781   case Instruction::ICmp:
00782   case Instruction::FCmp:
00783     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
00784   default:
00785     assert(getNumOperands() == 2 && "Must be binary operator?");
00786     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
00787   }
00788 }
00789 
00790 
00791 //===----------------------------------------------------------------------===//
00792 //                      isValueValidForType implementations
00793 
00794 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
00795   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
00796   if (Ty == Type::getInt1Ty(Ty->getContext()))
00797     return Val == 0 || Val == 1;
00798   if (NumBits >= 64)
00799     return true; // always true, has to fit in largest type
00800   uint64_t Max = (1ll << NumBits) - 1;
00801   return Val <= Max;
00802 }
00803 
00804 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
00805   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
00806   if (Ty == Type::getInt1Ty(Ty->getContext()))
00807     return Val == 0 || Val == 1 || Val == -1;
00808   if (NumBits >= 64)
00809     return true; // always true, has to fit in largest type
00810   int64_t Min = -(1ll << (NumBits-1));
00811   int64_t Max = (1ll << (NumBits-1)) - 1;
00812   return (Val >= Min && Val <= Max);
00813 }
00814 
00815 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
00816   // convert modifies in place, so make a copy.
00817   APFloat Val2 = APFloat(Val);
00818   bool losesInfo;
00819   switch (Ty->getTypeID()) {
00820   default:
00821     return false;         // These can't be represented as floating point!
00822 
00823   // FIXME rounding mode needs to be more flexible
00824   case Type::FloatTyID: {
00825     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
00826       return true;
00827     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
00828     return !losesInfo;
00829   }
00830   case Type::DoubleTyID: {
00831     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
00832         &Val2.getSemantics() == &APFloat::IEEEdouble)
00833       return true;
00834     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
00835     return !losesInfo;
00836   }
00837   case Type::X86_FP80TyID:
00838     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
00839            &Val2.getSemantics() == &APFloat::IEEEdouble ||
00840            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
00841   case Type::FP128TyID:
00842     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
00843            &Val2.getSemantics() == &APFloat::IEEEdouble ||
00844            &Val2.getSemantics() == &APFloat::IEEEquad;
00845   case Type::PPC_FP128TyID:
00846     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
00847            &Val2.getSemantics() == &APFloat::IEEEdouble ||
00848            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
00849   }
00850 }
00851 
00852 //===----------------------------------------------------------------------===//
00853 //                      Factory Function Implementation
00854 
00855 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
00856 
00857 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
00858   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
00859          "Cannot create an aggregate zero of non-aggregate type!");
00860   
00861   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
00862   // Implicitly locked.
00863   return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
00864 }
00865 
00866 /// destroyConstant - Remove the constant from the constant table...
00867 ///
00868 void ConstantAggregateZero::destroyConstant() {
00869   // Implicitly locked.
00870   getType()->getContext().pImpl->AggZeroConstants.remove(this);
00871   destroyConstantImpl();
00872 }
00873 
00874 /// destroyConstant - Remove the constant from the constant table...
00875 ///
00876 void ConstantArray::destroyConstant() {
00877   // Implicitly locked.
00878   getType()->getContext().pImpl->ArrayConstants.remove(this);
00879   destroyConstantImpl();
00880 }
00881 
00882 /// isString - This method returns true if the array is an array of i8, and 
00883 /// if the elements of the array are all ConstantInt's.
00884 bool ConstantArray::isString() const {
00885   // Check the element type for i8...
00886   if (getType()->getElementType() != Type::getInt8Ty(getContext()))
00887     return false;
00888   // Check the elements to make sure they are all integers, not constant
00889   // expressions.
00890   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00891     if (!isa<ConstantInt>(getOperand(i)))
00892       return false;
00893   return true;
00894 }
00895 
00896 /// isCString - This method returns true if the array is a string (see
00897 /// isString) and it ends in a null byte \\0 and does not contains any other
00898 /// null bytes except its terminator.
00899 bool ConstantArray::isCString() const {
00900   // Check the element type for i8...
00901   if (getType()->getElementType() != Type::getInt8Ty(getContext()))
00902     return false;
00903 
00904   // Last element must be a null.
00905   if (!getOperand(getNumOperands()-1)->isNullValue())
00906     return false;
00907   // Other elements must be non-null integers.
00908   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
00909     if (!isa<ConstantInt>(getOperand(i)))
00910       return false;
00911     if (getOperand(i)->isNullValue())
00912       return false;
00913   }
00914   return true;
00915 }
00916 
00917 
00918 /// getAsString - If the sub-element type of this array is i8
00919 /// then this method converts the array to an std::string and returns it.
00920 /// Otherwise, it asserts out.
00921 ///
00922 std::string ConstantArray::getAsString() const {
00923   assert(isString() && "Not a string!");
00924   std::string Result;
00925   Result.reserve(getNumOperands());
00926   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
00927     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
00928   return Result;
00929 }
00930 
00931 
00932 //---- ConstantStruct::get() implementation...
00933 //
00934 
00935 namespace llvm {
00936 
00937 }
00938 
00939 // destroyConstant - Remove the constant from the constant table...
00940 //
00941 void ConstantStruct::destroyConstant() {
00942   // Implicitly locked.
00943   getType()->getContext().pImpl->StructConstants.remove(this);
00944   destroyConstantImpl();
00945 }
00946 
00947 // destroyConstant - Remove the constant from the constant table...
00948 //
00949 void ConstantVector::destroyConstant() {
00950   // Implicitly locked.
00951   getType()->getContext().pImpl->VectorConstants.remove(this);
00952   destroyConstantImpl();
00953 }
00954 
00955 /// This function will return true iff every element in this vector constant
00956 /// is set to all ones.
00957 /// @returns true iff this constant's emements are all set to all ones.
00958 /// @brief Determine if the value is all ones.
00959 bool ConstantVector::isAllOnesValue() const {
00960   // Check out first element.
00961   const Constant *Elt = getOperand(0);
00962   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
00963   if (!CI || !CI->isAllOnesValue()) return false;
00964   // Then make sure all remaining elements point to the same value.
00965   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
00966     if (getOperand(I) != Elt) return false;
00967   }
00968   return true;
00969 }
00970 
00971 /// getSplatValue - If this is a splat constant, where all of the
00972 /// elements have the same value, return that value. Otherwise return null.
00973 Constant *ConstantVector::getSplatValue() {
00974   // Check out first element.
00975   Constant *Elt = getOperand(0);
00976   // Then make sure all remaining elements point to the same value.
00977   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
00978     if (getOperand(I) != Elt) return 0;
00979   return Elt;
00980 }
00981 
00982 //---- ConstantPointerNull::get() implementation...
00983 //
00984 
00985 static char getValType(ConstantPointerNull *) {
00986   return 0;
00987 }
00988 
00989 
00990 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
00991   // Implicitly locked.
00992   return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
00993 }
00994 
00995 // destroyConstant - Remove the constant from the constant table...
00996 //
00997 void ConstantPointerNull::destroyConstant() {
00998   // Implicitly locked.
00999   getType()->getContext().pImpl->NullPtrConstants.remove(this);
01000   destroyConstantImpl();
01001 }
01002 
01003 
01004 //---- UndefValue::get() implementation...
01005 //
01006 
01007 static char getValType(UndefValue *) {
01008   return 0;
01009 }
01010 
01011 UndefValue *UndefValue::get(const Type *Ty) {
01012   // Implicitly locked.
01013   return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
01014 }
01015 
01016 // destroyConstant - Remove the constant from the constant table.
01017 //
01018 void UndefValue::destroyConstant() {
01019   // Implicitly locked.
01020   getType()->getContext().pImpl->UndefValueConstants.remove(this);
01021   destroyConstantImpl();
01022 }
01023 
01024 //---- ConstantExpr::get() implementations...
01025 //
01026 
01027 static ExprMapKeyType getValType(ConstantExpr *CE) {
01028   std::vector<Constant*> Operands;
01029   Operands.reserve(CE->getNumOperands());
01030   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
01031     Operands.push_back(cast<Constant>(CE->getOperand(i)));
01032   return ExprMapKeyType(CE->getOpcode(), Operands, 
01033       CE->isCompare() ? CE->getPredicate() : 0,
01034       CE->hasIndices() ?
01035         CE->getIndices() : SmallVector<unsigned, 4>());
01036 }
01037 
01038 /// This is a utility function to handle folding of casts and lookup of the
01039 /// cast in the ExprConstants map. It is used by the various get* methods below.
01040 static inline Constant *getFoldedCast(
01041   Instruction::CastOps opc, Constant *C, const Type *Ty) {
01042   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
01043   // Fold a few common cases
01044   if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
01045     return FC;
01046 
01047   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
01048 
01049   // Look up the constant in the table first to ensure uniqueness
01050   std::vector<Constant*> argVec(1, C);
01051   ExprMapKeyType Key(opc, argVec);
01052   
01053   // Implicitly locked.
01054   return pImpl->ExprConstants.getOrCreate(Ty, Key);
01055 }
01056  
01057 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
01058   Instruction::CastOps opc = Instruction::CastOps(oc);
01059   assert(Instruction::isCast(opc) && "opcode out of range");
01060   assert(C && Ty && "Null arguments to getCast");
01061   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
01062 
01063   switch (opc) {
01064     default:
01065       llvm_unreachable("Invalid cast opcode");
01066       break;
01067     case Instruction::Trunc:    return getTrunc(C, Ty);
01068     case Instruction::ZExt:     return getZExt(C, Ty);
01069     case Instruction::SExt:     return getSExt(C, Ty);
01070     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
01071     case Instruction::FPExt:    return getFPExtend(C, Ty);
01072     case Instruction::UIToFP:   return getUIToFP(C, Ty);
01073     case Instruction::SIToFP:   return getSIToFP(C, Ty);
01074     case Instruction::FPToUI:   return getFPToUI(C, Ty);
01075     case Instruction::FPToSI:   return getFPToSI(C, Ty);
01076     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
01077     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
01078     case Instruction::BitCast:  return getBitCast(C, Ty);
01079   }
01080   return 0;
01081 } 
01082 
01083 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
01084   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01085     return getCast(Instruction::BitCast, C, Ty);
01086   return getCast(Instruction::ZExt, C, Ty);
01087 }
01088 
01089 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
01090   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01091     return getCast(Instruction::BitCast, C, Ty);
01092   return getCast(Instruction::SExt, C, Ty);
01093 }
01094 
01095 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
01096   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
01097     return getCast(Instruction::BitCast, C, Ty);
01098   return getCast(Instruction::Trunc, C, Ty);
01099 }
01100 
01101 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
01102   assert(isa<PointerType>(S->getType()) && "Invalid cast");
01103   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
01104 
01105   if (Ty->isInteger())
01106     return getCast(Instruction::PtrToInt, S, Ty);
01107   return getCast(Instruction::BitCast, S, Ty);
01108 }
01109 
01110 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
01111                                        bool isSigned) {
01112   assert(C->getType()->isIntOrIntVector() &&
01113          Ty->isIntOrIntVector() && "Invalid cast");
01114   unsigned SrcBits = C->getType()->getScalarSizeInBits();
01115   unsigned DstBits = Ty->getScalarSizeInBits();
01116   Instruction::CastOps opcode =
01117     (SrcBits == DstBits ? Instruction::BitCast :
01118      (SrcBits > DstBits ? Instruction::Trunc :
01119       (isSigned ? Instruction::SExt : Instruction::ZExt)));
01120   return getCast(opcode, C, Ty);
01121 }
01122 
01123 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
01124   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
01125          "Invalid cast");
01126   unsigned SrcBits = C->getType()->getScalarSizeInBits();
01127   unsigned DstBits = Ty->getScalarSizeInBits();
01128   if (SrcBits == DstBits)
01129     return C; // Avoid a useless cast
01130   Instruction::CastOps opcode =
01131      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
01132   return getCast(opcode, C, Ty);
01133 }
01134 
01135 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
01136 #ifndef NDEBUG
01137   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01138   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01139 #endif
01140   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01141   assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
01142   assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
01143   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
01144          "SrcTy must be larger than DestTy for Trunc!");
01145 
01146   return getFoldedCast(Instruction::Trunc, C, Ty);
01147 }
01148 
01149 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
01150 #ifndef NDEBUG
01151   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01152   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01153 #endif
01154   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01155   assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
01156   assert(Ty->isIntOrIntVector() && "SExt produces only integer");
01157   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
01158          "SrcTy must be smaller than DestTy for SExt!");
01159 
01160   return getFoldedCast(Instruction::SExt, C, Ty);
01161 }
01162 
01163 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
01164 #ifndef NDEBUG
01165   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01166   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01167 #endif
01168   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01169   assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
01170   assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
01171   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
01172          "SrcTy must be smaller than DestTy for ZExt!");
01173 
01174   return getFoldedCast(Instruction::ZExt, C, Ty);
01175 }
01176 
01177 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
01178 #ifndef NDEBUG
01179   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01180   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01181 #endif
01182   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01183   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
01184          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
01185          "This is an illegal floating point truncation!");
01186   return getFoldedCast(Instruction::FPTrunc, C, Ty);
01187 }
01188 
01189 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
01190 #ifndef NDEBUG
01191   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01192   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01193 #endif
01194   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01195   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
01196          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
01197          "This is an illegal floating point extension!");
01198   return getFoldedCast(Instruction::FPExt, C, Ty);
01199 }
01200 
01201 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
01202 #ifndef NDEBUG
01203   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01204   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01205 #endif
01206   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01207   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
01208          "This is an illegal uint to floating point cast!");
01209   return getFoldedCast(Instruction::UIToFP, C, Ty);
01210 }
01211 
01212 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
01213 #ifndef NDEBUG
01214   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01215   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01216 #endif
01217   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01218   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
01219          "This is an illegal sint to floating point cast!");
01220   return getFoldedCast(Instruction::SIToFP, C, Ty);
01221 }
01222 
01223 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
01224 #ifndef NDEBUG
01225   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01226   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01227 #endif
01228   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01229   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
01230          "This is an illegal floating point to uint cast!");
01231   return getFoldedCast(Instruction::FPToUI, C, Ty);
01232 }
01233 
01234 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
01235 #ifndef NDEBUG
01236   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
01237   bool toVec = Ty->getTypeID() == Type::VectorTyID;
01238 #endif
01239   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
01240   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
01241          "This is an illegal floating point to sint cast!");
01242   return getFoldedCast(Instruction::FPToSI, C, Ty);
01243 }
01244 
01245 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
01246   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
01247   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
01248   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
01249 }
01250 
01251 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
01252   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
01253   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
01254   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
01255 }
01256 
01257 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
01258   // BitCast implies a no-op cast of type only. No bits change.  However, you 
01259   // can't cast pointers to anything but pointers.
01260 #ifndef NDEBUG
01261   const Type *SrcTy = C->getType();
01262   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
01263          "BitCast cannot cast pointer to non-pointer and vice versa");
01264 
01265   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
01266   // or nonptr->ptr). For all the other types, the cast is okay if source and 
01267   // destination bit widths are identical.
01268   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
01269   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
01270 #endif
01271   assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
01272   
01273   // It is common to ask for a bitcast of a value to its own type, handle this
01274   // speedily.
01275   if (C->getType() == DstTy) return C;
01276   
01277   return getFoldedCast(Instruction::BitCast, C, DstTy);
01278 }
01279 
01280 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
01281                               Constant *C1, Constant *C2) {
01282   // Check the operands for consistency first
01283   assert(Opcode >= Instruction::BinaryOpsBegin &&
01284          Opcode <  Instruction::BinaryOpsEnd   &&
01285          "Invalid opcode in binary constant expression");
01286   assert(C1->getType() == C2->getType() &&
01287          "Operand types in binary constant expression should match");
01288 
01289   if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
01290     if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
01291                                                      Opcode, C1, C2))
01292       return FC;          // Fold a few common cases...
01293 
01294   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
01295   ExprMapKeyType Key(Opcode, argVec);
01296   
01297   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
01298   
01299   // Implicitly locked.
01300   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
01301 }
01302 
01303 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
01304                                      Constant *C1, Constant *C2) {
01305   switch (predicate) {
01306     default: llvm_unreachable("Invalid CmpInst predicate");
01307     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
01308     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
01309     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
01310     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
01311     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
01312     case CmpInst::FCMP_TRUE:
01313       return getFCmp(predicate, C1, C2);
01314 
01315     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
01316     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
01317     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
01318     case CmpInst::ICMP_SLE:
01319       return getICmp(predicate, C1, C2);
01320   }
01321 }
01322 
01323 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
01324   // API compatibility: Adjust integer opcodes to floating-point opcodes.
01325   if (C1->getType()->isFPOrFPVector()) {
01326     if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
01327     else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
01328     else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
01329   }
01330 #ifndef NDEBUG
01331   switch (Opcode) {
01332   case Instruction::Add:
01333   case Instruction::Sub:
01334   case Instruction::Mul:
01335     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01336     assert(C1->getType()->isIntOrIntVector() &&
01337            "Tried to create an integer operation on a non-integer type!");
01338     break;
01339   case Instruction::FAdd:
01340   case Instruction::FSub:
01341   case Instruction::FMul:
01342     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01343     assert(C1->getType()->isFPOrFPVector() &&
01344            "Tried to create a floating-point operation on a "
01345            "non-floating-point type!");
01346     break;
01347   case Instruction::UDiv: 
01348   case Instruction::SDiv: 
01349     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01350     assert(C1->getType()->isIntOrIntVector() &&
01351            "Tried to create an arithmetic operation on a non-arithmetic type!");
01352     break;
01353   case Instruction::FDiv:
01354     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01355     assert(C1->getType()->isFPOrFPVector() &&
01356            "Tried to create an arithmetic operation on a non-arithmetic type!");
01357     break;
01358   case Instruction::URem: 
01359   case Instruction::SRem: 
01360     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01361     assert(C1->getType()->isIntOrIntVector() &&
01362            "Tried to create an arithmetic operation on a non-arithmetic type!");
01363     break;
01364   case Instruction::FRem:
01365     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01366     assert(C1->getType()->isFPOrFPVector() &&
01367            "Tried to create an arithmetic operation on a non-arithmetic type!");
01368     break;
01369   case Instruction::And:
01370   case Instruction::Or:
01371   case Instruction::Xor:
01372     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01373     assert(C1->getType()->isIntOrIntVector() &&
01374            "Tried to create a logical operation on a non-integral type!");
01375     break;
01376   case Instruction::Shl:
01377   case Instruction::LShr:
01378   case Instruction::AShr:
01379     assert(C1->getType() == C2->getType() && "Op types should be identical!");
01380     assert(C1->getType()->isIntOrIntVector() &&
01381            "Tried to create a shift operation on a non-integer type!");
01382     break;
01383   default:
01384     break;
01385   }
01386 #endif
01387 
01388   return getTy(C1->getType(), Opcode, C1, C2);
01389 }
01390 
01391 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
01392   // sizeof is implemented as: (i64) gep (Ty*)null, 1
01393   // Note that a non-inbounds gep is used, as null isn't within any object.
01394   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
01395   Constant *GEP = getGetElementPtr(
01396                  Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
01397   return getCast(Instruction::PtrToInt, GEP, 
01398                  Type::getInt64Ty(Ty->getContext()));
01399 }
01400 
01401 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
01402   // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
01403   // Note that a non-inbounds gep is used, as null isn't within any object.
01404   const Type *AligningTy = StructType::get(Ty->getContext(),
01405                                    Type::getInt8Ty(Ty->getContext()), Ty, NULL);
01406   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
01407   Constant *Zero = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 0);
01408   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
01409   Constant *Indices[2] = { Zero, One };
01410   Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
01411   return getCast(Instruction::PtrToInt, GEP,
01412                  Type::getInt32Ty(Ty->getContext()));
01413 }
01414 
01415 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
01416   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
01417   // Note that a non-inbounds gep is used, as null isn't within any object.
01418   Constant *GEPIdx[] = {
01419     ConstantInt::get(Type::getInt64Ty(STy->getContext()), 0),
01420     ConstantInt::get(Type::getInt32Ty(STy->getContext()), FieldNo)
01421   };
01422   Constant *GEP = getGetElementPtr(
01423                 Constant::getNullValue(PointerType::getUnqual(STy)), GEPIdx, 2);
01424   return getCast(Instruction::PtrToInt, GEP,
01425                  Type::getInt64Ty(STy->getContext()));
01426 }
01427 
01428 Constant *ConstantExpr::getCompare(unsigned short pred, 
01429                             Constant *C1, Constant *C2) {
01430   assert(C1->getType() == C2->getType() && "Op types should be identical!");
01431   return getCompareTy(pred, C1, C2);
01432 }
01433 
01434 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
01435                                     Constant *V1, Constant *V2) {
01436   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
01437 
01438   if (ReqTy == V1->getType())
01439     if (Constant *SC = ConstantFoldSelectInstruction(
01440                                                 ReqTy->getContext(), C, V1, V2))
01441       return SC;        // Fold common cases
01442 
01443   std::vector<Constant*> argVec(3, C);
01444   argVec[1] = V1;
01445   argVec[2] = V2;
01446   ExprMapKeyType Key(Instruction::Select, argVec);
01447   
01448   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
01449   
01450   // Implicitly locked.
01451   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
01452 }
01453 
01454 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
01455                                            Value* const *Idxs,
01456                                            unsigned NumIdx) {
01457   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
01458                                            Idxs+NumIdx) ==
01459          cast<PointerType>(ReqTy)->getElementType() &&
01460          "GEP indices invalid!");
01461 
01462   if (Constant *FC = ConstantFoldGetElementPtr(
01463                               ReqTy->getContext(), C, (Constant**)Idxs, NumIdx))
01464     return FC;          // Fold a few common cases...
01465 
01466   assert(isa<PointerType>(C->getType()) &&
01467          "Non-pointer type for constant GetElementPtr expression");
01468   // Look up the constant in the table first to ensure uniqueness
01469   std::vector<Constant*> ArgVec;
01470   ArgVec.reserve(NumIdx+1);
01471   ArgVec.push_back(C);
01472   for (unsigned i = 0; i != NumIdx; ++i)
01473     ArgVec.push_back(cast<Constant>(Idxs[i]));
01474   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
01475 
01476   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
01477 
01478   // Implicitly locked.
01479   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
01480 }
01481 
01482 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
01483                                          unsigned NumIdx) {
01484   // Get the result type of the getelementptr!
01485   const Type *Ty = 
01486     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
01487   assert(Ty && "GEP indices invalid!");
01488   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
01489   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
01490 }
01491 
01492 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
01493                                                  Value* const *Idxs,
01494                                                  unsigned NumIdx) {
01495   Constant *Result = getGetElementPtr(C, Idxs, NumIdx);
01496   // Set in bounds attribute, assuming constant folding didn't eliminate the
01497   // GEP.
01498   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Result))
01499     GEP->setIsInBounds(true);
01500   return Result;
01501 }
01502 
01503 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
01504                                          unsigned NumIdx) {
01505   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
01506 }
01507 
01508 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
01509                                                  Constant* const *Idxs,
01510                                                  unsigned NumIdx) {
01511   return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
01512 }
01513 
01514 Constant *
01515 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
01516   assert(LHS->getType() == RHS->getType());
01517   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
01518          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
01519 
01520   if (Constant *FC = ConstantFoldCompareInstruction(
01521                                              LHS->getContext(), pred, LHS, RHS))
01522     return FC;          // Fold a few common cases...
01523 
01524   // Look up the constant in the table first to ensure uniqueness
01525   std::vector<Constant*> ArgVec;
01526   ArgVec.push_back(LHS);
01527   ArgVec.push_back(RHS);
01528   // Get the key type with both the opcode and predicate
01529   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
01530 
01531   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
01532 
01533   // Implicitly locked.
01534   return
01535       pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
01536 }
01537 
01538 Constant *
01539 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
01540   assert(LHS->getType() == RHS->getType());
01541   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
01542 
01543   if (Constant *FC = ConstantFoldCompareInstruction(
01544                                             LHS->getContext(), pred, LHS, RHS))
01545     return FC;          // Fold a few common cases...
01546 
01547   // Look up the constant in the table first to ensure uniqueness
01548   std::vector<Constant*> ArgVec;
01549   ArgVec.push_back(LHS);
01550   ArgVec.push_back(RHS);
01551   // Get the key type with both the opcode and predicate
01552   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
01553   
01554   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
01555   
01556   // Implicitly locked.
01557   return
01558       pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
01559 }
01560 
01561 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
01562                                             Constant *Idx) {
01563   if (Constant *FC = ConstantFoldExtractElementInstruction(
01564                                                 ReqTy->getContext(), Val, Idx))
01565     return FC;          // Fold a few common cases...
01566   // Look up the constant in the table first to ensure uniqueness
01567   std::vector<Constant*> ArgVec(1, Val);
01568   ArgVec.push_back(Idx);
01569   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
01570   
01571   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
01572   
01573   // Implicitly locked.
01574   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
01575 }
01576 
01577 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
01578   assert(isa<VectorType>(Val->getType()) &&
01579          "Tried to create extractelement operation on non-vector type!");
01580   assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
01581          "Extractelement index must be i32 type!");
01582   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
01583                              Val, Idx);
01584 }
01585 
01586 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
01587                                            Constant *Elt, Constant *Idx) {
01588   if (Constant *FC = ConstantFoldInsertElementInstruction(
01589                                             ReqTy->getContext(), Val, Elt, Idx))
01590     return FC;          // Fold a few common cases...
01591   // Look up the constant in the table first to ensure uniqueness
01592   std::vector<Constant*> ArgVec(1, Val);
01593   ArgVec.push_back(Elt);
01594   ArgVec.push_back(Idx);
01595   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
01596   
01597   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
01598   
01599   // Implicitly locked.
01600   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
01601 }
01602 
01603 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
01604                                          Constant *Idx) {
01605   assert(isa<VectorType>(Val->getType()) &&
01606          "Tried to create insertelement operation on non-vector type!");
01607   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
01608          && "Insertelement types must match!");
01609   assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
01610          "Insertelement index must be i32 type!");
01611   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
01612 }
01613 
01614 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
01615                                            Constant *V2, Constant *Mask) {
01616   if (Constant *FC = ConstantFoldShuffleVectorInstruction(
01617                                             ReqTy->getContext(), V1, V2, Mask))
01618     return FC;          // Fold a few common cases...
01619   // Look up the constant in the table first to ensure uniqueness
01620   std::vector<Constant*> ArgVec(1, V1);
01621   ArgVec.push_back(V2);
01622   ArgVec.push_back(Mask);
01623   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
01624   
01625   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
01626   
01627   // Implicitly locked.
01628   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
01629 }
01630 
01631 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
01632                                          Constant *Mask) {
01633   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
01634          "Invalid shuffle vector constant expr operands!");
01635 
01636   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
01637   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
01638   const Type *ShufTy = VectorType::get(EltTy, NElts);
01639   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
01640 }
01641 
01642 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
01643                                          Constant *Val,
01644                                         const unsigned *Idxs, unsigned NumIdx) {
01645   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
01646                                           Idxs+NumIdx) == Val->getType() &&
01647          "insertvalue indices invalid!");
01648   assert(Agg->getType() == ReqTy &&
01649          "insertvalue type invalid!");
01650   assert(Agg->getType()->isFirstClassType() &&
01651          "Non-first-class type for constant InsertValue expression");
01652   Constant *FC = ConstantFoldInsertValueInstruction(
01653                                   ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
01654   assert(FC && "InsertValue constant expr couldn't be folded!");
01655   return FC;
01656 }
01657 
01658 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
01659                                      const unsigned *IdxList, unsigned NumIdx) {
01660   assert(Agg->getType()->isFirstClassType() &&
01661          "Tried to create insertelement operation on non-first-class type!");
01662 
01663   const Type *ReqTy = Agg->getType();
01664 #ifndef NDEBUG
01665   const Type *ValTy =
01666     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
01667 #endif
01668   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
01669   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
01670 }
01671 
01672 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
01673                                         const unsigned *Idxs, unsigned NumIdx) {
01674   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
01675                                           Idxs+NumIdx) == ReqTy &&
01676          "extractvalue indices invalid!");
01677   assert(Agg->getType()->isFirstClassType() &&
01678          "Non-first-class type for constant extractvalue expression");
01679   Constant *FC = ConstantFoldExtractValueInstruction(
01680                                         ReqTy->getContext(), Agg, Idxs, NumIdx);
01681   assert(FC && "ExtractValue constant expr couldn't be folded!");
01682   return FC;
01683 }
01684 
01685 Constant *ConstantExpr::getExtractValue(Constant *Agg,
01686                                      const unsigned *IdxList, unsigned NumIdx) {
01687   assert(Agg->getType()->isFirstClassType() &&
01688          "Tried to create extractelement operation on non-first-class type!");
01689 
01690   const Type *ReqTy =
01691     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
01692   assert(ReqTy && "extractvalue indices invalid!");
01693   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
01694 }
01695 
01696 Constant* ConstantExpr::getNeg(Constant* C) {
01697   // API compatibility: Adjust integer opcodes to floating-point opcodes.
01698   if (C->getType()->isFPOrFPVector())
01699     return getFNeg(C);
01700   assert(C->getType()->isIntOrIntVector() &&
01701          "Cannot NEG a nonintegral value!");
01702   return get(Instruction::Sub,
01703              ConstantFP::getZeroValueForNegation(C->getType()),
01704              C);
01705 }
01706 
01707 Constant* ConstantExpr::getFNeg(Constant* C) {
01708   assert(C->getType()->isFPOrFPVector() &&
01709          "Cannot FNEG a non-floating-point value!");
01710   return get(Instruction::FSub,
01711              ConstantFP::getZeroValueForNegation(C->getType()),
01712              C);
01713 }
01714 
01715 Constant* ConstantExpr::getNot(Constant* C) {
01716   assert(C->getType()->isIntOrIntVector() &&
01717          "Cannot NOT a nonintegral value!");
01718   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
01719 }
01720 
01721 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
01722   return get(Instruction::Add, C1, C2);
01723 }
01724 
01725 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
01726   return get(Instruction::FAdd, C1, C2);
01727 }
01728 
01729 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
01730   return get(Instruction::Sub, C1, C2);
01731 }
01732 
01733 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
01734   return get(Instruction::FSub, C1, C2);
01735 }
01736 
01737 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
01738   return get(Instruction::Mul, C1, C2);
01739 }
01740 
01741 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
01742   return get(Instruction::FMul, C1, C2);
01743 }
01744 
01745 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
01746   return get(Instruction::UDiv, C1, C2);
01747 }
01748 
01749 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
01750   return get(Instruction::SDiv, C1, C2);
01751 }
01752 
01753 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
01754   return get(Instruction::FDiv, C1, C2);
01755 }
01756 
01757 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
01758   return get(Instruction::URem, C1, C2);
01759 }
01760 
01761 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
01762   return get(Instruction::SRem, C1, C2);
01763 }
01764 
01765 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
01766   return get(Instruction::FRem, C1, C2);
01767 }
01768 
01769 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
01770   return get(Instruction::And, C1, C2);
01771 }
01772 
01773 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
01774   return get(Instruction::Or, C1, C2);
01775 }
01776 
01777 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
01778   return get(Instruction::Xor, C1, C2);
01779 }
01780 
01781 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
01782   return get(Instruction::Shl, C1, C2);
01783 }
01784 
01785 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
01786   return get(Instruction::LShr, C1, C2);
01787 }
01788 
01789 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
01790   return get(Instruction::AShr, C1, C2);
01791 }
01792 
01793 // destroyConstant - Remove the constant from the constant table...
01794 //
01795 void ConstantExpr::destroyConstant() {
01796   // Implicitly locked.
01797   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
01798   pImpl->ExprConstants.remove(this);
01799   destroyConstantImpl();
01800 }
01801 
01802 const char *ConstantExpr::getOpcodeName() const {
01803   return Instruction::getOpcodeName(getOpcode());
01804 }
01805 
01806 //===----------------------------------------------------------------------===//
01807 //                replaceUsesOfWithOnConstant implementations
01808 
01809 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
01810 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
01811 /// etc.
01812 ///
01813 /// Note that we intentionally replace all uses of From with To here.  Consider
01814 /// a large array that uses 'From' 1000 times.  By handling this case all here,
01815 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
01816 /// single invocation handles all 1000 uses.  Handling them one at a time would
01817 /// work, but would be really slow because it would have to unique each updated
01818 /// array instance.
01819 
01820 static std::vector<Constant*> getValType(ConstantArray *CA) {
01821   std::vector<Constant*> Elements;
01822   Elements.reserve(CA->getNumOperands());
01823   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
01824     Elements.push_back(cast<Constant>(CA->getOperand(i)));
01825   return Elements;
01826 }
01827 
01828 
01829 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
01830                                                 Use *U) {
01831   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
01832   Constant *ToC = cast<Constant>(To);
01833 
01834   LLVMContext &Context = getType()->getContext();
01835   LLVMContextImpl *pImpl = Context.pImpl;
01836 
01837   std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
01838   Lookup.first.first = getType();
01839   Lookup.second = this;
01840 
01841   std::vector<Constant*> &Values = Lookup.first.second;
01842   Values.reserve(getNumOperands());  // Build replacement array.
01843 
01844   // Fill values with the modified operands of the constant array.  Also, 
01845   // compute whether this turns into an all-zeros array.
01846   bool isAllZeros = false;
01847   unsigned NumUpdated = 0;
01848   if (!ToC->isNullValue()) {
01849     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
01850       Constant *Val = cast<Constant>(O->get());
01851       if (Val == From) {
01852         Val = ToC;
01853         ++NumUpdated;
01854       }
01855       Values.push_back(Val);
01856     }
01857   } else {
01858     isAllZeros = true;
01859     for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
01860       Constant *Val = cast<Constant>(O->get());
01861       if (Val == From) {
01862         Val = ToC;
01863         ++NumUpdated;
01864       }
01865       Values.push_back(Val);
01866       if (isAllZeros) isAllZeros = Val->isNullValue();
01867     }
01868   }
01869   
01870   Constant *Replacement = 0;
01871   if (isAllZeros) {
01872     Replacement = ConstantAggregateZero::get(getType());
01873   } else {
01874     // Check to see if we have this array type already.
01875     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
01876     bool Exists;
01877     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
01878       pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
01879     
01880     if (Exists) {
01881       Replacement = cast<Constant>(I->second);
01882     } else {
01883       // Okay, the new shape doesn't exist in the system yet.  Instead of
01884       // creating a new constant array, inserting it, replaceallusesof'ing the
01885       // old with the new, then deleting the old... just update the current one
01886       // in place!
01887       pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
01888       
01889       // Update to the new value.  Optimize for the case when we have a single
01890       // operand that we're changing, but handle bulk updates efficiently.
01891       if (NumUpdated == 1) {
01892         unsigned OperandToUpdate = U - OperandList;
01893         assert(getOperand(OperandToUpdate) == From &&
01894                "ReplaceAllUsesWith broken!");
01895         setOperand(OperandToUpdate, ToC);
01896       } else {
01897         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
01898           if (getOperand(i) == From)
01899             setOperand(i, ToC);
01900       }
01901       return;
01902     }
01903   }
01904  
01905   // Otherwise, I do need to replace this with an existing value.
01906   assert(Replacement != this && "I didn't contain From!");
01907   
01908   // Everyone using this now uses the replacement.
01909   uncheckedReplaceAllUsesWith(Replacement);
01910   
01911   // Delete the old constant!
01912   destroyConstant();
01913 }
01914 
01915 static std::vector<Constant*> getValType(ConstantStruct *CS) {
01916   std::vector<Constant*> Elements;
01917   Elements.reserve(CS->getNumOperands());
01918   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
01919     Elements.push_back(cast<Constant>(CS->getOperand(i)));
01920   return Elements;
01921 }
01922 
01923 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
01924                                                  Use *U) {
01925   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
01926   Constant *ToC = cast<Constant>(To);
01927 
01928   unsigned OperandToUpdate = U-OperandList;
01929   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
01930 
01931   std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
01932   Lookup.first.first = getType();
01933   Lookup.second = this;
01934   std::vector<Constant*> &Values = Lookup.first.second;
01935   Values.reserve(getNumOperands());  // Build replacement struct.
01936   
01937   
01938   // Fill values with the modified operands of the constant struct.  Also, 
01939   // compute whether this turns into an all-zeros struct.
01940   bool isAllZeros = false;
01941   if (!ToC->isNullValue()) {
01942     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
01943       Values.push_back(cast<Constant>(O->get()));
01944   } else {
01945     isAllZeros = true;
01946     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
01947       Constant *Val = cast<Constant>(O->get());
01948       Values.push_back(Val);
01949       if (isAllZeros) isAllZeros = Val->isNullValue();
01950     }
01951   }
01952   Values[OperandToUpdate] = ToC;
01953   
01954   LLVMContext &Context = getType()->getContext();
01955   LLVMContextImpl *pImpl = Context.pImpl;
01956   
01957   Constant *Replacement = 0;
01958   if (isAllZeros) {
01959     Replacement = ConstantAggregateZero::get(getType());
01960   } else {
01961     // Check to see if we have this array type already.
01962     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
01963     bool Exists;
01964     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
01965       pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
01966     
01967     if (Exists) {
01968       Replacement = cast<Constant>(I->second);
01969     } else {
01970       // Okay, the new shape doesn't exist in the system yet.  Instead of
01971       // creating a new constant struct, inserting it, replaceallusesof'ing the
01972       // old with the new, then deleting the old... just update the current one
01973       // in place!
01974       pImpl->StructConstants.MoveConstantToNewSlot(this, I);
01975       
01976       // Update to the new value.
01977       setOperand(OperandToUpdate, ToC);
01978       return;
01979     }
01980   }
01981   
01982   assert(Replacement != this && "I didn't contain From!");
01983   
01984   // Everyone using this now uses the replacement.
01985   uncheckedReplaceAllUsesWith(Replacement);
01986   
01987   // Delete the old constant!
01988   destroyConstant();
01989 }
01990 
01991 static std::vector<Constant*> getValType(ConstantVector *CP) {
01992   std::vector<Constant*> Elements;
01993   Elements.reserve(CP->getNumOperands());
01994   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
01995     Elements.push_back(CP->getOperand(i));
01996   return Elements;
01997 }
01998 
01999 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
02000                                                  Use *U) {
02001   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
02002   
02003   std::vector<Constant*> Values;
02004   Values.reserve(getNumOperands());  // Build replacement array...
02005   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
02006     Constant *Val = getOperand(i);
02007     if (Val == From) Val = cast<Constant>(To);
02008     Values.push_back(Val);
02009   }
02010   
02011   Constant *Replacement = get(getType(), Values);
02012   assert(Replacement != this && "I didn't contain From!");
02013   
02014   // Everyone using this now uses the replacement.
02015   uncheckedReplaceAllUsesWith(Replacement);
02016   
02017   // Delete the old constant!
02018   destroyConstant();
02019 }
02020 
02021 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
02022                                                Use *U) {
02023   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
02024   Constant *To = cast<Constant>(ToV);
02025   
02026   Constant *Replacement = 0;
02027   if (getOpcode() == Instruction::GetElementPtr) {
02028     SmallVector<Constant*, 8> Indices;
02029     Constant *Pointer = getOperand(0);
02030     Indices.reserve(getNumOperands()-1);
02031     if (Pointer == From) Pointer = To;
02032     
02033     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
02034       Constant *Val = getOperand(i);
02035       if (Val == From) Val = To;
02036       Indices.push_back(Val);
02037     }
02038     Replacement = ConstantExpr::getGetElementPtr(Pointer,
02039                                                  &Indices[0], Indices.size());
02040   } else if (getOpcode() == Instruction::ExtractValue) {
02041     Constant *Agg = getOperand(0);
02042     if (Agg == From) Agg = To;
02043     
02044     const SmallVector<unsigned, 4> &Indices = getIndices();
02045     Replacement = ConstantExpr::getExtractValue(Agg,
02046                                                 &Indices[0], Indices.size());
02047   } else if (getOpcode() == Instruction::InsertValue) {
02048     Constant *Agg = getOperand(0);
02049     Constant *Val = getOperand(1);
02050     if (Agg == From) Agg = To;
02051     if (Val == From) Val = To;
02052     
02053     const SmallVector<unsigned, 4> &Indices = getIndices();
02054     Replacement = ConstantExpr::getInsertValue(Agg, Val,
02055                                                &Indices[0], Indices.size());
02056   } else if (isCast()) {
02057     assert(getOperand(0) == From && "Cast only has one use!");
02058     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
02059   } else if (getOpcode() == Instruction::Select) {
02060     Constant *C1 = getOperand(0);
02061     Constant *C2 = getOperand(1);
02062     Constant *C3 = getOperand(2);
02063     if (C1 == From) C1 = To;
02064     if (C2 == From) C2 = To;
02065     if (C3 == From) C3 = To;
02066     Replacement = ConstantExpr::getSelect(C1, C2, C3);
02067   } else if (getOpcode() == Instruction::ExtractElement) {
02068     Constant *C1 = getOperand(0);
02069     Constant *C2 = getOperand(1);
02070     if (C1 == From) C1 = To;
02071     if (C2 == From) C2 = To;
02072     Replacement = ConstantExpr::getExtractElement(C1, C2);
02073   } else if (getOpcode() == Instruction::InsertElement) {
02074     Constant *C1 = getOperand(0);
02075     Constant *C2 = getOperand(1);
02076     Constant *C3 = getOperand(1);
02077     if (C1 == From) C1 = To;
02078     if (C2 == From) C2 = To;
02079     if (C3 == From) C3 = To;
02080     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
02081   } else if (getOpcode() == Instruction::ShuffleVector) {
02082     Constant *C1 = getOperand(0);
02083     Constant *C2 = getOperand(1);
02084     Constant *C3 = getOperand(2);
02085     if (C1 == From) C1 = To;
02086     if (C2 == From) C2 = To;
02087     if (C3 == From) C3 = To;
02088     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
02089   } else if (isCompare()) {
02090     Constant *C1 = getOperand(0);
02091     Constant *C2 = getOperand(1);
02092     if (C1 == From) C1 = To;
02093     if (C2 == From) C2 = To;
02094     if (getOpcode() == Instruction::ICmp)
02095       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
02096     else {
02097       assert(getOpcode() == Instruction::FCmp);
02098       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
02099     }
02100   } else if (getNumOperands() == 2) {
02101     Constant *C1 = getOperand(0);
02102     Constant *C2 = getOperand(1);
02103     if (C1 == From) C1 = To;
02104     if (C2 == From) C2 = To;
02105     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
02106   } else {
02107     llvm_unreachable("Unknown ConstantExpr type!");
02108     return;
02109   }
02110   
02111   assert(Replacement != this && "I didn't contain From!");
02112   
02113   // Everyone using this now uses the replacement.
02114   uncheckedReplaceAllUsesWith(Replacement);
02115   
02116   // Delete the old constant!
02117   destroyConstant();
02118 }
02119