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