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