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