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