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