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