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