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