Assert that ConstantArrays are created with correctly-typed elements.
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/System/Mutex.h"
33 #include "llvm/System/RWMutex.h"
34 #include "llvm/System/Threading.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include <algorithm>
38 #include <map>
39 using namespace llvm;
40
41 //===----------------------------------------------------------------------===//
42 //                              Constant Class
43 //===----------------------------------------------------------------------===//
44
45 // Constructor to create a '0' constant of arbitrary type...
46 static const uint64_t zero[2] = {0, 0};
47 Constant* Constant::getNullValue(const Type* Ty) {
48   switch (Ty->getTypeID()) {
49   case Type::IntegerTyID:
50     return ConstantInt::get(Ty, 0);
51   case Type::FloatTyID:
52     return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
53   case Type::DoubleTyID:
54     return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
55   case Type::X86_FP80TyID:
56     return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
57   case Type::FP128TyID:
58     return ConstantFP::get(Ty->getContext(),
59                            APFloat(APInt(128, 2, zero), true));
60   case Type::PPC_FP128TyID:
61     return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
62   case Type::PointerTyID:
63     return ConstantPointerNull::get(cast<PointerType>(Ty));
64   case Type::StructTyID:
65   case Type::ArrayTyID:
66   case Type::VectorTyID:
67     return ConstantAggregateZero::get(Ty);
68   default:
69     // Function, Label, or Opaque type?
70     assert(!"Cannot create a null constant of that type!");
71     return 0;
72   }
73 }
74
75 Constant* Constant::getIntegerValue(const Type* Ty, const APInt &V) {
76   const Type *ScalarTy = Ty->getScalarType();
77
78   // Create the base integer constant.
79   Constant *C = ConstantInt::get(Ty->getContext(), V);
80
81   // Convert an integer to a pointer, if necessary.
82   if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
83     C = ConstantExpr::getIntToPtr(C, PTy);
84
85   // Broadcast a scalar to a vector, if necessary.
86   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
87     C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
88
89   return C;
90 }
91
92 Constant* Constant::getAllOnesValue(const Type* Ty) {
93   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
94     return ConstantInt::get(Ty->getContext(),
95                             APInt::getAllOnesValue(ITy->getBitWidth()));
96   
97   std::vector<Constant*> Elts;
98   const VectorType* VTy = cast<VectorType>(Ty);
99   Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
100   assert(Elts[0] && "Not a vector integer type!");
101   return cast<ConstantVector>(ConstantVector::get(Elts));
102 }
103
104 void Constant::destroyConstantImpl() {
105   // When a Constant is destroyed, there may be lingering
106   // references to the constant by other constants in the constant pool.  These
107   // constants are implicitly dependent on the module that is being deleted,
108   // but they don't know that.  Because we only find out when the CPV is
109   // deleted, we must now notify all of our users (that should only be
110   // Constants) that they are, in fact, invalid now and should be deleted.
111   //
112   while (!use_empty()) {
113     Value *V = use_back();
114 #ifndef NDEBUG      // Only in -g mode...
115     if (!isa<Constant>(V)) {
116       errs() << "While deleting: " << *this
117              << "\n\nUse still stuck around after Def is destroyed: "
118              << *V << "\n\n";
119     }
120 #endif
121     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
122     Constant *CV = cast<Constant>(V);
123     CV->destroyConstant();
124
125     // The constant should remove itself from our use list...
126     assert((use_empty() || use_back() != V) && "Constant not removed!");
127   }
128
129   // Value has no outstanding references it is safe to delete it now...
130   delete this;
131 }
132
133 /// canTrap - Return true if evaluation of this constant could trap.  This is
134 /// true for things like constant expressions that could divide by zero.
135 bool Constant::canTrap() const {
136   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
137   // The only thing that could possibly trap are constant exprs.
138   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
139   if (!CE) return false;
140   
141   // ConstantExpr traps if any operands can trap. 
142   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
143     if (getOperand(i)->canTrap()) 
144       return true;
145
146   // Otherwise, only specific operations can trap.
147   switch (CE->getOpcode()) {
148   default:
149     return false;
150   case Instruction::UDiv:
151   case Instruction::SDiv:
152   case Instruction::FDiv:
153   case Instruction::URem:
154   case Instruction::SRem:
155   case Instruction::FRem:
156     // Div and rem can trap if the RHS is not known to be non-zero.
157     if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
158       return true;
159     return false;
160   }
161 }
162
163
164 /// getRelocationInfo - This method classifies the entry according to
165 /// whether or not it may generate a relocation entry.  This must be
166 /// conservative, so if it might codegen to a relocatable entry, it should say
167 /// so.  The return values are:
168 /// 
169 ///  NoRelocation: This constant pool entry is guaranteed to never have a
170 ///     relocation applied to it (because it holds a simple constant like
171 ///     '4').
172 ///  LocalRelocation: This entry has relocations, but the entries are
173 ///     guaranteed to be resolvable by the static linker, so the dynamic
174 ///     linker will never see them.
175 ///  GlobalRelocations: This entry may have arbitrary relocations.
176 ///
177 /// FIXME: This really should not be in VMCore.
178 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
179   if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
180     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
181       return LocalRelocation;  // Local to this file/library.
182     return GlobalRelocations;    // Global reference.
183   }
184   
185   PossibleRelocationsTy Result = NoRelocation;
186   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
187     Result = std::max(Result, getOperand(i)->getRelocationInfo());
188   
189   return Result;
190 }
191
192
193 /// getVectorElements - This method, which is only valid on constant of vector
194 /// type, returns the elements of the vector in the specified smallvector.
195 /// This handles breaking down a vector undef into undef elements, etc.  For
196 /// constant exprs and other cases we can't handle, we return an empty vector.
197 void Constant::getVectorElements(LLVMContext &Context,
198                                  SmallVectorImpl<Constant*> &Elts) const {
199   assert(isa<VectorType>(getType()) && "Not a vector constant!");
200   
201   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
202     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
203       Elts.push_back(CV->getOperand(i));
204     return;
205   }
206   
207   const VectorType *VT = cast<VectorType>(getType());
208   if (isa<ConstantAggregateZero>(this)) {
209     Elts.assign(VT->getNumElements(), 
210                 Constant::getNullValue(VT->getElementType()));
211     return;
212   }
213   
214   if (isa<UndefValue>(this)) {
215     Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
216     return;
217   }
218   
219   // Unknown type, must be constant expr etc.
220 }
221
222
223
224 //===----------------------------------------------------------------------===//
225 //                                ConstantInt
226 //===----------------------------------------------------------------------===//
227
228 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
229   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
230   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
231 }
232
233 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
234   LLVMContextImpl *pImpl = Context.pImpl;
235   sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
236   if (pImpl->TheTrueVal)
237     return pImpl->TheTrueVal;
238   else
239     return (pImpl->TheTrueVal =
240               ConstantInt::get(IntegerType::get(Context, 1), 1));
241 }
242
243 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
244   LLVMContextImpl *pImpl = Context.pImpl;
245   sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
246   if (pImpl->TheFalseVal)
247     return pImpl->TheFalseVal;
248   else
249     return (pImpl->TheFalseVal =
250               ConstantInt::get(IntegerType::get(Context, 1), 0));
251 }
252
253
254 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
255 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
256 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
257 // compare APInt's of different widths, which would violate an APInt class
258 // invariant which generates an assertion.
259 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
260   // Get the corresponding integer type for the bit width of the value.
261   const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
262   // get an existing value or the insertion position
263   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
264   
265   Context.pImpl->ConstantsLock.reader_acquire();
266   ConstantInt *&Slot = Context.pImpl->IntConstants[Key]; 
267   Context.pImpl->ConstantsLock.reader_release();
268     
269   if (!Slot) {
270     sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
271     ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key]; 
272     if (!Slot) {
273       NewSlot = new ConstantInt(ITy, V);
274     }
275     
276     return NewSlot;
277   } else {
278     return Slot;
279   }
280 }
281
282 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
283   Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
284                                V, isSigned);
285
286   // For vectors, broadcast the value.
287   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
288     return ConstantVector::get(
289       std::vector<Constant *>(VTy->getNumElements(), C));
290
291   return C;
292 }
293
294 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V, 
295                               bool isSigned) {
296   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
297 }
298
299 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
300   return get(Ty, V, true);
301 }
302
303 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
304   return get(Ty, V, true);
305 }
306
307 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
308   ConstantInt *C = get(Ty->getContext(), V);
309   assert(C->getType() == Ty->getScalarType() &&
310          "ConstantInt type doesn't match the type implied by its value!");
311
312   // For vectors, broadcast the value.
313   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
314     return ConstantVector::get(
315       std::vector<Constant *>(VTy->getNumElements(), C));
316
317   return C;
318 }
319
320 ConstantInt* ConstantInt::get(const IntegerType* Ty, const StringRef& Str,
321                               uint8_t radix) {
322   return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
323 }
324
325 //===----------------------------------------------------------------------===//
326 //                                ConstantFP
327 //===----------------------------------------------------------------------===//
328
329 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
330   if (Ty == Type::getFloatTy(Ty->getContext()))
331     return &APFloat::IEEEsingle;
332   if (Ty == Type::getDoubleTy(Ty->getContext()))
333     return &APFloat::IEEEdouble;
334   if (Ty == Type::getX86_FP80Ty(Ty->getContext()))
335     return &APFloat::x87DoubleExtended;
336   else if (Ty == Type::getFP128Ty(Ty->getContext()))
337     return &APFloat::IEEEquad;
338   
339   assert(Ty == Type::getPPC_FP128Ty(Ty->getContext()) && "Unknown FP format");
340   return &APFloat::PPCDoubleDouble;
341 }
342
343 /// get() - This returns a constant fp for the specified value in the
344 /// specified type.  This should only be used for simple constant values like
345 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
346 Constant* ConstantFP::get(const Type* Ty, double V) {
347   LLVMContext &Context = Ty->getContext();
348   
349   APFloat FV(V);
350   bool ignored;
351   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
352              APFloat::rmNearestTiesToEven, &ignored);
353   Constant *C = get(Context, FV);
354
355   // For vectors, broadcast the value.
356   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
357     return ConstantVector::get(
358       std::vector<Constant *>(VTy->getNumElements(), C));
359
360   return C;
361 }
362
363
364 Constant* ConstantFP::get(const Type* Ty, const StringRef& Str) {
365   LLVMContext &Context = Ty->getContext();
366
367   APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
368   Constant *C = get(Context, FV);
369
370   // For vectors, broadcast the value.
371   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
372     return ConstantVector::get(
373       std::vector<Constant *>(VTy->getNumElements(), C));
374
375   return C; 
376 }
377
378
379 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
380   LLVMContext &Context = Ty->getContext();
381   APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
382   apf.changeSign();
383   return get(Context, apf);
384 }
385
386
387 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
388   if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
389     if (PTy->getElementType()->isFloatingPoint()) {
390       std::vector<Constant*> zeros(PTy->getNumElements(),
391                            getNegativeZero(PTy->getElementType()));
392       return ConstantVector::get(PTy, zeros);
393     }
394
395   if (Ty->isFloatingPoint()) 
396     return getNegativeZero(Ty);
397
398   return Constant::getNullValue(Ty);
399 }
400
401
402 // ConstantFP accessors.
403 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
404   DenseMapAPFloatKeyInfo::KeyTy Key(V);
405   
406   LLVMContextImpl* pImpl = Context.pImpl;
407   
408   pImpl->ConstantsLock.reader_acquire();
409   ConstantFP *&Slot = pImpl->FPConstants[Key];
410   pImpl->ConstantsLock.reader_release();
411     
412   if (!Slot) {
413     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
414     ConstantFP *&NewSlot = pImpl->FPConstants[Key];
415     if (!NewSlot) {
416       const Type *Ty;
417       if (&V.getSemantics() == &APFloat::IEEEsingle)
418         Ty = Type::getFloatTy(Context);
419       else if (&V.getSemantics() == &APFloat::IEEEdouble)
420         Ty = Type::getDoubleTy(Context);
421       else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
422         Ty = Type::getX86_FP80Ty(Context);
423       else if (&V.getSemantics() == &APFloat::IEEEquad)
424         Ty = Type::getFP128Ty(Context);
425       else {
426         assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
427                "Unknown FP format");
428         Ty = Type::getPPC_FP128Ty(Context);
429       }
430       NewSlot = new ConstantFP(Ty, V);
431     }
432     
433     return NewSlot;
434   }
435   
436   return Slot;
437 }
438
439 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
440   const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
441   return ConstantFP::get(Ty->getContext(),
442                          APFloat::getInf(Semantics, Negative));
443 }
444
445 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
446   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
447   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
448          "FP type Mismatch");
449 }
450
451 bool ConstantFP::isNullValue() const {
452   return Val.isZero() && !Val.isNegative();
453 }
454
455 bool ConstantFP::isExactlyValue(const APFloat& V) const {
456   return Val.bitwiseIsEqual(V);
457 }
458
459 //===----------------------------------------------------------------------===//
460 //                            ConstantXXX Classes
461 //===----------------------------------------------------------------------===//
462
463
464 ConstantArray::ConstantArray(const ArrayType *T,
465                              const std::vector<Constant*> &V)
466   : Constant(T, ConstantArrayVal,
467              OperandTraits<ConstantArray>::op_end(this) - V.size(),
468              V.size()) {
469   assert(V.size() == T->getNumElements() &&
470          "Invalid initializer vector for constant array");
471   Use *OL = OperandList;
472   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
473        I != E; ++I, ++OL) {
474     Constant *C = *I;
475     assert((C->getType() == T->getElementType() ||
476             (T->isAbstract() &&
477              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
478            "Initializer for array element doesn't match array element type!");
479     *OL = C;
480   }
481 }
482
483 Constant *ConstantArray::get(const ArrayType *Ty, 
484                              const std::vector<Constant*> &V) {
485   for (unsigned i = 0, e = V.size(); i != e; ++i) {
486     assert(V[i]->getType() == Ty->getElementType() &&
487            "Wrong type in array element initializer");
488   }
489   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
490   // If this is an all-zero array, return a ConstantAggregateZero object
491   if (!V.empty()) {
492     Constant *C = V[0];
493     if (!C->isNullValue()) {
494       // Implicitly locked.
495       return pImpl->ArrayConstants.getOrCreate(Ty, V);
496     }
497     for (unsigned i = 1, e = V.size(); i != e; ++i)
498       if (V[i] != C) {
499         // Implicitly locked.
500         return pImpl->ArrayConstants.getOrCreate(Ty, V);
501       }
502   }
503   
504   return ConstantAggregateZero::get(Ty);
505 }
506
507
508 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
509                              unsigned NumVals) {
510   // FIXME: make this the primary ctor method.
511   return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
512 }
513
514 /// ConstantArray::get(const string&) - Return an array that is initialized to
515 /// contain the specified string.  If length is zero then a null terminator is 
516 /// added to the specified string so that it may be used in a natural way. 
517 /// Otherwise, the length parameter specifies how much of the string to use 
518 /// and it won't be null terminated.
519 ///
520 Constant* ConstantArray::get(LLVMContext &Context, const StringRef &Str,
521                              bool AddNull) {
522   std::vector<Constant*> ElementVals;
523   for (unsigned i = 0; i < Str.size(); ++i)
524     ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
525
526   // Add a null terminator to the string...
527   if (AddNull) {
528     ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
529   }
530
531   ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
532   return get(ATy, ElementVals);
533 }
534
535
536
537 ConstantStruct::ConstantStruct(const StructType *T,
538                                const std::vector<Constant*> &V)
539   : Constant(T, ConstantStructVal,
540              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
541              V.size()) {
542   assert(V.size() == T->getNumElements() &&
543          "Invalid initializer vector for constant structure");
544   Use *OL = OperandList;
545   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
546        I != E; ++I, ++OL) {
547     Constant *C = *I;
548     assert((C->getType() == T->getElementType(I-V.begin()) ||
549             ((T->getElementType(I-V.begin())->isAbstract() ||
550               C->getType()->isAbstract()) &&
551              T->getElementType(I-V.begin())->getTypeID() == 
552                    C->getType()->getTypeID())) &&
553            "Initializer for struct element doesn't match struct element type!");
554     *OL = C;
555   }
556 }
557
558 // ConstantStruct accessors.
559 Constant* ConstantStruct::get(const StructType* T,
560                               const std::vector<Constant*>& V) {
561   LLVMContextImpl* pImpl = T->getContext().pImpl;
562   
563   // Create a ConstantAggregateZero value if all elements are zeros...
564   for (unsigned i = 0, e = V.size(); i != e; ++i)
565     if (!V[i]->isNullValue())
566       // Implicitly locked.
567       return pImpl->StructConstants.getOrCreate(T, V);
568
569   return ConstantAggregateZero::get(T);
570 }
571
572 Constant* ConstantStruct::get(LLVMContext &Context,
573                               const std::vector<Constant*>& V, bool packed) {
574   std::vector<const Type*> StructEls;
575   StructEls.reserve(V.size());
576   for (unsigned i = 0, e = V.size(); i != e; ++i)
577     StructEls.push_back(V[i]->getType());
578   return get(StructType::get(Context, StructEls, packed), V);
579 }
580
581 Constant* ConstantStruct::get(LLVMContext &Context,
582                               Constant* const *Vals, unsigned NumVals,
583                               bool Packed) {
584   // FIXME: make this the primary ctor method.
585   return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
586 }
587
588 ConstantVector::ConstantVector(const VectorType *T,
589                                const std::vector<Constant*> &V)
590   : Constant(T, ConstantVectorVal,
591              OperandTraits<ConstantVector>::op_end(this) - V.size(),
592              V.size()) {
593   Use *OL = OperandList;
594     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
595          I != E; ++I, ++OL) {
596       Constant *C = *I;
597       assert((C->getType() == T->getElementType() ||
598             (T->isAbstract() &&
599              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
600            "Initializer for vector element doesn't match vector element type!");
601     *OL = C;
602   }
603 }
604
605 // ConstantVector accessors.
606 Constant* ConstantVector::get(const VectorType* T,
607                               const std::vector<Constant*>& V) {
608    assert(!V.empty() && "Vectors can't be empty");
609    LLVMContext &Context = T->getContext();
610    LLVMContextImpl *pImpl = Context.pImpl;
611    
612   // If this is an all-undef or alll-zero vector, return a
613   // ConstantAggregateZero or UndefValue.
614   Constant *C = V[0];
615   bool isZero = C->isNullValue();
616   bool isUndef = isa<UndefValue>(C);
617
618   if (isZero || isUndef) {
619     for (unsigned i = 1, e = V.size(); i != e; ++i)
620       if (V[i] != C) {
621         isZero = isUndef = false;
622         break;
623       }
624   }
625   
626   if (isZero)
627     return ConstantAggregateZero::get(T);
628   if (isUndef)
629     return UndefValue::get(T);
630     
631   // Implicitly locked.
632   return pImpl->VectorConstants.getOrCreate(T, V);
633 }
634
635 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
636   assert(!V.empty() && "Cannot infer type if V is empty");
637   return get(VectorType::get(V.front()->getType(),V.size()), V);
638 }
639
640 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
641   // FIXME: make this the primary ctor method.
642   return get(std::vector<Constant*>(Vals, Vals+NumVals));
643 }
644
645 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
646   return getTy(C1->getType(), Instruction::Add, C1, C2,
647                OverflowingBinaryOperator::NoSignedWrap);
648 }
649
650 Constant* ConstantExpr::getNSWSub(Constant* C1, Constant* C2) {
651   return getTy(C1->getType(), Instruction::Sub, C1, C2,
652                OverflowingBinaryOperator::NoSignedWrap);
653 }
654
655 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
656   return getTy(C1->getType(), Instruction::SDiv, C1, C2,
657                SDivOperator::IsExact);
658 }
659
660 // Utility function for determining if a ConstantExpr is a CastOp or not. This
661 // can't be inline because we don't want to #include Instruction.h into
662 // Constant.h
663 bool ConstantExpr::isCast() const {
664   return Instruction::isCast(getOpcode());
665 }
666
667 bool ConstantExpr::isCompare() const {
668   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
669 }
670
671 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
672   if (getOpcode() != Instruction::GetElementPtr) return false;
673
674   gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
675   User::const_op_iterator OI = next(this->op_begin());
676
677   // Skip the first index, as it has no static limit.
678   ++GEPI;
679   ++OI;
680
681   // The remaining indices must be compile-time known integers within the
682   // bounds of the corresponding notional static array types.
683   for (; GEPI != E; ++GEPI, ++OI) {
684     ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
685     if (!CI) return false;
686     if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
687       if (CI->getValue().getActiveBits() > 64 ||
688           CI->getZExtValue() >= ATy->getNumElements())
689         return false;
690   }
691
692   // All the indices checked out.
693   return true;
694 }
695
696 bool ConstantExpr::hasIndices() const {
697   return getOpcode() == Instruction::ExtractValue ||
698          getOpcode() == Instruction::InsertValue;
699 }
700
701 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
702   if (const ExtractValueConstantExpr *EVCE =
703         dyn_cast<ExtractValueConstantExpr>(this))
704     return EVCE->Indices;
705
706   return cast<InsertValueConstantExpr>(this)->Indices;
707 }
708
709 unsigned ConstantExpr::getPredicate() const {
710   assert(getOpcode() == Instruction::FCmp || 
711          getOpcode() == Instruction::ICmp);
712   return ((const CompareConstantExpr*)this)->predicate;
713 }
714
715 /// getWithOperandReplaced - Return a constant expression identical to this
716 /// one, but with the specified operand set to the specified value.
717 Constant *
718 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
719   assert(OpNo < getNumOperands() && "Operand num is out of range!");
720   assert(Op->getType() == getOperand(OpNo)->getType() &&
721          "Replacing operand with value of different type!");
722   if (getOperand(OpNo) == Op)
723     return const_cast<ConstantExpr*>(this);
724   
725   Constant *Op0, *Op1, *Op2;
726   switch (getOpcode()) {
727   case Instruction::Trunc:
728   case Instruction::ZExt:
729   case Instruction::SExt:
730   case Instruction::FPTrunc:
731   case Instruction::FPExt:
732   case Instruction::UIToFP:
733   case Instruction::SIToFP:
734   case Instruction::FPToUI:
735   case Instruction::FPToSI:
736   case Instruction::PtrToInt:
737   case Instruction::IntToPtr:
738   case Instruction::BitCast:
739     return ConstantExpr::getCast(getOpcode(), Op, getType());
740   case Instruction::Select:
741     Op0 = (OpNo == 0) ? Op : getOperand(0);
742     Op1 = (OpNo == 1) ? Op : getOperand(1);
743     Op2 = (OpNo == 2) ? Op : getOperand(2);
744     return ConstantExpr::getSelect(Op0, Op1, Op2);
745   case Instruction::InsertElement:
746     Op0 = (OpNo == 0) ? Op : getOperand(0);
747     Op1 = (OpNo == 1) ? Op : getOperand(1);
748     Op2 = (OpNo == 2) ? Op : getOperand(2);
749     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
750   case Instruction::ExtractElement:
751     Op0 = (OpNo == 0) ? Op : getOperand(0);
752     Op1 = (OpNo == 1) ? Op : getOperand(1);
753     return ConstantExpr::getExtractElement(Op0, Op1);
754   case Instruction::ShuffleVector:
755     Op0 = (OpNo == 0) ? Op : getOperand(0);
756     Op1 = (OpNo == 1) ? Op : getOperand(1);
757     Op2 = (OpNo == 2) ? Op : getOperand(2);
758     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
759   case Instruction::GetElementPtr: {
760     SmallVector<Constant*, 8> Ops;
761     Ops.resize(getNumOperands()-1);
762     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
763       Ops[i-1] = getOperand(i);
764     if (OpNo == 0)
765       return cast<GEPOperator>(this)->isInBounds() ?
766         ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
767         ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
768     Ops[OpNo-1] = Op;
769     return cast<GEPOperator>(this)->isInBounds() ?
770       ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0], Ops.size()) :
771       ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
772   }
773   default:
774     assert(getNumOperands() == 2 && "Must be binary operator?");
775     Op0 = (OpNo == 0) ? Op : getOperand(0);
776     Op1 = (OpNo == 1) ? Op : getOperand(1);
777     return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassData);
778   }
779 }
780
781 /// getWithOperands - This returns the current constant expression with the
782 /// operands replaced with the specified values.  The specified operands must
783 /// match count and type with the existing ones.
784 Constant *ConstantExpr::
785 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
786   assert(NumOps == getNumOperands() && "Operand count mismatch!");
787   bool AnyChange = false;
788   for (unsigned i = 0; i != NumOps; ++i) {
789     assert(Ops[i]->getType() == getOperand(i)->getType() &&
790            "Operand type mismatch!");
791     AnyChange |= Ops[i] != getOperand(i);
792   }
793   if (!AnyChange)  // No operands changed, return self.
794     return const_cast<ConstantExpr*>(this);
795
796   switch (getOpcode()) {
797   case Instruction::Trunc:
798   case Instruction::ZExt:
799   case Instruction::SExt:
800   case Instruction::FPTrunc:
801   case Instruction::FPExt:
802   case Instruction::UIToFP:
803   case Instruction::SIToFP:
804   case Instruction::FPToUI:
805   case Instruction::FPToSI:
806   case Instruction::PtrToInt:
807   case Instruction::IntToPtr:
808   case Instruction::BitCast:
809     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
810   case Instruction::Select:
811     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
812   case Instruction::InsertElement:
813     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
814   case Instruction::ExtractElement:
815     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
816   case Instruction::ShuffleVector:
817     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
818   case Instruction::GetElementPtr:
819     return cast<GEPOperator>(this)->isInBounds() ?
820       ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
821       ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
822   case Instruction::ICmp:
823   case Instruction::FCmp:
824     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
825   default:
826     assert(getNumOperands() == 2 && "Must be binary operator?");
827     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassData);
828   }
829 }
830
831
832 //===----------------------------------------------------------------------===//
833 //                      isValueValidForType implementations
834
835 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
836   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
837   if (Ty == Type::getInt1Ty(Ty->getContext()))
838     return Val == 0 || Val == 1;
839   if (NumBits >= 64)
840     return true; // always true, has to fit in largest type
841   uint64_t Max = (1ll << NumBits) - 1;
842   return Val <= Max;
843 }
844
845 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
846   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
847   if (Ty == Type::getInt1Ty(Ty->getContext()))
848     return Val == 0 || Val == 1 || Val == -1;
849   if (NumBits >= 64)
850     return true; // always true, has to fit in largest type
851   int64_t Min = -(1ll << (NumBits-1));
852   int64_t Max = (1ll << (NumBits-1)) - 1;
853   return (Val >= Min && Val <= Max);
854 }
855
856 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
857   // convert modifies in place, so make a copy.
858   APFloat Val2 = APFloat(Val);
859   bool losesInfo;
860   switch (Ty->getTypeID()) {
861   default:
862     return false;         // These can't be represented as floating point!
863
864   // FIXME rounding mode needs to be more flexible
865   case Type::FloatTyID: {
866     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
867       return true;
868     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
869     return !losesInfo;
870   }
871   case Type::DoubleTyID: {
872     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
873         &Val2.getSemantics() == &APFloat::IEEEdouble)
874       return true;
875     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
876     return !losesInfo;
877   }
878   case Type::X86_FP80TyID:
879     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
880            &Val2.getSemantics() == &APFloat::IEEEdouble ||
881            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
882   case Type::FP128TyID:
883     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
884            &Val2.getSemantics() == &APFloat::IEEEdouble ||
885            &Val2.getSemantics() == &APFloat::IEEEquad;
886   case Type::PPC_FP128TyID:
887     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
888            &Val2.getSemantics() == &APFloat::IEEEdouble ||
889            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
890   }
891 }
892
893 //===----------------------------------------------------------------------===//
894 //                      Factory Function Implementation
895
896 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
897   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
898          "Cannot create an aggregate zero of non-aggregate type!");
899   
900   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
901   // Implicitly locked.
902   return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
903 }
904
905 /// destroyConstant - Remove the constant from the constant table...
906 ///
907 void ConstantAggregateZero::destroyConstant() {
908   // Implicitly locked.
909   getType()->getContext().pImpl->AggZeroConstants.remove(this);
910   destroyConstantImpl();
911 }
912
913 /// destroyConstant - Remove the constant from the constant table...
914 ///
915 void ConstantArray::destroyConstant() {
916   // Implicitly locked.
917   getType()->getContext().pImpl->ArrayConstants.remove(this);
918   destroyConstantImpl();
919 }
920
921 /// isString - This method returns true if the array is an array of i8, and 
922 /// if the elements of the array are all ConstantInt's.
923 bool ConstantArray::isString() const {
924   // Check the element type for i8...
925   if (getType()->getElementType() != Type::getInt8Ty(getContext()))
926     return false;
927   // Check the elements to make sure they are all integers, not constant
928   // expressions.
929   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
930     if (!isa<ConstantInt>(getOperand(i)))
931       return false;
932   return true;
933 }
934
935 /// isCString - This method returns true if the array is a string (see
936 /// isString) and it ends in a null byte \\0 and does not contains any other
937 /// null bytes except its terminator.
938 bool ConstantArray::isCString() const {
939   // Check the element type for i8...
940   if (getType()->getElementType() != Type::getInt8Ty(getContext()))
941     return false;
942
943   // Last element must be a null.
944   if (!getOperand(getNumOperands()-1)->isNullValue())
945     return false;
946   // Other elements must be non-null integers.
947   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
948     if (!isa<ConstantInt>(getOperand(i)))
949       return false;
950     if (getOperand(i)->isNullValue())
951       return false;
952   }
953   return true;
954 }
955
956
957 /// getAsString - If the sub-element type of this array is i8
958 /// then this method converts the array to an std::string and returns it.
959 /// Otherwise, it asserts out.
960 ///
961 std::string ConstantArray::getAsString() const {
962   assert(isString() && "Not a string!");
963   std::string Result;
964   Result.reserve(getNumOperands());
965   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
966     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
967   return Result;
968 }
969
970
971 //---- ConstantStruct::get() implementation...
972 //
973
974 namespace llvm {
975
976 }
977
978 // destroyConstant - Remove the constant from the constant table...
979 //
980 void ConstantStruct::destroyConstant() {
981   // Implicitly locked.
982   getType()->getContext().pImpl->StructConstants.remove(this);
983   destroyConstantImpl();
984 }
985
986 // destroyConstant - Remove the constant from the constant table...
987 //
988 void ConstantVector::destroyConstant() {
989   // Implicitly locked.
990   getType()->getContext().pImpl->VectorConstants.remove(this);
991   destroyConstantImpl();
992 }
993
994 /// This function will return true iff every element in this vector constant
995 /// is set to all ones.
996 /// @returns true iff this constant's emements are all set to all ones.
997 /// @brief Determine if the value is all ones.
998 bool ConstantVector::isAllOnesValue() const {
999   // Check out first element.
1000   const Constant *Elt = getOperand(0);
1001   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1002   if (!CI || !CI->isAllOnesValue()) return false;
1003   // Then make sure all remaining elements point to the same value.
1004   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1005     if (getOperand(I) != Elt) return false;
1006   }
1007   return true;
1008 }
1009
1010 /// getSplatValue - If this is a splat constant, where all of the
1011 /// elements have the same value, return that value. Otherwise return null.
1012 Constant *ConstantVector::getSplatValue() {
1013   // Check out first element.
1014   Constant *Elt = getOperand(0);
1015   // Then make sure all remaining elements point to the same value.
1016   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1017     if (getOperand(I) != Elt) return 0;
1018   return Elt;
1019 }
1020
1021 //---- ConstantPointerNull::get() implementation...
1022 //
1023
1024 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1025   // Implicitly locked.
1026   return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1027 }
1028
1029 // destroyConstant - Remove the constant from the constant table...
1030 //
1031 void ConstantPointerNull::destroyConstant() {
1032   // Implicitly locked.
1033   getType()->getContext().pImpl->NullPtrConstants.remove(this);
1034   destroyConstantImpl();
1035 }
1036
1037
1038 //---- UndefValue::get() implementation...
1039 //
1040
1041 UndefValue *UndefValue::get(const Type *Ty) {
1042   // Implicitly locked.
1043   return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1044 }
1045
1046 // destroyConstant - Remove the constant from the constant table.
1047 //
1048 void UndefValue::destroyConstant() {
1049   // Implicitly locked.
1050   getType()->getContext().pImpl->UndefValueConstants.remove(this);
1051   destroyConstantImpl();
1052 }
1053
1054 //---- ConstantExpr::get() implementations...
1055 //
1056
1057 /// This is a utility function to handle folding of casts and lookup of the
1058 /// cast in the ExprConstants map. It is used by the various get* methods below.
1059 static inline Constant *getFoldedCast(
1060   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1061   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1062   // Fold a few common cases
1063   if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1064     return FC;
1065
1066   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1067
1068   // Look up the constant in the table first to ensure uniqueness
1069   std::vector<Constant*> argVec(1, C);
1070   ExprMapKeyType Key(opc, argVec);
1071   
1072   // Implicitly locked.
1073   return pImpl->ExprConstants.getOrCreate(Ty, Key);
1074 }
1075  
1076 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1077   Instruction::CastOps opc = Instruction::CastOps(oc);
1078   assert(Instruction::isCast(opc) && "opcode out of range");
1079   assert(C && Ty && "Null arguments to getCast");
1080   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1081
1082   switch (opc) {
1083     default:
1084       llvm_unreachable("Invalid cast opcode");
1085       break;
1086     case Instruction::Trunc:    return getTrunc(C, Ty);
1087     case Instruction::ZExt:     return getZExt(C, Ty);
1088     case Instruction::SExt:     return getSExt(C, Ty);
1089     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1090     case Instruction::FPExt:    return getFPExtend(C, Ty);
1091     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1092     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1093     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1094     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1095     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1096     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1097     case Instruction::BitCast:  return getBitCast(C, Ty);
1098   }
1099   return 0;
1100
1101
1102 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1103   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1104     return getCast(Instruction::BitCast, C, Ty);
1105   return getCast(Instruction::ZExt, C, Ty);
1106 }
1107
1108 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1109   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1110     return getCast(Instruction::BitCast, C, Ty);
1111   return getCast(Instruction::SExt, C, Ty);
1112 }
1113
1114 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1115   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1116     return getCast(Instruction::BitCast, C, Ty);
1117   return getCast(Instruction::Trunc, C, Ty);
1118 }
1119
1120 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1121   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1122   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1123
1124   if (Ty->isInteger())
1125     return getCast(Instruction::PtrToInt, S, Ty);
1126   return getCast(Instruction::BitCast, S, Ty);
1127 }
1128
1129 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1130                                        bool isSigned) {
1131   assert(C->getType()->isIntOrIntVector() &&
1132          Ty->isIntOrIntVector() && "Invalid cast");
1133   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1134   unsigned DstBits = Ty->getScalarSizeInBits();
1135   Instruction::CastOps opcode =
1136     (SrcBits == DstBits ? Instruction::BitCast :
1137      (SrcBits > DstBits ? Instruction::Trunc :
1138       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1139   return getCast(opcode, C, Ty);
1140 }
1141
1142 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1143   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1144          "Invalid cast");
1145   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1146   unsigned DstBits = Ty->getScalarSizeInBits();
1147   if (SrcBits == DstBits)
1148     return C; // Avoid a useless cast
1149   Instruction::CastOps opcode =
1150      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1151   return getCast(opcode, C, Ty);
1152 }
1153
1154 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1155 #ifndef NDEBUG
1156   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1157   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1158 #endif
1159   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1160   assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1161   assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1162   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1163          "SrcTy must be larger than DestTy for Trunc!");
1164
1165   return getFoldedCast(Instruction::Trunc, C, Ty);
1166 }
1167
1168 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1169 #ifndef NDEBUG
1170   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1171   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1172 #endif
1173   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1174   assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1175   assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1176   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1177          "SrcTy must be smaller than DestTy for SExt!");
1178
1179   return getFoldedCast(Instruction::SExt, C, Ty);
1180 }
1181
1182 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1183 #ifndef NDEBUG
1184   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1185   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1186 #endif
1187   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1188   assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1189   assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1190   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1191          "SrcTy must be smaller than DestTy for ZExt!");
1192
1193   return getFoldedCast(Instruction::ZExt, C, Ty);
1194 }
1195
1196 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1197 #ifndef NDEBUG
1198   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1199   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1200 #endif
1201   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1202   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1203          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1204          "This is an illegal floating point truncation!");
1205   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1206 }
1207
1208 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1209 #ifndef NDEBUG
1210   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1211   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1212 #endif
1213   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1214   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1215          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1216          "This is an illegal floating point extension!");
1217   return getFoldedCast(Instruction::FPExt, C, Ty);
1218 }
1219
1220 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1221 #ifndef NDEBUG
1222   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1223   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1224 #endif
1225   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1226   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1227          "This is an illegal uint to floating point cast!");
1228   return getFoldedCast(Instruction::UIToFP, C, Ty);
1229 }
1230
1231 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1232 #ifndef NDEBUG
1233   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1234   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1235 #endif
1236   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1237   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1238          "This is an illegal sint to floating point cast!");
1239   return getFoldedCast(Instruction::SIToFP, C, Ty);
1240 }
1241
1242 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1243 #ifndef NDEBUG
1244   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1245   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1246 #endif
1247   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1248   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1249          "This is an illegal floating point to uint cast!");
1250   return getFoldedCast(Instruction::FPToUI, C, Ty);
1251 }
1252
1253 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1254 #ifndef NDEBUG
1255   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1256   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1257 #endif
1258   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1259   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1260          "This is an illegal floating point to sint cast!");
1261   return getFoldedCast(Instruction::FPToSI, C, Ty);
1262 }
1263
1264 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1265   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1266   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1267   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1268 }
1269
1270 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1271   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1272   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1273   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1274 }
1275
1276 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1277   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1278   // can't cast pointers to anything but pointers.
1279 #ifndef NDEBUG
1280   const Type *SrcTy = C->getType();
1281   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1282          "BitCast cannot cast pointer to non-pointer and vice versa");
1283
1284   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1285   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1286   // destination bit widths are identical.
1287   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1288   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1289 #endif
1290   assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1291   
1292   // It is common to ask for a bitcast of a value to its own type, handle this
1293   // speedily.
1294   if (C->getType() == DstTy) return C;
1295   
1296   return getFoldedCast(Instruction::BitCast, C, DstTy);
1297 }
1298
1299 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1300                               Constant *C1, Constant *C2,
1301                               unsigned Flags) {
1302   // Check the operands for consistency first
1303   assert(Opcode >= Instruction::BinaryOpsBegin &&
1304          Opcode <  Instruction::BinaryOpsEnd   &&
1305          "Invalid opcode in binary constant expression");
1306   assert(C1->getType() == C2->getType() &&
1307          "Operand types in binary constant expression should match");
1308
1309   if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1310     if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1311                                                      Opcode, C1, C2))
1312       return FC;          // Fold a few common cases...
1313
1314   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1315   ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1316   
1317   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1318   
1319   // Implicitly locked.
1320   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1321 }
1322
1323 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1324                                      Constant *C1, Constant *C2) {
1325   switch (predicate) {
1326     default: llvm_unreachable("Invalid CmpInst predicate");
1327     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1328     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1329     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1330     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1331     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1332     case CmpInst::FCMP_TRUE:
1333       return getFCmp(predicate, C1, C2);
1334
1335     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1336     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1337     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1338     case CmpInst::ICMP_SLE:
1339       return getICmp(predicate, C1, C2);
1340   }
1341 }
1342
1343 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1344                             unsigned Flags) {
1345   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1346   if (C1->getType()->isFPOrFPVector()) {
1347     if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1348     else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1349     else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1350   }
1351 #ifndef NDEBUG
1352   switch (Opcode) {
1353   case Instruction::Add:
1354   case Instruction::Sub:
1355   case Instruction::Mul:
1356     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1357     assert(C1->getType()->isIntOrIntVector() &&
1358            "Tried to create an integer operation on a non-integer type!");
1359     break;
1360   case Instruction::FAdd:
1361   case Instruction::FSub:
1362   case Instruction::FMul:
1363     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1364     assert(C1->getType()->isFPOrFPVector() &&
1365            "Tried to create a floating-point operation on a "
1366            "non-floating-point type!");
1367     break;
1368   case Instruction::UDiv: 
1369   case Instruction::SDiv: 
1370     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1371     assert(C1->getType()->isIntOrIntVector() &&
1372            "Tried to create an arithmetic operation on a non-arithmetic type!");
1373     break;
1374   case Instruction::FDiv:
1375     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1376     assert(C1->getType()->isFPOrFPVector() &&
1377            "Tried to create an arithmetic operation on a non-arithmetic type!");
1378     break;
1379   case Instruction::URem: 
1380   case Instruction::SRem: 
1381     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1382     assert(C1->getType()->isIntOrIntVector() &&
1383            "Tried to create an arithmetic operation on a non-arithmetic type!");
1384     break;
1385   case Instruction::FRem:
1386     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1387     assert(C1->getType()->isFPOrFPVector() &&
1388            "Tried to create an arithmetic operation on a non-arithmetic type!");
1389     break;
1390   case Instruction::And:
1391   case Instruction::Or:
1392   case Instruction::Xor:
1393     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1394     assert(C1->getType()->isIntOrIntVector() &&
1395            "Tried to create a logical operation on a non-integral type!");
1396     break;
1397   case Instruction::Shl:
1398   case Instruction::LShr:
1399   case Instruction::AShr:
1400     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1401     assert(C1->getType()->isIntOrIntVector() &&
1402            "Tried to create a shift operation on a non-integer type!");
1403     break;
1404   default:
1405     break;
1406   }
1407 #endif
1408
1409   return getTy(C1->getType(), Opcode, C1, C2, Flags);
1410 }
1411
1412 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1413   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1414   // Note that a non-inbounds gep is used, as null isn't within any object.
1415   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1416   Constant *GEP = getGetElementPtr(
1417                  Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1418   return getCast(Instruction::PtrToInt, GEP, 
1419                  Type::getInt64Ty(Ty->getContext()));
1420 }
1421
1422 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1423   // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1424   // Note that a non-inbounds gep is used, as null isn't within any object.
1425   const Type *AligningTy = StructType::get(Ty->getContext(),
1426                                    Type::getInt8Ty(Ty->getContext()), Ty, NULL);
1427   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1428   Constant *Zero = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 0);
1429   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1430   Constant *Indices[2] = { Zero, One };
1431   Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1432   return getCast(Instruction::PtrToInt, GEP,
1433                  Type::getInt32Ty(Ty->getContext()));
1434 }
1435
1436 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1437   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1438   // Note that a non-inbounds gep is used, as null isn't within any object.
1439   Constant *GEPIdx[] = {
1440     ConstantInt::get(Type::getInt64Ty(STy->getContext()), 0),
1441     ConstantInt::get(Type::getInt32Ty(STy->getContext()), FieldNo)
1442   };
1443   Constant *GEP = getGetElementPtr(
1444                 Constant::getNullValue(PointerType::getUnqual(STy)), GEPIdx, 2);
1445   return getCast(Instruction::PtrToInt, GEP,
1446                  Type::getInt64Ty(STy->getContext()));
1447 }
1448
1449 Constant *ConstantExpr::getCompare(unsigned short pred, 
1450                             Constant *C1, Constant *C2) {
1451   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1452   return getCompareTy(pred, C1, C2);
1453 }
1454
1455 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1456                                     Constant *V1, Constant *V2) {
1457   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1458
1459   if (ReqTy == V1->getType())
1460     if (Constant *SC = ConstantFoldSelectInstruction(
1461                                                 ReqTy->getContext(), C, V1, V2))
1462       return SC;        // Fold common cases
1463
1464   std::vector<Constant*> argVec(3, C);
1465   argVec[1] = V1;
1466   argVec[2] = V2;
1467   ExprMapKeyType Key(Instruction::Select, argVec);
1468   
1469   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1470   
1471   // Implicitly locked.
1472   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1473 }
1474
1475 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1476                                            Value* const *Idxs,
1477                                            unsigned NumIdx) {
1478   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1479                                            Idxs+NumIdx) ==
1480          cast<PointerType>(ReqTy)->getElementType() &&
1481          "GEP indices invalid!");
1482
1483   if (Constant *FC = ConstantFoldGetElementPtr(
1484                               ReqTy->getContext(), C, /*inBounds=*/false,
1485                               (Constant**)Idxs, NumIdx))
1486     return FC;          // Fold a few common cases...
1487
1488   assert(isa<PointerType>(C->getType()) &&
1489          "Non-pointer type for constant GetElementPtr expression");
1490   // Look up the constant in the table first to ensure uniqueness
1491   std::vector<Constant*> ArgVec;
1492   ArgVec.reserve(NumIdx+1);
1493   ArgVec.push_back(C);
1494   for (unsigned i = 0; i != NumIdx; ++i)
1495     ArgVec.push_back(cast<Constant>(Idxs[i]));
1496   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1497
1498   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1499
1500   // Implicitly locked.
1501   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1502 }
1503
1504 Constant *ConstantExpr::getInBoundsGetElementPtrTy(const Type *ReqTy,
1505                                                    Constant *C,
1506                                                    Value* const *Idxs,
1507                                                    unsigned NumIdx) {
1508   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1509                                            Idxs+NumIdx) ==
1510          cast<PointerType>(ReqTy)->getElementType() &&
1511          "GEP indices invalid!");
1512
1513   if (Constant *FC = ConstantFoldGetElementPtr(
1514                               ReqTy->getContext(), C, /*inBounds=*/true,
1515                               (Constant**)Idxs, NumIdx))
1516     return FC;          // Fold a few common cases...
1517
1518   assert(isa<PointerType>(C->getType()) &&
1519          "Non-pointer type for constant GetElementPtr expression");
1520   // Look up the constant in the table first to ensure uniqueness
1521   std::vector<Constant*> ArgVec;
1522   ArgVec.reserve(NumIdx+1);
1523   ArgVec.push_back(C);
1524   for (unsigned i = 0; i != NumIdx; ++i)
1525     ArgVec.push_back(cast<Constant>(Idxs[i]));
1526   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1527                            GEPOperator::IsInBounds);
1528
1529   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1530
1531   // Implicitly locked.
1532   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1533 }
1534
1535 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1536                                          unsigned NumIdx) {
1537   // Get the result type of the getelementptr!
1538   const Type *Ty = 
1539     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1540   assert(Ty && "GEP indices invalid!");
1541   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1542   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1543 }
1544
1545 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1546                                                  Value* const *Idxs,
1547                                                  unsigned NumIdx) {
1548   // Get the result type of the getelementptr!
1549   const Type *Ty = 
1550     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1551   assert(Ty && "GEP indices invalid!");
1552   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1553   return getInBoundsGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1554 }
1555
1556 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1557                                          unsigned NumIdx) {
1558   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1559 }
1560
1561 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1562                                                  Constant* const *Idxs,
1563                                                  unsigned NumIdx) {
1564   return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1565 }
1566
1567 Constant *
1568 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1569   assert(LHS->getType() == RHS->getType());
1570   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1571          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1572
1573   if (Constant *FC = ConstantFoldCompareInstruction(
1574                                              LHS->getContext(), pred, LHS, RHS))
1575     return FC;          // Fold a few common cases...
1576
1577   // Look up the constant in the table first to ensure uniqueness
1578   std::vector<Constant*> ArgVec;
1579   ArgVec.push_back(LHS);
1580   ArgVec.push_back(RHS);
1581   // Get the key type with both the opcode and predicate
1582   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1583
1584   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1585
1586   // Implicitly locked.
1587   return
1588       pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1589 }
1590
1591 Constant *
1592 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1593   assert(LHS->getType() == RHS->getType());
1594   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1595
1596   if (Constant *FC = ConstantFoldCompareInstruction(
1597                                             LHS->getContext(), pred, LHS, RHS))
1598     return FC;          // Fold a few common cases...
1599
1600   // Look up the constant in the table first to ensure uniqueness
1601   std::vector<Constant*> ArgVec;
1602   ArgVec.push_back(LHS);
1603   ArgVec.push_back(RHS);
1604   // Get the key type with both the opcode and predicate
1605   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1606   
1607   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1608   
1609   // Implicitly locked.
1610   return
1611       pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1612 }
1613
1614 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1615                                             Constant *Idx) {
1616   if (Constant *FC = ConstantFoldExtractElementInstruction(
1617                                                 ReqTy->getContext(), Val, Idx))
1618     return FC;          // Fold a few common cases...
1619   // Look up the constant in the table first to ensure uniqueness
1620   std::vector<Constant*> ArgVec(1, Val);
1621   ArgVec.push_back(Idx);
1622   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1623   
1624   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1625   
1626   // Implicitly locked.
1627   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1628 }
1629
1630 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1631   assert(isa<VectorType>(Val->getType()) &&
1632          "Tried to create extractelement operation on non-vector type!");
1633   assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1634          "Extractelement index must be i32 type!");
1635   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1636                              Val, Idx);
1637 }
1638
1639 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1640                                            Constant *Elt, Constant *Idx) {
1641   if (Constant *FC = ConstantFoldInsertElementInstruction(
1642                                             ReqTy->getContext(), Val, Elt, Idx))
1643     return FC;          // Fold a few common cases...
1644   // Look up the constant in the table first to ensure uniqueness
1645   std::vector<Constant*> ArgVec(1, Val);
1646   ArgVec.push_back(Elt);
1647   ArgVec.push_back(Idx);
1648   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1649   
1650   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1651   
1652   // Implicitly locked.
1653   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1654 }
1655
1656 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1657                                          Constant *Idx) {
1658   assert(isa<VectorType>(Val->getType()) &&
1659          "Tried to create insertelement operation on non-vector type!");
1660   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1661          && "Insertelement types must match!");
1662   assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1663          "Insertelement index must be i32 type!");
1664   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1665 }
1666
1667 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1668                                            Constant *V2, Constant *Mask) {
1669   if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1670                                             ReqTy->getContext(), V1, V2, Mask))
1671     return FC;          // Fold a few common cases...
1672   // Look up the constant in the table first to ensure uniqueness
1673   std::vector<Constant*> ArgVec(1, V1);
1674   ArgVec.push_back(V2);
1675   ArgVec.push_back(Mask);
1676   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1677   
1678   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1679   
1680   // Implicitly locked.
1681   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1682 }
1683
1684 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1685                                          Constant *Mask) {
1686   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1687          "Invalid shuffle vector constant expr operands!");
1688
1689   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1690   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1691   const Type *ShufTy = VectorType::get(EltTy, NElts);
1692   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1693 }
1694
1695 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1696                                          Constant *Val,
1697                                         const unsigned *Idxs, unsigned NumIdx) {
1698   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1699                                           Idxs+NumIdx) == Val->getType() &&
1700          "insertvalue indices invalid!");
1701   assert(Agg->getType() == ReqTy &&
1702          "insertvalue type invalid!");
1703   assert(Agg->getType()->isFirstClassType() &&
1704          "Non-first-class type for constant InsertValue expression");
1705   Constant *FC = ConstantFoldInsertValueInstruction(
1706                                   ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1707   assert(FC && "InsertValue constant expr couldn't be folded!");
1708   return FC;
1709 }
1710
1711 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1712                                      const unsigned *IdxList, unsigned NumIdx) {
1713   assert(Agg->getType()->isFirstClassType() &&
1714          "Tried to create insertelement operation on non-first-class type!");
1715
1716   const Type *ReqTy = Agg->getType();
1717 #ifndef NDEBUG
1718   const Type *ValTy =
1719     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1720 #endif
1721   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1722   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1723 }
1724
1725 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1726                                         const unsigned *Idxs, unsigned NumIdx) {
1727   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1728                                           Idxs+NumIdx) == ReqTy &&
1729          "extractvalue indices invalid!");
1730   assert(Agg->getType()->isFirstClassType() &&
1731          "Non-first-class type for constant extractvalue expression");
1732   Constant *FC = ConstantFoldExtractValueInstruction(
1733                                         ReqTy->getContext(), Agg, Idxs, NumIdx);
1734   assert(FC && "ExtractValue constant expr couldn't be folded!");
1735   return FC;
1736 }
1737
1738 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1739                                      const unsigned *IdxList, unsigned NumIdx) {
1740   assert(Agg->getType()->isFirstClassType() &&
1741          "Tried to create extractelement operation on non-first-class type!");
1742
1743   const Type *ReqTy =
1744     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1745   assert(ReqTy && "extractvalue indices invalid!");
1746   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1747 }
1748
1749 Constant* ConstantExpr::getNeg(Constant* C) {
1750   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1751   if (C->getType()->isFPOrFPVector())
1752     return getFNeg(C);
1753   assert(C->getType()->isIntOrIntVector() &&
1754          "Cannot NEG a nonintegral value!");
1755   return get(Instruction::Sub,
1756              ConstantFP::getZeroValueForNegation(C->getType()),
1757              C);
1758 }
1759
1760 Constant* ConstantExpr::getFNeg(Constant* C) {
1761   assert(C->getType()->isFPOrFPVector() &&
1762          "Cannot FNEG a non-floating-point value!");
1763   return get(Instruction::FSub,
1764              ConstantFP::getZeroValueForNegation(C->getType()),
1765              C);
1766 }
1767
1768 Constant* ConstantExpr::getNot(Constant* C) {
1769   assert(C->getType()->isIntOrIntVector() &&
1770          "Cannot NOT a nonintegral value!");
1771   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1772 }
1773
1774 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1775   return get(Instruction::Add, C1, C2);
1776 }
1777
1778 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1779   return get(Instruction::FAdd, C1, C2);
1780 }
1781
1782 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1783   return get(Instruction::Sub, C1, C2);
1784 }
1785
1786 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1787   return get(Instruction::FSub, C1, C2);
1788 }
1789
1790 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1791   return get(Instruction::Mul, C1, C2);
1792 }
1793
1794 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1795   return get(Instruction::FMul, C1, C2);
1796 }
1797
1798 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1799   return get(Instruction::UDiv, C1, C2);
1800 }
1801
1802 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1803   return get(Instruction::SDiv, C1, C2);
1804 }
1805
1806 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1807   return get(Instruction::FDiv, C1, C2);
1808 }
1809
1810 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1811   return get(Instruction::URem, C1, C2);
1812 }
1813
1814 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1815   return get(Instruction::SRem, C1, C2);
1816 }
1817
1818 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1819   return get(Instruction::FRem, C1, C2);
1820 }
1821
1822 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1823   return get(Instruction::And, C1, C2);
1824 }
1825
1826 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1827   return get(Instruction::Or, C1, C2);
1828 }
1829
1830 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1831   return get(Instruction::Xor, C1, C2);
1832 }
1833
1834 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1835   return get(Instruction::Shl, C1, C2);
1836 }
1837
1838 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1839   return get(Instruction::LShr, C1, C2);
1840 }
1841
1842 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1843   return get(Instruction::AShr, C1, C2);
1844 }
1845
1846 // destroyConstant - Remove the constant from the constant table...
1847 //
1848 void ConstantExpr::destroyConstant() {
1849   // Implicitly locked.
1850   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1851   pImpl->ExprConstants.remove(this);
1852   destroyConstantImpl();
1853 }
1854
1855 const char *ConstantExpr::getOpcodeName() const {
1856   return Instruction::getOpcodeName(getOpcode());
1857 }
1858
1859 //===----------------------------------------------------------------------===//
1860 //                replaceUsesOfWithOnConstant implementations
1861
1862 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1863 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
1864 /// etc.
1865 ///
1866 /// Note that we intentionally replace all uses of From with To here.  Consider
1867 /// a large array that uses 'From' 1000 times.  By handling this case all here,
1868 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1869 /// single invocation handles all 1000 uses.  Handling them one at a time would
1870 /// work, but would be really slow because it would have to unique each updated
1871 /// array instance.
1872
1873 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1874                                                 Use *U) {
1875   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1876   Constant *ToC = cast<Constant>(To);
1877
1878   LLVMContext &Context = getType()->getContext();
1879   LLVMContextImpl *pImpl = Context.pImpl;
1880
1881   std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1882   Lookup.first.first = getType();
1883   Lookup.second = this;
1884
1885   std::vector<Constant*> &Values = Lookup.first.second;
1886   Values.reserve(getNumOperands());  // Build replacement array.
1887
1888   // Fill values with the modified operands of the constant array.  Also, 
1889   // compute whether this turns into an all-zeros array.
1890   bool isAllZeros = false;
1891   unsigned NumUpdated = 0;
1892   if (!ToC->isNullValue()) {
1893     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1894       Constant *Val = cast<Constant>(O->get());
1895       if (Val == From) {
1896         Val = ToC;
1897         ++NumUpdated;
1898       }
1899       Values.push_back(Val);
1900     }
1901   } else {
1902     isAllZeros = true;
1903     for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1904       Constant *Val = cast<Constant>(O->get());
1905       if (Val == From) {
1906         Val = ToC;
1907         ++NumUpdated;
1908       }
1909       Values.push_back(Val);
1910       if (isAllZeros) isAllZeros = Val->isNullValue();
1911     }
1912   }
1913   
1914   Constant *Replacement = 0;
1915   if (isAllZeros) {
1916     Replacement = ConstantAggregateZero::get(getType());
1917   } else {
1918     // Check to see if we have this array type already.
1919     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1920     bool Exists;
1921     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1922       pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1923     
1924     if (Exists) {
1925       Replacement = I->second;
1926     } else {
1927       // Okay, the new shape doesn't exist in the system yet.  Instead of
1928       // creating a new constant array, inserting it, replaceallusesof'ing the
1929       // old with the new, then deleting the old... just update the current one
1930       // in place!
1931       pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1932       
1933       // Update to the new value.  Optimize for the case when we have a single
1934       // operand that we're changing, but handle bulk updates efficiently.
1935       if (NumUpdated == 1) {
1936         unsigned OperandToUpdate = U - OperandList;
1937         assert(getOperand(OperandToUpdate) == From &&
1938                "ReplaceAllUsesWith broken!");
1939         setOperand(OperandToUpdate, ToC);
1940       } else {
1941         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1942           if (getOperand(i) == From)
1943             setOperand(i, ToC);
1944       }
1945       return;
1946     }
1947   }
1948  
1949   // Otherwise, I do need to replace this with an existing value.
1950   assert(Replacement != this && "I didn't contain From!");
1951   
1952   // Everyone using this now uses the replacement.
1953   uncheckedReplaceAllUsesWith(Replacement);
1954   
1955   // Delete the old constant!
1956   destroyConstant();
1957 }
1958
1959 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1960                                                  Use *U) {
1961   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1962   Constant *ToC = cast<Constant>(To);
1963
1964   unsigned OperandToUpdate = U-OperandList;
1965   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1966
1967   std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1968   Lookup.first.first = getType();
1969   Lookup.second = this;
1970   std::vector<Constant*> &Values = Lookup.first.second;
1971   Values.reserve(getNumOperands());  // Build replacement struct.
1972   
1973   
1974   // Fill values with the modified operands of the constant struct.  Also, 
1975   // compute whether this turns into an all-zeros struct.
1976   bool isAllZeros = false;
1977   if (!ToC->isNullValue()) {
1978     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1979       Values.push_back(cast<Constant>(O->get()));
1980   } else {
1981     isAllZeros = true;
1982     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1983       Constant *Val = cast<Constant>(O->get());
1984       Values.push_back(Val);
1985       if (isAllZeros) isAllZeros = Val->isNullValue();
1986     }
1987   }
1988   Values[OperandToUpdate] = ToC;
1989   
1990   LLVMContext &Context = getType()->getContext();
1991   LLVMContextImpl *pImpl = Context.pImpl;
1992   
1993   Constant *Replacement = 0;
1994   if (isAllZeros) {
1995     Replacement = ConstantAggregateZero::get(getType());
1996   } else {
1997     // Check to see if we have this array type already.
1998     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1999     bool Exists;
2000     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2001       pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2002     
2003     if (Exists) {
2004       Replacement = I->second;
2005     } else {
2006       // Okay, the new shape doesn't exist in the system yet.  Instead of
2007       // creating a new constant struct, inserting it, replaceallusesof'ing the
2008       // old with the new, then deleting the old... just update the current one
2009       // in place!
2010       pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2011       
2012       // Update to the new value.
2013       setOperand(OperandToUpdate, ToC);
2014       return;
2015     }
2016   }
2017   
2018   assert(Replacement != this && "I didn't contain From!");
2019   
2020   // Everyone using this now uses the replacement.
2021   uncheckedReplaceAllUsesWith(Replacement);
2022   
2023   // Delete the old constant!
2024   destroyConstant();
2025 }
2026
2027 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2028                                                  Use *U) {
2029   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2030   
2031   std::vector<Constant*> Values;
2032   Values.reserve(getNumOperands());  // Build replacement array...
2033   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2034     Constant *Val = getOperand(i);
2035     if (Val == From) Val = cast<Constant>(To);
2036     Values.push_back(Val);
2037   }
2038   
2039   Constant *Replacement = get(getType(), Values);
2040   assert(Replacement != this && "I didn't contain From!");
2041   
2042   // Everyone using this now uses the replacement.
2043   uncheckedReplaceAllUsesWith(Replacement);
2044   
2045   // Delete the old constant!
2046   destroyConstant();
2047 }
2048
2049 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2050                                                Use *U) {
2051   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2052   Constant *To = cast<Constant>(ToV);
2053   
2054   Constant *Replacement = 0;
2055   if (getOpcode() == Instruction::GetElementPtr) {
2056     SmallVector<Constant*, 8> Indices;
2057     Constant *Pointer = getOperand(0);
2058     Indices.reserve(getNumOperands()-1);
2059     if (Pointer == From) Pointer = To;
2060     
2061     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2062       Constant *Val = getOperand(i);
2063       if (Val == From) Val = To;
2064       Indices.push_back(Val);
2065     }
2066     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2067                                                  &Indices[0], Indices.size());
2068   } else if (getOpcode() == Instruction::ExtractValue) {
2069     Constant *Agg = getOperand(0);
2070     if (Agg == From) Agg = To;
2071     
2072     const SmallVector<unsigned, 4> &Indices = getIndices();
2073     Replacement = ConstantExpr::getExtractValue(Agg,
2074                                                 &Indices[0], Indices.size());
2075   } else if (getOpcode() == Instruction::InsertValue) {
2076     Constant *Agg = getOperand(0);
2077     Constant *Val = getOperand(1);
2078     if (Agg == From) Agg = To;
2079     if (Val == From) Val = To;
2080     
2081     const SmallVector<unsigned, 4> &Indices = getIndices();
2082     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2083                                                &Indices[0], Indices.size());
2084   } else if (isCast()) {
2085     assert(getOperand(0) == From && "Cast only has one use!");
2086     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2087   } else if (getOpcode() == Instruction::Select) {
2088     Constant *C1 = getOperand(0);
2089     Constant *C2 = getOperand(1);
2090     Constant *C3 = getOperand(2);
2091     if (C1 == From) C1 = To;
2092     if (C2 == From) C2 = To;
2093     if (C3 == From) C3 = To;
2094     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2095   } else if (getOpcode() == Instruction::ExtractElement) {
2096     Constant *C1 = getOperand(0);
2097     Constant *C2 = getOperand(1);
2098     if (C1 == From) C1 = To;
2099     if (C2 == From) C2 = To;
2100     Replacement = ConstantExpr::getExtractElement(C1, C2);
2101   } else if (getOpcode() == Instruction::InsertElement) {
2102     Constant *C1 = getOperand(0);
2103     Constant *C2 = getOperand(1);
2104     Constant *C3 = getOperand(1);
2105     if (C1 == From) C1 = To;
2106     if (C2 == From) C2 = To;
2107     if (C3 == From) C3 = To;
2108     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2109   } else if (getOpcode() == Instruction::ShuffleVector) {
2110     Constant *C1 = getOperand(0);
2111     Constant *C2 = getOperand(1);
2112     Constant *C3 = getOperand(2);
2113     if (C1 == From) C1 = To;
2114     if (C2 == From) C2 = To;
2115     if (C3 == From) C3 = To;
2116     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2117   } else if (isCompare()) {
2118     Constant *C1 = getOperand(0);
2119     Constant *C2 = getOperand(1);
2120     if (C1 == From) C1 = To;
2121     if (C2 == From) C2 = To;
2122     if (getOpcode() == Instruction::ICmp)
2123       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2124     else {
2125       assert(getOpcode() == Instruction::FCmp);
2126       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2127     }
2128   } else if (getNumOperands() == 2) {
2129     Constant *C1 = getOperand(0);
2130     Constant *C2 = getOperand(1);
2131     if (C1 == From) C1 = To;
2132     if (C2 == From) C2 = To;
2133     Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassData);
2134   } else {
2135     llvm_unreachable("Unknown ConstantExpr type!");
2136     return;
2137   }
2138   
2139   assert(Replacement != this && "I didn't contain From!");
2140   
2141   // Everyone using this now uses the replacement.
2142   uncheckedReplaceAllUsesWith(Replacement);
2143   
2144   // Delete the old constant!
2145   destroyConstant();
2146 }