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