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