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