Remove the API for creating ConstantExprs with the nsw, nuw, inbounds,
[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 // Utility function for determining if a ConstantExpr is a CastOp or not. This
635 // can't be inline because we don't want to #include Instruction.h into
636 // Constant.h
637 bool ConstantExpr::isCast() const {
638   return Instruction::isCast(getOpcode());
639 }
640
641 bool ConstantExpr::isCompare() const {
642   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
643 }
644
645 bool ConstantExpr::hasIndices() const {
646   return getOpcode() == Instruction::ExtractValue ||
647          getOpcode() == Instruction::InsertValue;
648 }
649
650 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
651   if (const ExtractValueConstantExpr *EVCE =
652         dyn_cast<ExtractValueConstantExpr>(this))
653     return EVCE->Indices;
654
655   return cast<InsertValueConstantExpr>(this)->Indices;
656 }
657
658 unsigned ConstantExpr::getPredicate() const {
659   assert(getOpcode() == Instruction::FCmp || 
660          getOpcode() == Instruction::ICmp);
661   return ((const CompareConstantExpr*)this)->predicate;
662 }
663
664 /// getWithOperandReplaced - Return a constant expression identical to this
665 /// one, but with the specified operand set to the specified value.
666 Constant *
667 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
668   assert(OpNo < getNumOperands() && "Operand num is out of range!");
669   assert(Op->getType() == getOperand(OpNo)->getType() &&
670          "Replacing operand with value of different type!");
671   if (getOperand(OpNo) == Op)
672     return const_cast<ConstantExpr*>(this);
673   
674   Constant *Op0, *Op1, *Op2;
675   switch (getOpcode()) {
676   case Instruction::Trunc:
677   case Instruction::ZExt:
678   case Instruction::SExt:
679   case Instruction::FPTrunc:
680   case Instruction::FPExt:
681   case Instruction::UIToFP:
682   case Instruction::SIToFP:
683   case Instruction::FPToUI:
684   case Instruction::FPToSI:
685   case Instruction::PtrToInt:
686   case Instruction::IntToPtr:
687   case Instruction::BitCast:
688     return ConstantExpr::getCast(getOpcode(), Op, getType());
689   case Instruction::Select:
690     Op0 = (OpNo == 0) ? Op : getOperand(0);
691     Op1 = (OpNo == 1) ? Op : getOperand(1);
692     Op2 = (OpNo == 2) ? Op : getOperand(2);
693     return ConstantExpr::getSelect(Op0, Op1, Op2);
694   case Instruction::InsertElement:
695     Op0 = (OpNo == 0) ? Op : getOperand(0);
696     Op1 = (OpNo == 1) ? Op : getOperand(1);
697     Op2 = (OpNo == 2) ? Op : getOperand(2);
698     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
699   case Instruction::ExtractElement:
700     Op0 = (OpNo == 0) ? Op : getOperand(0);
701     Op1 = (OpNo == 1) ? Op : getOperand(1);
702     return ConstantExpr::getExtractElement(Op0, Op1);
703   case Instruction::ShuffleVector:
704     Op0 = (OpNo == 0) ? Op : getOperand(0);
705     Op1 = (OpNo == 1) ? Op : getOperand(1);
706     Op2 = (OpNo == 2) ? Op : getOperand(2);
707     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
708   case Instruction::GetElementPtr: {
709     SmallVector<Constant*, 8> Ops;
710     Ops.resize(getNumOperands()-1);
711     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
712       Ops[i-1] = getOperand(i);
713     if (OpNo == 0)
714       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
715     Ops[OpNo-1] = Op;
716     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
717   }
718   default:
719     assert(getNumOperands() == 2 && "Must be binary operator?");
720     Op0 = (OpNo == 0) ? Op : getOperand(0);
721     Op1 = (OpNo == 1) ? Op : getOperand(1);
722     return ConstantExpr::get(getOpcode(), Op0, Op1);
723   }
724 }
725
726 /// getWithOperands - This returns the current constant expression with the
727 /// operands replaced with the specified values.  The specified operands must
728 /// match count and type with the existing ones.
729 Constant *ConstantExpr::
730 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
731   assert(NumOps == getNumOperands() && "Operand count mismatch!");
732   bool AnyChange = false;
733   for (unsigned i = 0; i != NumOps; ++i) {
734     assert(Ops[i]->getType() == getOperand(i)->getType() &&
735            "Operand type mismatch!");
736     AnyChange |= Ops[i] != getOperand(i);
737   }
738   if (!AnyChange)  // No operands changed, return self.
739     return const_cast<ConstantExpr*>(this);
740
741   switch (getOpcode()) {
742   case Instruction::Trunc:
743   case Instruction::ZExt:
744   case Instruction::SExt:
745   case Instruction::FPTrunc:
746   case Instruction::FPExt:
747   case Instruction::UIToFP:
748   case Instruction::SIToFP:
749   case Instruction::FPToUI:
750   case Instruction::FPToSI:
751   case Instruction::PtrToInt:
752   case Instruction::IntToPtr:
753   case Instruction::BitCast:
754     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
755   case Instruction::Select:
756     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
757   case Instruction::InsertElement:
758     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
759   case Instruction::ExtractElement:
760     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
761   case Instruction::ShuffleVector:
762     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
763   case Instruction::GetElementPtr:
764     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
765   case Instruction::ICmp:
766   case Instruction::FCmp:
767     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
768   default:
769     assert(getNumOperands() == 2 && "Must be binary operator?");
770     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
771   }
772 }
773
774
775 //===----------------------------------------------------------------------===//
776 //                      isValueValidForType implementations
777
778 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
779   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
780   if (Ty == Type::getInt1Ty(Ty->getContext()))
781     return Val == 0 || Val == 1;
782   if (NumBits >= 64)
783     return true; // always true, has to fit in largest type
784   uint64_t Max = (1ll << NumBits) - 1;
785   return Val <= Max;
786 }
787
788 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
789   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
790   if (Ty == Type::getInt1Ty(Ty->getContext()))
791     return Val == 0 || Val == 1 || Val == -1;
792   if (NumBits >= 64)
793     return true; // always true, has to fit in largest type
794   int64_t Min = -(1ll << (NumBits-1));
795   int64_t Max = (1ll << (NumBits-1)) - 1;
796   return (Val >= Min && Val <= Max);
797 }
798
799 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
800   // convert modifies in place, so make a copy.
801   APFloat Val2 = APFloat(Val);
802   bool losesInfo;
803   switch (Ty->getTypeID()) {
804   default:
805     return false;         // These can't be represented as floating point!
806
807   // FIXME rounding mode needs to be more flexible
808   case Type::FloatTyID: {
809     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
810       return true;
811     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
812     return !losesInfo;
813   }
814   case Type::DoubleTyID: {
815     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
816         &Val2.getSemantics() == &APFloat::IEEEdouble)
817       return true;
818     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
819     return !losesInfo;
820   }
821   case Type::X86_FP80TyID:
822     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
823            &Val2.getSemantics() == &APFloat::IEEEdouble ||
824            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
825   case Type::FP128TyID:
826     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
827            &Val2.getSemantics() == &APFloat::IEEEdouble ||
828            &Val2.getSemantics() == &APFloat::IEEEquad;
829   case Type::PPC_FP128TyID:
830     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
831            &Val2.getSemantics() == &APFloat::IEEEdouble ||
832            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
833   }
834 }
835
836 //===----------------------------------------------------------------------===//
837 //                      Factory Function Implementation
838
839 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
840
841 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
842   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
843          "Cannot create an aggregate zero of non-aggregate type!");
844   
845   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
846   // Implicitly locked.
847   return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
848 }
849
850 /// destroyConstant - Remove the constant from the constant table...
851 ///
852 void ConstantAggregateZero::destroyConstant() {
853   // Implicitly locked.
854   getType()->getContext().pImpl->AggZeroConstants.remove(this);
855   destroyConstantImpl();
856 }
857
858 /// destroyConstant - Remove the constant from the constant table...
859 ///
860 void ConstantArray::destroyConstant() {
861   // Implicitly locked.
862   getType()->getContext().pImpl->ArrayConstants.remove(this);
863   destroyConstantImpl();
864 }
865
866 /// isString - This method returns true if the array is an array of i8, and 
867 /// if the elements of the array are all ConstantInt's.
868 bool ConstantArray::isString() const {
869   // Check the element type for i8...
870   if (getType()->getElementType() != Type::getInt8Ty(getContext()))
871     return false;
872   // Check the elements to make sure they are all integers, not constant
873   // expressions.
874   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
875     if (!isa<ConstantInt>(getOperand(i)))
876       return false;
877   return true;
878 }
879
880 /// isCString - This method returns true if the array is a string (see
881 /// isString) and it ends in a null byte \\0 and does not contains any other
882 /// null bytes except its terminator.
883 bool ConstantArray::isCString() const {
884   // Check the element type for i8...
885   if (getType()->getElementType() != Type::getInt8Ty(getContext()))
886     return false;
887
888   // Last element must be a null.
889   if (!getOperand(getNumOperands()-1)->isNullValue())
890     return false;
891   // Other elements must be non-null integers.
892   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
893     if (!isa<ConstantInt>(getOperand(i)))
894       return false;
895     if (getOperand(i)->isNullValue())
896       return false;
897   }
898   return true;
899 }
900
901
902 /// getAsString - If the sub-element type of this array is i8
903 /// then this method converts the array to an std::string and returns it.
904 /// Otherwise, it asserts out.
905 ///
906 std::string ConstantArray::getAsString() const {
907   assert(isString() && "Not a string!");
908   std::string Result;
909   Result.reserve(getNumOperands());
910   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
911     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
912   return Result;
913 }
914
915
916 //---- ConstantStruct::get() implementation...
917 //
918
919 namespace llvm {
920
921 }
922
923 // destroyConstant - Remove the constant from the constant table...
924 //
925 void ConstantStruct::destroyConstant() {
926   // Implicitly locked.
927   getType()->getContext().pImpl->StructConstants.remove(this);
928   destroyConstantImpl();
929 }
930
931 // destroyConstant - Remove the constant from the constant table...
932 //
933 void ConstantVector::destroyConstant() {
934   // Implicitly locked.
935   getType()->getContext().pImpl->VectorConstants.remove(this);
936   destroyConstantImpl();
937 }
938
939 /// This function will return true iff every element in this vector constant
940 /// is set to all ones.
941 /// @returns true iff this constant's emements are all set to all ones.
942 /// @brief Determine if the value is all ones.
943 bool ConstantVector::isAllOnesValue() const {
944   // Check out first element.
945   const Constant *Elt = getOperand(0);
946   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
947   if (!CI || !CI->isAllOnesValue()) return false;
948   // Then make sure all remaining elements point to the same value.
949   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
950     if (getOperand(I) != Elt) return false;
951   }
952   return true;
953 }
954
955 /// getSplatValue - If this is a splat constant, where all of the
956 /// elements have the same value, return that value. Otherwise return null.
957 Constant *ConstantVector::getSplatValue() {
958   // Check out first element.
959   Constant *Elt = getOperand(0);
960   // Then make sure all remaining elements point to the same value.
961   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
962     if (getOperand(I) != Elt) return 0;
963   return Elt;
964 }
965
966 //---- ConstantPointerNull::get() implementation...
967 //
968
969 static char getValType(ConstantPointerNull *) {
970   return 0;
971 }
972
973
974 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
975   // Implicitly locked.
976   return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
977 }
978
979 // destroyConstant - Remove the constant from the constant table...
980 //
981 void ConstantPointerNull::destroyConstant() {
982   // Implicitly locked.
983   getType()->getContext().pImpl->NullPtrConstants.remove(this);
984   destroyConstantImpl();
985 }
986
987
988 //---- UndefValue::get() implementation...
989 //
990
991 static char getValType(UndefValue *) {
992   return 0;
993 }
994
995 UndefValue *UndefValue::get(const Type *Ty) {
996   // Implicitly locked.
997   return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
998 }
999
1000 // destroyConstant - Remove the constant from the constant table.
1001 //
1002 void UndefValue::destroyConstant() {
1003   // Implicitly locked.
1004   getType()->getContext().pImpl->UndefValueConstants.remove(this);
1005   destroyConstantImpl();
1006 }
1007
1008 //---- ConstantExpr::get() implementations...
1009 //
1010
1011 static ExprMapKeyType getValType(ConstantExpr *CE) {
1012   std::vector<Constant*> Operands;
1013   Operands.reserve(CE->getNumOperands());
1014   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1015     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1016   return ExprMapKeyType(CE->getOpcode(), Operands, 
1017       CE->isCompare() ? CE->getPredicate() : 0,
1018       CE->hasIndices() ?
1019         CE->getIndices() : SmallVector<unsigned, 4>());
1020 }
1021
1022 /// This is a utility function to handle folding of casts and lookup of the
1023 /// cast in the ExprConstants map. It is used by the various get* methods below.
1024 static inline Constant *getFoldedCast(
1025   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1026   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1027   // Fold a few common cases
1028   if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1029     return FC;
1030
1031   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1032
1033   // Look up the constant in the table first to ensure uniqueness
1034   std::vector<Constant*> argVec(1, C);
1035   ExprMapKeyType Key(opc, argVec);
1036   
1037   // Implicitly locked.
1038   return pImpl->ExprConstants.getOrCreate(Ty, Key);
1039 }
1040  
1041 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1042   Instruction::CastOps opc = Instruction::CastOps(oc);
1043   assert(Instruction::isCast(opc) && "opcode out of range");
1044   assert(C && Ty && "Null arguments to getCast");
1045   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1046
1047   switch (opc) {
1048     default:
1049       llvm_unreachable("Invalid cast opcode");
1050       break;
1051     case Instruction::Trunc:    return getTrunc(C, Ty);
1052     case Instruction::ZExt:     return getZExt(C, Ty);
1053     case Instruction::SExt:     return getSExt(C, Ty);
1054     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1055     case Instruction::FPExt:    return getFPExtend(C, Ty);
1056     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1057     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1058     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1059     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1060     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1061     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1062     case Instruction::BitCast:  return getBitCast(C, Ty);
1063   }
1064   return 0;
1065
1066
1067 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1068   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1069     return getCast(Instruction::BitCast, C, Ty);
1070   return getCast(Instruction::ZExt, C, Ty);
1071 }
1072
1073 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1074   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1075     return getCast(Instruction::BitCast, C, Ty);
1076   return getCast(Instruction::SExt, C, Ty);
1077 }
1078
1079 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1080   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1081     return getCast(Instruction::BitCast, C, Ty);
1082   return getCast(Instruction::Trunc, C, Ty);
1083 }
1084
1085 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1086   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1087   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1088
1089   if (Ty->isInteger())
1090     return getCast(Instruction::PtrToInt, S, Ty);
1091   return getCast(Instruction::BitCast, S, Ty);
1092 }
1093
1094 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1095                                        bool isSigned) {
1096   assert(C->getType()->isIntOrIntVector() &&
1097          Ty->isIntOrIntVector() && "Invalid cast");
1098   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1099   unsigned DstBits = Ty->getScalarSizeInBits();
1100   Instruction::CastOps opcode =
1101     (SrcBits == DstBits ? Instruction::BitCast :
1102      (SrcBits > DstBits ? Instruction::Trunc :
1103       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1104   return getCast(opcode, C, Ty);
1105 }
1106
1107 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1108   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1109          "Invalid cast");
1110   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1111   unsigned DstBits = Ty->getScalarSizeInBits();
1112   if (SrcBits == DstBits)
1113     return C; // Avoid a useless cast
1114   Instruction::CastOps opcode =
1115      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1116   return getCast(opcode, C, Ty);
1117 }
1118
1119 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1120 #ifndef NDEBUG
1121   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1122   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1123 #endif
1124   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1125   assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1126   assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1127   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1128          "SrcTy must be larger than DestTy for Trunc!");
1129
1130   return getFoldedCast(Instruction::Trunc, C, Ty);
1131 }
1132
1133 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1134 #ifndef NDEBUG
1135   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1136   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1137 #endif
1138   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1139   assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1140   assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1141   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1142          "SrcTy must be smaller than DestTy for SExt!");
1143
1144   return getFoldedCast(Instruction::SExt, C, Ty);
1145 }
1146
1147 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1148 #ifndef NDEBUG
1149   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1150   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1151 #endif
1152   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1153   assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1154   assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1155   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1156          "SrcTy must be smaller than DestTy for ZExt!");
1157
1158   return getFoldedCast(Instruction::ZExt, C, Ty);
1159 }
1160
1161 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1162 #ifndef NDEBUG
1163   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1164   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1165 #endif
1166   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1167   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1168          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1169          "This is an illegal floating point truncation!");
1170   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1171 }
1172
1173 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1174 #ifndef NDEBUG
1175   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1176   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1177 #endif
1178   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1179   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1180          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1181          "This is an illegal floating point extension!");
1182   return getFoldedCast(Instruction::FPExt, C, Ty);
1183 }
1184
1185 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1186 #ifndef NDEBUG
1187   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1188   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1189 #endif
1190   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1191   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1192          "This is an illegal uint to floating point cast!");
1193   return getFoldedCast(Instruction::UIToFP, C, Ty);
1194 }
1195
1196 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1197 #ifndef NDEBUG
1198   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1199   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1200 #endif
1201   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1202   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1203          "This is an illegal sint to floating point cast!");
1204   return getFoldedCast(Instruction::SIToFP, C, Ty);
1205 }
1206
1207 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1208 #ifndef NDEBUG
1209   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1210   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1211 #endif
1212   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1213   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1214          "This is an illegal floating point to uint cast!");
1215   return getFoldedCast(Instruction::FPToUI, C, Ty);
1216 }
1217
1218 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1219 #ifndef NDEBUG
1220   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1221   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1222 #endif
1223   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1224   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1225          "This is an illegal floating point to sint cast!");
1226   return getFoldedCast(Instruction::FPToSI, C, Ty);
1227 }
1228
1229 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1230   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1231   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1232   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1233 }
1234
1235 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1236   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1237   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1238   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1239 }
1240
1241 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1242   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1243   // can't cast pointers to anything but pointers.
1244 #ifndef NDEBUG
1245   const Type *SrcTy = C->getType();
1246   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1247          "BitCast cannot cast pointer to non-pointer and vice versa");
1248
1249   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1250   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1251   // destination bit widths are identical.
1252   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1253   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1254 #endif
1255   assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1256   
1257   // It is common to ask for a bitcast of a value to its own type, handle this
1258   // speedily.
1259   if (C->getType() == DstTy) return C;
1260   
1261   return getFoldedCast(Instruction::BitCast, C, DstTy);
1262 }
1263
1264 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1265                               Constant *C1, Constant *C2) {
1266   // Check the operands for consistency first
1267   assert(Opcode >= Instruction::BinaryOpsBegin &&
1268          Opcode <  Instruction::BinaryOpsEnd   &&
1269          "Invalid opcode in binary constant expression");
1270   assert(C1->getType() == C2->getType() &&
1271          "Operand types in binary constant expression should match");
1272
1273   if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1274     if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1275                                                      Opcode, C1, C2))
1276       return FC;          // Fold a few common cases...
1277
1278   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1279   ExprMapKeyType Key(Opcode, argVec);
1280   
1281   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1282   
1283   // Implicitly locked.
1284   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1285 }
1286
1287 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1288                                      Constant *C1, Constant *C2) {
1289   switch (predicate) {
1290     default: llvm_unreachable("Invalid CmpInst predicate");
1291     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1292     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1293     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1294     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1295     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1296     case CmpInst::FCMP_TRUE:
1297       return getFCmp(predicate, C1, C2);
1298
1299     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1300     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1301     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1302     case CmpInst::ICMP_SLE:
1303       return getICmp(predicate, C1, C2);
1304   }
1305 }
1306
1307 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1308   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1309   if (C1->getType()->isFPOrFPVector()) {
1310     if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1311     else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1312     else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1313   }
1314 #ifndef NDEBUG
1315   switch (Opcode) {
1316   case Instruction::Add:
1317   case Instruction::Sub:
1318   case Instruction::Mul:
1319     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1320     assert(C1->getType()->isIntOrIntVector() &&
1321            "Tried to create an integer operation on a non-integer type!");
1322     break;
1323   case Instruction::FAdd:
1324   case Instruction::FSub:
1325   case Instruction::FMul:
1326     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1327     assert(C1->getType()->isFPOrFPVector() &&
1328            "Tried to create a floating-point operation on a "
1329            "non-floating-point type!");
1330     break;
1331   case Instruction::UDiv: 
1332   case Instruction::SDiv: 
1333     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1334     assert(C1->getType()->isIntOrIntVector() &&
1335            "Tried to create an arithmetic operation on a non-arithmetic type!");
1336     break;
1337   case Instruction::FDiv:
1338     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1339     assert(C1->getType()->isFPOrFPVector() &&
1340            "Tried to create an arithmetic operation on a non-arithmetic type!");
1341     break;
1342   case Instruction::URem: 
1343   case Instruction::SRem: 
1344     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1345     assert(C1->getType()->isIntOrIntVector() &&
1346            "Tried to create an arithmetic operation on a non-arithmetic type!");
1347     break;
1348   case Instruction::FRem:
1349     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1350     assert(C1->getType()->isFPOrFPVector() &&
1351            "Tried to create an arithmetic operation on a non-arithmetic type!");
1352     break;
1353   case Instruction::And:
1354   case Instruction::Or:
1355   case Instruction::Xor:
1356     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1357     assert(C1->getType()->isIntOrIntVector() &&
1358            "Tried to create a logical operation on a non-integral type!");
1359     break;
1360   case Instruction::Shl:
1361   case Instruction::LShr:
1362   case Instruction::AShr:
1363     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1364     assert(C1->getType()->isIntOrIntVector() &&
1365            "Tried to create a shift operation on a non-integer type!");
1366     break;
1367   default:
1368     break;
1369   }
1370 #endif
1371
1372   return getTy(C1->getType(), Opcode, C1, C2);
1373 }
1374
1375 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1376   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1377   // Note that a non-inbounds gep is used, as null isn't within any object.
1378   Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1379   Constant *GEP = getGetElementPtr(
1380                  Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1381   return getCast(Instruction::PtrToInt, GEP, 
1382                  Type::getInt64Ty(Ty->getContext()));
1383 }
1384
1385 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1386   // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1387   // Note that a non-inbounds gep is used, as null isn't within any object.
1388   const Type *AligningTy = StructType::get(Ty->getContext(),
1389                                    Type::getInt8Ty(Ty->getContext()), Ty, NULL);
1390   Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1391   Constant *Zero = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 0);
1392   Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1393   Constant *Indices[2] = { Zero, One };
1394   Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1395   return getCast(Instruction::PtrToInt, GEP,
1396                  Type::getInt32Ty(Ty->getContext()));
1397 }
1398
1399 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1400   // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1401   // Note that a non-inbounds gep is used, as null isn't within any object.
1402   Constant *GEPIdx[] = {
1403     ConstantInt::get(Type::getInt64Ty(STy->getContext()), 0),
1404     ConstantInt::get(Type::getInt32Ty(STy->getContext()), FieldNo)
1405   };
1406   Constant *GEP = getGetElementPtr(
1407                 Constant::getNullValue(PointerType::getUnqual(STy)), GEPIdx, 2);
1408   return getCast(Instruction::PtrToInt, GEP,
1409                  Type::getInt64Ty(STy->getContext()));
1410 }
1411
1412 Constant *ConstantExpr::getCompare(unsigned short pred, 
1413                             Constant *C1, Constant *C2) {
1414   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1415   return getCompareTy(pred, C1, C2);
1416 }
1417
1418 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1419                                     Constant *V1, Constant *V2) {
1420   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1421
1422   if (ReqTy == V1->getType())
1423     if (Constant *SC = ConstantFoldSelectInstruction(
1424                                                 ReqTy->getContext(), C, V1, V2))
1425       return SC;        // Fold common cases
1426
1427   std::vector<Constant*> argVec(3, C);
1428   argVec[1] = V1;
1429   argVec[2] = V2;
1430   ExprMapKeyType Key(Instruction::Select, argVec);
1431   
1432   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1433   
1434   // Implicitly locked.
1435   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1436 }
1437
1438 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1439                                            Value* const *Idxs,
1440                                            unsigned NumIdx) {
1441   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1442                                            Idxs+NumIdx) ==
1443          cast<PointerType>(ReqTy)->getElementType() &&
1444          "GEP indices invalid!");
1445
1446   if (Constant *FC = ConstantFoldGetElementPtr(
1447                               ReqTy->getContext(), C, (Constant**)Idxs, NumIdx))
1448     return FC;          // Fold a few common cases...
1449
1450   assert(isa<PointerType>(C->getType()) &&
1451          "Non-pointer type for constant GetElementPtr expression");
1452   // Look up the constant in the table first to ensure uniqueness
1453   std::vector<Constant*> ArgVec;
1454   ArgVec.reserve(NumIdx+1);
1455   ArgVec.push_back(C);
1456   for (unsigned i = 0; i != NumIdx; ++i)
1457     ArgVec.push_back(cast<Constant>(Idxs[i]));
1458   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1459
1460   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1461
1462   // Implicitly locked.
1463   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1464 }
1465
1466 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1467                                          unsigned NumIdx) {
1468   // Get the result type of the getelementptr!
1469   const Type *Ty = 
1470     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1471   assert(Ty && "GEP indices invalid!");
1472   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1473   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1474 }
1475
1476 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1477                                          unsigned NumIdx) {
1478   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1479 }
1480
1481 Constant *
1482 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1483   assert(LHS->getType() == RHS->getType());
1484   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1485          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1486
1487   if (Constant *FC = ConstantFoldCompareInstruction(
1488                                              LHS->getContext(), pred, LHS, RHS))
1489     return FC;          // Fold a few common cases...
1490
1491   // Look up the constant in the table first to ensure uniqueness
1492   std::vector<Constant*> ArgVec;
1493   ArgVec.push_back(LHS);
1494   ArgVec.push_back(RHS);
1495   // Get the key type with both the opcode and predicate
1496   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1497
1498   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1499
1500   // Implicitly locked.
1501   return
1502       pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1503 }
1504
1505 Constant *
1506 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1507   assert(LHS->getType() == RHS->getType());
1508   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1509
1510   if (Constant *FC = ConstantFoldCompareInstruction(
1511                                             LHS->getContext(), pred, LHS, RHS))
1512     return FC;          // Fold a few common cases...
1513
1514   // Look up the constant in the table first to ensure uniqueness
1515   std::vector<Constant*> ArgVec;
1516   ArgVec.push_back(LHS);
1517   ArgVec.push_back(RHS);
1518   // Get the key type with both the opcode and predicate
1519   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1520   
1521   LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1522   
1523   // Implicitly locked.
1524   return
1525       pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1526 }
1527
1528 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1529                                             Constant *Idx) {
1530   if (Constant *FC = ConstantFoldExtractElementInstruction(
1531                                                 ReqTy->getContext(), Val, Idx))
1532     return FC;          // Fold a few common cases...
1533   // Look up the constant in the table first to ensure uniqueness
1534   std::vector<Constant*> ArgVec(1, Val);
1535   ArgVec.push_back(Idx);
1536   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1537   
1538   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1539   
1540   // Implicitly locked.
1541   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1542 }
1543
1544 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1545   assert(isa<VectorType>(Val->getType()) &&
1546          "Tried to create extractelement operation on non-vector type!");
1547   assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1548          "Extractelement index must be i32 type!");
1549   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1550                              Val, Idx);
1551 }
1552
1553 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1554                                            Constant *Elt, Constant *Idx) {
1555   if (Constant *FC = ConstantFoldInsertElementInstruction(
1556                                             ReqTy->getContext(), Val, Elt, Idx))
1557     return FC;          // Fold a few common cases...
1558   // Look up the constant in the table first to ensure uniqueness
1559   std::vector<Constant*> ArgVec(1, Val);
1560   ArgVec.push_back(Elt);
1561   ArgVec.push_back(Idx);
1562   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1563   
1564   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1565   
1566   // Implicitly locked.
1567   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1568 }
1569
1570 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1571                                          Constant *Idx) {
1572   assert(isa<VectorType>(Val->getType()) &&
1573          "Tried to create insertelement operation on non-vector type!");
1574   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1575          && "Insertelement types must match!");
1576   assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1577          "Insertelement index must be i32 type!");
1578   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1579 }
1580
1581 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1582                                            Constant *V2, Constant *Mask) {
1583   if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1584                                             ReqTy->getContext(), V1, V2, Mask))
1585     return FC;          // Fold a few common cases...
1586   // Look up the constant in the table first to ensure uniqueness
1587   std::vector<Constant*> ArgVec(1, V1);
1588   ArgVec.push_back(V2);
1589   ArgVec.push_back(Mask);
1590   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1591   
1592   LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1593   
1594   // Implicitly locked.
1595   return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1596 }
1597
1598 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1599                                          Constant *Mask) {
1600   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1601          "Invalid shuffle vector constant expr operands!");
1602
1603   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1604   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1605   const Type *ShufTy = VectorType::get(EltTy, NElts);
1606   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1607 }
1608
1609 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1610                                          Constant *Val,
1611                                         const unsigned *Idxs, unsigned NumIdx) {
1612   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1613                                           Idxs+NumIdx) == Val->getType() &&
1614          "insertvalue indices invalid!");
1615   assert(Agg->getType() == ReqTy &&
1616          "insertvalue type invalid!");
1617   assert(Agg->getType()->isFirstClassType() &&
1618          "Non-first-class type for constant InsertValue expression");
1619   Constant *FC = ConstantFoldInsertValueInstruction(
1620                                   ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1621   assert(FC && "InsertValue constant expr couldn't be folded!");
1622   return FC;
1623 }
1624
1625 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1626                                      const unsigned *IdxList, unsigned NumIdx) {
1627   assert(Agg->getType()->isFirstClassType() &&
1628          "Tried to create insertelement operation on non-first-class type!");
1629
1630   const Type *ReqTy = Agg->getType();
1631 #ifndef NDEBUG
1632   const Type *ValTy =
1633     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1634 #endif
1635   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1636   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1637 }
1638
1639 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1640                                         const unsigned *Idxs, unsigned NumIdx) {
1641   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1642                                           Idxs+NumIdx) == ReqTy &&
1643          "extractvalue indices invalid!");
1644   assert(Agg->getType()->isFirstClassType() &&
1645          "Non-first-class type for constant extractvalue expression");
1646   Constant *FC = ConstantFoldExtractValueInstruction(
1647                                         ReqTy->getContext(), Agg, Idxs, NumIdx);
1648   assert(FC && "ExtractValue constant expr couldn't be folded!");
1649   return FC;
1650 }
1651
1652 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1653                                      const unsigned *IdxList, unsigned NumIdx) {
1654   assert(Agg->getType()->isFirstClassType() &&
1655          "Tried to create extractelement operation on non-first-class type!");
1656
1657   const Type *ReqTy =
1658     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1659   assert(ReqTy && "extractvalue indices invalid!");
1660   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1661 }
1662
1663 Constant* ConstantExpr::getNeg(Constant* C) {
1664   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1665   if (C->getType()->isFPOrFPVector())
1666     return getFNeg(C);
1667   assert(C->getType()->isIntOrIntVector() &&
1668          "Cannot NEG a nonintegral value!");
1669   return get(Instruction::Sub,
1670              ConstantFP::getZeroValueForNegation(C->getType()),
1671              C);
1672 }
1673
1674 Constant* ConstantExpr::getFNeg(Constant* C) {
1675   assert(C->getType()->isFPOrFPVector() &&
1676          "Cannot FNEG a non-floating-point value!");
1677   return get(Instruction::FSub,
1678              ConstantFP::getZeroValueForNegation(C->getType()),
1679              C);
1680 }
1681
1682 Constant* ConstantExpr::getNot(Constant* C) {
1683   assert(C->getType()->isIntOrIntVector() &&
1684          "Cannot NOT a nonintegral value!");
1685   return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1686 }
1687
1688 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1689   return get(Instruction::Add, C1, C2);
1690 }
1691
1692 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1693   return get(Instruction::FAdd, C1, C2);
1694 }
1695
1696 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1697   return get(Instruction::Sub, C1, C2);
1698 }
1699
1700 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1701   return get(Instruction::FSub, C1, C2);
1702 }
1703
1704 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1705   return get(Instruction::Mul, C1, C2);
1706 }
1707
1708 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1709   return get(Instruction::FMul, C1, C2);
1710 }
1711
1712 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1713   return get(Instruction::UDiv, C1, C2);
1714 }
1715
1716 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1717   return get(Instruction::SDiv, C1, C2);
1718 }
1719
1720 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1721   return get(Instruction::FDiv, C1, C2);
1722 }
1723
1724 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1725   return get(Instruction::URem, C1, C2);
1726 }
1727
1728 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1729   return get(Instruction::SRem, C1, C2);
1730 }
1731
1732 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1733   return get(Instruction::FRem, C1, C2);
1734 }
1735
1736 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1737   return get(Instruction::And, C1, C2);
1738 }
1739
1740 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1741   return get(Instruction::Or, C1, C2);
1742 }
1743
1744 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1745   return get(Instruction::Xor, C1, C2);
1746 }
1747
1748 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1749   return get(Instruction::Shl, C1, C2);
1750 }
1751
1752 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1753   return get(Instruction::LShr, C1, C2);
1754 }
1755
1756 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1757   return get(Instruction::AShr, C1, C2);
1758 }
1759
1760 // destroyConstant - Remove the constant from the constant table...
1761 //
1762 void ConstantExpr::destroyConstant() {
1763   // Implicitly locked.
1764   LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1765   pImpl->ExprConstants.remove(this);
1766   destroyConstantImpl();
1767 }
1768
1769 const char *ConstantExpr::getOpcodeName() const {
1770   return Instruction::getOpcodeName(getOpcode());
1771 }
1772
1773 //===----------------------------------------------------------------------===//
1774 //                replaceUsesOfWithOnConstant implementations
1775
1776 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1777 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
1778 /// etc.
1779 ///
1780 /// Note that we intentionally replace all uses of From with To here.  Consider
1781 /// a large array that uses 'From' 1000 times.  By handling this case all here,
1782 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1783 /// single invocation handles all 1000 uses.  Handling them one at a time would
1784 /// work, but would be really slow because it would have to unique each updated
1785 /// array instance.
1786
1787 static std::vector<Constant*> getValType(ConstantArray *CA) {
1788   std::vector<Constant*> Elements;
1789   Elements.reserve(CA->getNumOperands());
1790   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1791     Elements.push_back(cast<Constant>(CA->getOperand(i)));
1792   return Elements;
1793 }
1794
1795
1796 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1797                                                 Use *U) {
1798   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1799   Constant *ToC = cast<Constant>(To);
1800
1801   LLVMContext &Context = getType()->getContext();
1802   LLVMContextImpl *pImpl = Context.pImpl;
1803
1804   std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
1805   Lookup.first.first = getType();
1806   Lookup.second = this;
1807
1808   std::vector<Constant*> &Values = Lookup.first.second;
1809   Values.reserve(getNumOperands());  // Build replacement array.
1810
1811   // Fill values with the modified operands of the constant array.  Also, 
1812   // compute whether this turns into an all-zeros array.
1813   bool isAllZeros = false;
1814   unsigned NumUpdated = 0;
1815   if (!ToC->isNullValue()) {
1816     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1817       Constant *Val = cast<Constant>(O->get());
1818       if (Val == From) {
1819         Val = ToC;
1820         ++NumUpdated;
1821       }
1822       Values.push_back(Val);
1823     }
1824   } else {
1825     isAllZeros = true;
1826     for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1827       Constant *Val = cast<Constant>(O->get());
1828       if (Val == From) {
1829         Val = ToC;
1830         ++NumUpdated;
1831       }
1832       Values.push_back(Val);
1833       if (isAllZeros) isAllZeros = Val->isNullValue();
1834     }
1835   }
1836   
1837   Constant *Replacement = 0;
1838   if (isAllZeros) {
1839     Replacement = ConstantAggregateZero::get(getType());
1840   } else {
1841     // Check to see if we have this array type already.
1842     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1843     bool Exists;
1844     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1845       pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1846     
1847     if (Exists) {
1848       Replacement = I->second;
1849     } else {
1850       // Okay, the new shape doesn't exist in the system yet.  Instead of
1851       // creating a new constant array, inserting it, replaceallusesof'ing the
1852       // old with the new, then deleting the old... just update the current one
1853       // in place!
1854       pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1855       
1856       // Update to the new value.  Optimize for the case when we have a single
1857       // operand that we're changing, but handle bulk updates efficiently.
1858       if (NumUpdated == 1) {
1859         unsigned OperandToUpdate = U - OperandList;
1860         assert(getOperand(OperandToUpdate) == From &&
1861                "ReplaceAllUsesWith broken!");
1862         setOperand(OperandToUpdate, ToC);
1863       } else {
1864         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1865           if (getOperand(i) == From)
1866             setOperand(i, ToC);
1867       }
1868       return;
1869     }
1870   }
1871  
1872   // Otherwise, I do need to replace this with an existing value.
1873   assert(Replacement != this && "I didn't contain From!");
1874   
1875   // Everyone using this now uses the replacement.
1876   uncheckedReplaceAllUsesWith(Replacement);
1877   
1878   // Delete the old constant!
1879   destroyConstant();
1880 }
1881
1882 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1883   std::vector<Constant*> Elements;
1884   Elements.reserve(CS->getNumOperands());
1885   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1886     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1887   return Elements;
1888 }
1889
1890 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1891                                                  Use *U) {
1892   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1893   Constant *ToC = cast<Constant>(To);
1894
1895   unsigned OperandToUpdate = U-OperandList;
1896   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1897
1898   std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
1899   Lookup.first.first = getType();
1900   Lookup.second = this;
1901   std::vector<Constant*> &Values = Lookup.first.second;
1902   Values.reserve(getNumOperands());  // Build replacement struct.
1903   
1904   
1905   // Fill values with the modified operands of the constant struct.  Also, 
1906   // compute whether this turns into an all-zeros struct.
1907   bool isAllZeros = false;
1908   if (!ToC->isNullValue()) {
1909     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1910       Values.push_back(cast<Constant>(O->get()));
1911   } else {
1912     isAllZeros = true;
1913     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1914       Constant *Val = cast<Constant>(O->get());
1915       Values.push_back(Val);
1916       if (isAllZeros) isAllZeros = Val->isNullValue();
1917     }
1918   }
1919   Values[OperandToUpdate] = ToC;
1920   
1921   LLVMContext &Context = getType()->getContext();
1922   LLVMContextImpl *pImpl = Context.pImpl;
1923   
1924   Constant *Replacement = 0;
1925   if (isAllZeros) {
1926     Replacement = ConstantAggregateZero::get(getType());
1927   } else {
1928     // Check to see if we have this array type already.
1929     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1930     bool Exists;
1931     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
1932       pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
1933     
1934     if (Exists) {
1935       Replacement = I->second;
1936     } else {
1937       // Okay, the new shape doesn't exist in the system yet.  Instead of
1938       // creating a new constant struct, inserting it, replaceallusesof'ing the
1939       // old with the new, then deleting the old... just update the current one
1940       // in place!
1941       pImpl->StructConstants.MoveConstantToNewSlot(this, I);
1942       
1943       // Update to the new value.
1944       setOperand(OperandToUpdate, ToC);
1945       return;
1946     }
1947   }
1948   
1949   assert(Replacement != this && "I didn't contain From!");
1950   
1951   // Everyone using this now uses the replacement.
1952   uncheckedReplaceAllUsesWith(Replacement);
1953   
1954   // Delete the old constant!
1955   destroyConstant();
1956 }
1957
1958 static std::vector<Constant*> getValType(ConstantVector *CP) {
1959   std::vector<Constant*> Elements;
1960   Elements.reserve(CP->getNumOperands());
1961   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1962     Elements.push_back(CP->getOperand(i));
1963   return Elements;
1964 }
1965
1966 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
1967                                                  Use *U) {
1968   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1969   
1970   std::vector<Constant*> Values;
1971   Values.reserve(getNumOperands());  // Build replacement array...
1972   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1973     Constant *Val = getOperand(i);
1974     if (Val == From) Val = cast<Constant>(To);
1975     Values.push_back(Val);
1976   }
1977   
1978   Constant *Replacement = get(getType(), Values);
1979   assert(Replacement != this && "I didn't contain From!");
1980   
1981   // Everyone using this now uses the replacement.
1982   uncheckedReplaceAllUsesWith(Replacement);
1983   
1984   // Delete the old constant!
1985   destroyConstant();
1986 }
1987
1988 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1989                                                Use *U) {
1990   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1991   Constant *To = cast<Constant>(ToV);
1992   
1993   Constant *Replacement = 0;
1994   if (getOpcode() == Instruction::GetElementPtr) {
1995     SmallVector<Constant*, 8> Indices;
1996     Constant *Pointer = getOperand(0);
1997     Indices.reserve(getNumOperands()-1);
1998     if (Pointer == From) Pointer = To;
1999     
2000     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2001       Constant *Val = getOperand(i);
2002       if (Val == From) Val = To;
2003       Indices.push_back(Val);
2004     }
2005     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2006                                                  &Indices[0], Indices.size());
2007   } else if (getOpcode() == Instruction::ExtractValue) {
2008     Constant *Agg = getOperand(0);
2009     if (Agg == From) Agg = To;
2010     
2011     const SmallVector<unsigned, 4> &Indices = getIndices();
2012     Replacement = ConstantExpr::getExtractValue(Agg,
2013                                                 &Indices[0], Indices.size());
2014   } else if (getOpcode() == Instruction::InsertValue) {
2015     Constant *Agg = getOperand(0);
2016     Constant *Val = getOperand(1);
2017     if (Agg == From) Agg = To;
2018     if (Val == From) Val = To;
2019     
2020     const SmallVector<unsigned, 4> &Indices = getIndices();
2021     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2022                                                &Indices[0], Indices.size());
2023   } else if (isCast()) {
2024     assert(getOperand(0) == From && "Cast only has one use!");
2025     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2026   } else if (getOpcode() == Instruction::Select) {
2027     Constant *C1 = getOperand(0);
2028     Constant *C2 = getOperand(1);
2029     Constant *C3 = getOperand(2);
2030     if (C1 == From) C1 = To;
2031     if (C2 == From) C2 = To;
2032     if (C3 == From) C3 = To;
2033     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2034   } else if (getOpcode() == Instruction::ExtractElement) {
2035     Constant *C1 = getOperand(0);
2036     Constant *C2 = getOperand(1);
2037     if (C1 == From) C1 = To;
2038     if (C2 == From) C2 = To;
2039     Replacement = ConstantExpr::getExtractElement(C1, C2);
2040   } else if (getOpcode() == Instruction::InsertElement) {
2041     Constant *C1 = getOperand(0);
2042     Constant *C2 = getOperand(1);
2043     Constant *C3 = getOperand(1);
2044     if (C1 == From) C1 = To;
2045     if (C2 == From) C2 = To;
2046     if (C3 == From) C3 = To;
2047     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2048   } else if (getOpcode() == Instruction::ShuffleVector) {
2049     Constant *C1 = getOperand(0);
2050     Constant *C2 = getOperand(1);
2051     Constant *C3 = getOperand(2);
2052     if (C1 == From) C1 = To;
2053     if (C2 == From) C2 = To;
2054     if (C3 == From) C3 = To;
2055     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2056   } else if (isCompare()) {
2057     Constant *C1 = getOperand(0);
2058     Constant *C2 = getOperand(1);
2059     if (C1 == From) C1 = To;
2060     if (C2 == From) C2 = To;
2061     if (getOpcode() == Instruction::ICmp)
2062       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2063     else {
2064       assert(getOpcode() == Instruction::FCmp);
2065       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2066     }
2067   } else if (getNumOperands() == 2) {
2068     Constant *C1 = getOperand(0);
2069     Constant *C2 = getOperand(1);
2070     if (C1 == From) C1 = To;
2071     if (C2 == From) C2 = To;
2072     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2073   } else {
2074     llvm_unreachable("Unknown ConstantExpr type!");
2075     return;
2076   }
2077   
2078   assert(Replacement != this && "I didn't contain From!");
2079   
2080   // Everyone using this now uses the replacement.
2081   uncheckedReplaceAllUsesWith(Replacement);
2082   
2083   // Delete the old constant!
2084   destroyConstant();
2085 }
2086