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