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