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