LLVM API Documentation

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