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