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