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