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