Provide a getOpcode() method on CmpInst to ensure the opcode is returned
[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) {
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), 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     }
1375   };
1376
1377   template<>
1378   struct ConvertConstantType<ConstantExpr, Type> {
1379     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1380       Constant *New;
1381       switch (OldC->getOpcode()) {
1382       case Instruction::Trunc:
1383       case Instruction::ZExt:
1384       case Instruction::SExt:
1385       case Instruction::FPTrunc:
1386       case Instruction::FPExt:
1387       case Instruction::UIToFP:
1388       case Instruction::SIToFP:
1389       case Instruction::FPToUI:
1390       case Instruction::FPToSI:
1391       case Instruction::PtrToInt:
1392       case Instruction::IntToPtr:
1393       case Instruction::BitCast:
1394         New = ConstantExpr::getCast(
1395             OldC->getOpcode(), OldC->getOperand(0), NewTy);
1396         break;
1397       case Instruction::Select:
1398         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1399                                         OldC->getOperand(1),
1400                                         OldC->getOperand(2));
1401         break;
1402       case Instruction::Shl:
1403       case Instruction::LShr:
1404       case Instruction::AShr:
1405         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1406                                      OldC->getOperand(0), OldC->getOperand(1));
1407         break;
1408       default:
1409         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1410                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1411         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1412                                   OldC->getOperand(1));
1413         break;
1414       case Instruction::GetElementPtr:
1415         // Make everyone now use a constant of the new type...
1416         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1417         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1418         break;
1419       }
1420
1421       assert(New != OldC && "Didn't replace constant??");
1422       OldC->uncheckedReplaceAllUsesWith(New);
1423       OldC->destroyConstant();    // This constant is now dead, destroy it.
1424     }
1425   };
1426 } // end namespace llvm
1427
1428
1429 static ExprMapKeyType getValType(ConstantExpr *CE) {
1430   std::vector<Constant*> Operands;
1431   Operands.reserve(CE->getNumOperands());
1432   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1433     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1434   return ExprMapKeyType(CE->getOpcode(), Operands, 
1435       CE->isCompare() ? CE->getPredicate() : 0);
1436 }
1437
1438 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1439                               ConstantExpr> > ExprConstants;
1440
1441 /// This is a utility function to handle folding of casts and lookup of the
1442 /// cast in the ExprConstants map. It is usedby the various get* methods below.
1443 static inline Constant *getFoldedCast(
1444   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1445   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1446   // Fold a few common cases
1447   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1448     return FC;
1449
1450   // Look up the constant in the table first to ensure uniqueness
1451   std::vector<Constant*> argVec(1, C);
1452   ExprMapKeyType Key(opc, argVec);
1453   return ExprConstants->getOrCreate(Ty, Key);
1454 }
1455  
1456 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1457   Instruction::CastOps opc = Instruction::CastOps(oc);
1458   assert(Instruction::isCast(opc) && "opcode out of range");
1459   assert(C && Ty && "Null arguments to getCast");
1460   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1461
1462   switch (opc) {
1463     default:
1464       assert(0 && "Invalid cast opcode");
1465       break;
1466     case Instruction::Trunc:    return getTrunc(C, Ty);
1467     case Instruction::ZExt:     return getZeroExtend(C, Ty);
1468     case Instruction::SExt:     return getSignExtend(C, Ty);
1469     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1470     case Instruction::FPExt:    return getFPExtend(C, Ty);
1471     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1472     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1473     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1474     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1475     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1476     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1477     case Instruction::BitCast:  return getBitCast(C, Ty);
1478   }
1479   return 0;
1480
1481
1482 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1483   // Note: we can't inline this because it requires the Instructions.h header
1484   return getCast(CastInst::getCastOpcode(
1485         C, C->getType()->isSigned(), Ty, Ty->isSigned()), C, Ty);
1486 }
1487
1488
1489 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1490   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1491     return getCast(Instruction::BitCast, C, Ty);
1492   return getCast(Instruction::ZExt, C, Ty);
1493 }
1494
1495 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1496   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1497     return getCast(Instruction::BitCast, C, Ty);
1498   return getCast(Instruction::SExt, C, Ty);
1499 }
1500
1501 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1502   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1503     return getCast(Instruction::BitCast, C, Ty);
1504   return getCast(Instruction::Trunc, C, Ty);
1505 }
1506
1507 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1508   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1509   assert((Ty->isIntegral() || Ty->getTypeID() == Type::PointerTyID) &&
1510          "Invalid cast");
1511
1512   if (Ty->isIntegral())
1513     return getCast(Instruction::PtrToInt, S, Ty);
1514   return getCast(Instruction::BitCast, S, Ty);
1515 }
1516
1517 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1518   assert(C->getType()->isInteger() && "Trunc operand must be integer");
1519   assert(Ty->isIntegral() && "Trunc produces only integral");
1520   assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1521          "SrcTy must be larger than DestTy for Trunc!");
1522
1523   return getFoldedCast(Instruction::Trunc, C, Ty);
1524 }
1525
1526 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1527   assert(C->getType()->isIntegral() && "SEXt operand must be integral");
1528   assert(Ty->isInteger() && "SExt produces only integer");
1529   assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1530          "SrcTy must be smaller than DestTy for SExt!");
1531
1532   return getFoldedCast(Instruction::SExt, C, Ty);
1533 }
1534
1535 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1536   assert(C->getType()->isIntegral() && "ZEXt operand must be integral");
1537   assert(Ty->isInteger() && "ZExt produces only integer");
1538   assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1539          "SrcTy must be smaller than DestTy for ZExt!");
1540
1541   return getFoldedCast(Instruction::ZExt, C, Ty);
1542 }
1543
1544 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1545   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1546          C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1547          "This is an illegal floating point truncation!");
1548   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1549 }
1550
1551 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1552   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1553          C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1554          "This is an illegal floating point extension!");
1555   return getFoldedCast(Instruction::FPExt, C, Ty);
1556 }
1557
1558 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1559   assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1560          "This is an illegal uint to floating point cast!");
1561   return getFoldedCast(Instruction::UIToFP, C, Ty);
1562 }
1563
1564 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1565   assert(C->getType()->isIntegral() && Ty->isFloatingPoint() &&
1566          "This is an illegal sint to floating point cast!");
1567   return getFoldedCast(Instruction::SIToFP, C, Ty);
1568 }
1569
1570 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1571   assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1572          "This is an illegal floating point to uint cast!");
1573   return getFoldedCast(Instruction::FPToUI, C, Ty);
1574 }
1575
1576 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1577   assert(C->getType()->isFloatingPoint() && Ty->isIntegral() &&
1578          "This is an illegal floating point to sint cast!");
1579   return getFoldedCast(Instruction::FPToSI, C, Ty);
1580 }
1581
1582 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1583   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1584   assert(DstTy->isIntegral() && "PtrToInt destination must be integral");
1585   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1586 }
1587
1588 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1589   assert(C->getType()->isIntegral() && "IntToPtr source must be integral");
1590   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1591   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1592 }
1593
1594 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1595   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1596   // can't cast pointers to anything but pointers.
1597   const Type *SrcTy = C->getType();
1598   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1599          "BitCast cannot cast pointer to non-pointer and vice versa");
1600
1601   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1602   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1603   // destination bit widths are identical.
1604   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1605   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1606   assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1607   return getFoldedCast(Instruction::BitCast, C, DstTy);
1608 }
1609
1610 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1611   // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1612   return getCast(Instruction::PtrToInt, getGetElementPtr(getNullValue(
1613     PointerType::get(Ty)), std::vector<Constant*>(1, 
1614     ConstantInt::get(Type::UIntTy, 1))), Type::ULongTy);
1615 }
1616
1617 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1618   // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1619   static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
1620
1621   return ConstantExpr::getGetElementPtr(C, Indices);
1622 }
1623
1624 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1625                               Constant *C1, Constant *C2) {
1626   if (Opcode == Instruction::Shl || Opcode == Instruction::LShr ||
1627       Opcode == Instruction::AShr)
1628     return getShiftTy(ReqTy, Opcode, C1, C2);
1629
1630   // Check the operands for consistency first
1631   assert(Opcode >= Instruction::BinaryOpsBegin &&
1632          Opcode <  Instruction::BinaryOpsEnd   &&
1633          "Invalid opcode in binary constant expression");
1634   assert(C1->getType() == C2->getType() &&
1635          "Operand types in binary constant expression should match");
1636
1637   if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
1638                                  ReqTy == Type::BoolTy))
1639     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1640       return FC;          // Fold a few common cases...
1641
1642   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1643   ExprMapKeyType Key(Opcode, argVec);
1644   return ExprConstants->getOrCreate(ReqTy, Key);
1645 }
1646
1647 Constant *ConstantExpr::getCompareTy(unsigned Opcode, unsigned short predicate,
1648                                      Constant *C1, Constant *C2) {
1649   if (Opcode == Instruction::ICmp)
1650     return getICmp(predicate, C1, C2);
1651   return getFCmp(predicate, C1, C2);
1652 }
1653
1654 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1655 #ifndef NDEBUG
1656   switch (Opcode) {
1657   case Instruction::Add: 
1658   case Instruction::Sub:
1659   case Instruction::Mul: 
1660     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1661     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1662             isa<PackedType>(C1->getType())) &&
1663            "Tried to create an arithmetic operation on a non-arithmetic type!");
1664     break;
1665   case Instruction::UDiv: 
1666   case Instruction::SDiv: 
1667     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1668     assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1669       cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1670            "Tried to create an arithmetic operation on a non-arithmetic type!");
1671     break;
1672   case Instruction::FDiv:
1673     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1674     assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1675       && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint())) 
1676       && "Tried to create an arithmetic operation on a non-arithmetic type!");
1677     break;
1678   case Instruction::URem: 
1679   case Instruction::SRem: 
1680     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1681     assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1682       cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1683            "Tried to create an arithmetic operation on a non-arithmetic type!");
1684     break;
1685   case Instruction::FRem:
1686     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1687     assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1688       && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint())) 
1689       && "Tried to create an arithmetic operation on a non-arithmetic type!");
1690     break;
1691   case Instruction::And:
1692   case Instruction::Or:
1693   case Instruction::Xor:
1694     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1695     assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1696            "Tried to create a logical operation on a non-integral type!");
1697     break;
1698   case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1699   case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1700     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1701     break;
1702   case Instruction::Shl:
1703   case Instruction::LShr:
1704   case Instruction::AShr:
1705     assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1706     assert(C1->getType()->isInteger() &&
1707            "Tried to create a shift operation on a non-integer type!");
1708     break;
1709   default:
1710     break;
1711   }
1712 #endif
1713
1714   return getTy(C1->getType(), Opcode, C1, C2);
1715 }
1716
1717 Constant *ConstantExpr::getCompare(unsigned Opcode, unsigned short pred, 
1718                             Constant *C1, Constant *C2) {
1719   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1720   return getCompareTy(Opcode, pred, C1, C2);
1721 }
1722
1723 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1724                                     Constant *V1, Constant *V2) {
1725   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1726   assert(V1->getType() == V2->getType() && "Select value types must match!");
1727   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1728
1729   if (ReqTy == V1->getType())
1730     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1731       return SC;        // Fold common cases
1732
1733   std::vector<Constant*> argVec(3, C);
1734   argVec[1] = V1;
1735   argVec[2] = V2;
1736   ExprMapKeyType Key(Instruction::Select, argVec);
1737   return ExprConstants->getOrCreate(ReqTy, Key);
1738 }
1739
1740 /// getShiftTy - Return a shift left or shift right constant expr
1741 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1742                                    Constant *C1, Constant *C2) {
1743   // Check the operands for consistency first
1744   assert((Opcode == Instruction::Shl   ||
1745           Opcode == Instruction::LShr  ||
1746           Opcode == Instruction::AShr) &&
1747          "Invalid opcode in binary constant expression");
1748   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1749          "Invalid operand types for Shift constant expr!");
1750
1751   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1752     return FC;          // Fold a few common cases...
1753
1754   // Look up the constant in the table first to ensure uniqueness
1755   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1756   ExprMapKeyType Key(Opcode, argVec);
1757   return ExprConstants->getOrCreate(ReqTy, Key);
1758 }
1759
1760 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1761                                            const std::vector<Value*> &IdxList) {
1762   assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1763          "GEP indices invalid!");
1764
1765   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1766     return FC;          // Fold a few common cases...
1767
1768   assert(isa<PointerType>(C->getType()) &&
1769          "Non-pointer type for constant GetElementPtr expression");
1770   // Look up the constant in the table first to ensure uniqueness
1771   std::vector<Constant*> ArgVec;
1772   ArgVec.reserve(IdxList.size()+1);
1773   ArgVec.push_back(C);
1774   for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1775     ArgVec.push_back(cast<Constant>(IdxList[i]));
1776   const ExprMapKeyType Key(Instruction::GetElementPtr,ArgVec);
1777   return ExprConstants->getOrCreate(ReqTy, Key);
1778 }
1779
1780 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1781                                          const std::vector<Constant*> &IdxList){
1782   // Get the result type of the getelementptr!
1783   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1784
1785   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1786                                                      true);
1787   assert(Ty && "GEP indices invalid!");
1788   return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1789 }
1790
1791 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1792                                          const std::vector<Value*> &IdxList) {
1793   // Get the result type of the getelementptr!
1794   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1795                                                      true);
1796   assert(Ty && "GEP indices invalid!");
1797   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1798 }
1799
1800 Constant *
1801 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1802   assert(LHS->getType() == RHS->getType());
1803   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1804          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1805
1806   if (Constant *FC = ConstantFoldCompare(Instruction::ICmp, LHS, RHS, pred))
1807     return FC;          // Fold a few common cases...
1808
1809   // Look up the constant in the table first to ensure uniqueness
1810   std::vector<Constant*> ArgVec;
1811   ArgVec.push_back(LHS);
1812   ArgVec.push_back(RHS);
1813   // Fake up an opcode value that encodes both the opcode and predicate
1814   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1815   return ExprConstants->getOrCreate(Type::BoolTy, Key);
1816 }
1817
1818 Constant *
1819 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1820   assert(LHS->getType() == RHS->getType());
1821   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1822
1823   if (Constant *FC = ConstantFoldCompare(Instruction::FCmp, LHS, RHS, pred))
1824     return FC;          // Fold a few common cases...
1825
1826   // Look up the constant in the table first to ensure uniqueness
1827   std::vector<Constant*> ArgVec;
1828   ArgVec.push_back(LHS);
1829   ArgVec.push_back(RHS);
1830   // Fake up an opcode value that encodes both the opcode and predicate
1831   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1832   return ExprConstants->getOrCreate(Type::BoolTy, Key);
1833 }
1834
1835 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1836                                             Constant *Idx) {
1837   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1838     return FC;          // Fold a few common cases...
1839   // Look up the constant in the table first to ensure uniqueness
1840   std::vector<Constant*> ArgVec(1, Val);
1841   ArgVec.push_back(Idx);
1842   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1843   return ExprConstants->getOrCreate(ReqTy, Key);
1844 }
1845
1846 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1847   assert(isa<PackedType>(Val->getType()) &&
1848          "Tried to create extractelement operation on non-packed type!");
1849   assert(Idx->getType() == Type::UIntTy &&
1850          "Extractelement index must be uint type!");
1851   return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1852                              Val, Idx);
1853 }
1854
1855 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1856                                            Constant *Elt, Constant *Idx) {
1857   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1858     return FC;          // Fold a few common cases...
1859   // Look up the constant in the table first to ensure uniqueness
1860   std::vector<Constant*> ArgVec(1, Val);
1861   ArgVec.push_back(Elt);
1862   ArgVec.push_back(Idx);
1863   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1864   return ExprConstants->getOrCreate(ReqTy, Key);
1865 }
1866
1867 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1868                                          Constant *Idx) {
1869   assert(isa<PackedType>(Val->getType()) &&
1870          "Tried to create insertelement operation on non-packed type!");
1871   assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1872          && "Insertelement types must match!");
1873   assert(Idx->getType() == Type::UIntTy &&
1874          "Insertelement index must be uint type!");
1875   return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1876                             Val, Elt, Idx);
1877 }
1878
1879 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1880                                            Constant *V2, Constant *Mask) {
1881   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1882     return FC;          // Fold a few common cases...
1883   // Look up the constant in the table first to ensure uniqueness
1884   std::vector<Constant*> ArgVec(1, V1);
1885   ArgVec.push_back(V2);
1886   ArgVec.push_back(Mask);
1887   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1888   return ExprConstants->getOrCreate(ReqTy, Key);
1889 }
1890
1891 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1892                                          Constant *Mask) {
1893   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1894          "Invalid shuffle vector constant expr operands!");
1895   return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1896 }
1897
1898 // destroyConstant - Remove the constant from the constant table...
1899 //
1900 void ConstantExpr::destroyConstant() {
1901   ExprConstants->remove(this);
1902   destroyConstantImpl();
1903 }
1904
1905 const char *ConstantExpr::getOpcodeName() const {
1906   return Instruction::getOpcodeName(getOpcode());
1907 }
1908
1909 //===----------------------------------------------------------------------===//
1910 //                replaceUsesOfWithOnConstant implementations
1911
1912 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1913                                                 Use *U) {
1914   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1915   Constant *ToC = cast<Constant>(To);
1916
1917   unsigned OperandToUpdate = U-OperandList;
1918   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1919
1920   std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1921   Lookup.first.first = getType();
1922   Lookup.second = this;
1923
1924   std::vector<Constant*> &Values = Lookup.first.second;
1925   Values.reserve(getNumOperands());  // Build replacement array.
1926
1927   // Fill values with the modified operands of the constant array.  Also, 
1928   // compute whether this turns into an all-zeros array.
1929   bool isAllZeros = false;
1930   if (!ToC->isNullValue()) {
1931     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1932       Values.push_back(cast<Constant>(O->get()));
1933   } else {
1934     isAllZeros = true;
1935     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1936       Constant *Val = cast<Constant>(O->get());
1937       Values.push_back(Val);
1938       if (isAllZeros) isAllZeros = Val->isNullValue();
1939     }
1940   }
1941   Values[OperandToUpdate] = ToC;
1942   
1943   Constant *Replacement = 0;
1944   if (isAllZeros) {
1945     Replacement = ConstantAggregateZero::get(getType());
1946   } else {
1947     // Check to see if we have this array type already.
1948     bool Exists;
1949     ArrayConstantsTy::MapTy::iterator I =
1950       ArrayConstants->InsertOrGetItem(Lookup, Exists);
1951     
1952     if (Exists) {
1953       Replacement = I->second;
1954     } else {
1955       // Okay, the new shape doesn't exist in the system yet.  Instead of
1956       // creating a new constant array, inserting it, replaceallusesof'ing the
1957       // old with the new, then deleting the old... just update the current one
1958       // in place!
1959       ArrayConstants->MoveConstantToNewSlot(this, I);
1960       
1961       // Update to the new value.
1962       setOperand(OperandToUpdate, ToC);
1963       return;
1964     }
1965   }
1966  
1967   // Otherwise, I do need to replace this with an existing value.
1968   assert(Replacement != this && "I didn't contain From!");
1969   
1970   // Everyone using this now uses the replacement.
1971   uncheckedReplaceAllUsesWith(Replacement);
1972   
1973   // Delete the old constant!
1974   destroyConstant();
1975 }
1976
1977 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1978                                                  Use *U) {
1979   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1980   Constant *ToC = cast<Constant>(To);
1981
1982   unsigned OperandToUpdate = U-OperandList;
1983   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1984
1985   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1986   Lookup.first.first = getType();
1987   Lookup.second = this;
1988   std::vector<Constant*> &Values = Lookup.first.second;
1989   Values.reserve(getNumOperands());  // Build replacement struct.
1990   
1991   
1992   // Fill values with the modified operands of the constant struct.  Also, 
1993   // compute whether this turns into an all-zeros struct.
1994   bool isAllZeros = false;
1995   if (!ToC->isNullValue()) {
1996     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1997       Values.push_back(cast<Constant>(O->get()));
1998   } else {
1999     isAllZeros = true;
2000     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2001       Constant *Val = cast<Constant>(O->get());
2002       Values.push_back(Val);
2003       if (isAllZeros) isAllZeros = Val->isNullValue();
2004     }
2005   }
2006   Values[OperandToUpdate] = ToC;
2007   
2008   Constant *Replacement = 0;
2009   if (isAllZeros) {
2010     Replacement = ConstantAggregateZero::get(getType());
2011   } else {
2012     // Check to see if we have this array type already.
2013     bool Exists;
2014     StructConstantsTy::MapTy::iterator I =
2015       StructConstants->InsertOrGetItem(Lookup, Exists);
2016     
2017     if (Exists) {
2018       Replacement = I->second;
2019     } else {
2020       // Okay, the new shape doesn't exist in the system yet.  Instead of
2021       // creating a new constant struct, inserting it, replaceallusesof'ing the
2022       // old with the new, then deleting the old... just update the current one
2023       // in place!
2024       StructConstants->MoveConstantToNewSlot(this, I);
2025       
2026       // Update to the new value.
2027       setOperand(OperandToUpdate, ToC);
2028       return;
2029     }
2030   }
2031   
2032   assert(Replacement != this && "I didn't contain From!");
2033   
2034   // Everyone using this now uses the replacement.
2035   uncheckedReplaceAllUsesWith(Replacement);
2036   
2037   // Delete the old constant!
2038   destroyConstant();
2039 }
2040
2041 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
2042                                                  Use *U) {
2043   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2044   
2045   std::vector<Constant*> Values;
2046   Values.reserve(getNumOperands());  // Build replacement array...
2047   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2048     Constant *Val = getOperand(i);
2049     if (Val == From) Val = cast<Constant>(To);
2050     Values.push_back(Val);
2051   }
2052   
2053   Constant *Replacement = ConstantPacked::get(getType(), Values);
2054   assert(Replacement != this && "I didn't contain From!");
2055   
2056   // Everyone using this now uses the replacement.
2057   uncheckedReplaceAllUsesWith(Replacement);
2058   
2059   // Delete the old constant!
2060   destroyConstant();
2061 }
2062
2063 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2064                                                Use *U) {
2065   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2066   Constant *To = cast<Constant>(ToV);
2067   
2068   Constant *Replacement = 0;
2069   if (getOpcode() == Instruction::GetElementPtr) {
2070     std::vector<Constant*> Indices;
2071     Constant *Pointer = getOperand(0);
2072     Indices.reserve(getNumOperands()-1);
2073     if (Pointer == From) Pointer = To;
2074     
2075     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2076       Constant *Val = getOperand(i);
2077       if (Val == From) Val = To;
2078       Indices.push_back(Val);
2079     }
2080     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
2081   } else if (isCast()) {
2082     assert(getOperand(0) == From && "Cast only has one use!");
2083     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2084   } else if (getOpcode() == Instruction::Select) {
2085     Constant *C1 = getOperand(0);
2086     Constant *C2 = getOperand(1);
2087     Constant *C3 = getOperand(2);
2088     if (C1 == From) C1 = To;
2089     if (C2 == From) C2 = To;
2090     if (C3 == From) C3 = To;
2091     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2092   } else if (getOpcode() == Instruction::ExtractElement) {
2093     Constant *C1 = getOperand(0);
2094     Constant *C2 = getOperand(1);
2095     if (C1 == From) C1 = To;
2096     if (C2 == From) C2 = To;
2097     Replacement = ConstantExpr::getExtractElement(C1, C2);
2098   } else if (getOpcode() == Instruction::InsertElement) {
2099     Constant *C1 = getOperand(0);
2100     Constant *C2 = getOperand(1);
2101     Constant *C3 = getOperand(1);
2102     if (C1 == From) C1 = To;
2103     if (C2 == From) C2 = To;
2104     if (C3 == From) C3 = To;
2105     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2106   } else if (getOpcode() == Instruction::ShuffleVector) {
2107     Constant *C1 = getOperand(0);
2108     Constant *C2 = getOperand(1);
2109     Constant *C3 = getOperand(2);
2110     if (C1 == From) C1 = To;
2111     if (C2 == From) C2 = To;
2112     if (C3 == From) C3 = To;
2113     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2114   } else if (isCompare()) {
2115     Constant *C1 = getOperand(0);
2116     Constant *C2 = getOperand(1);
2117     if (C1 == From) C1 = To;
2118     if (C2 == From) C2 = To;
2119     if (getOpcode() == Instruction::ICmp)
2120       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2121     else
2122       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2123   } else if (getNumOperands() == 2) {
2124     Constant *C1 = getOperand(0);
2125     Constant *C2 = getOperand(1);
2126     if (C1 == From) C1 = To;
2127     if (C2 == From) C2 = To;
2128     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2129   } else {
2130     assert(0 && "Unknown ConstantExpr type!");
2131     return;
2132   }
2133   
2134   assert(Replacement != this && "I didn't contain From!");
2135   
2136   // Everyone using this now uses the replacement.
2137   uncheckedReplaceAllUsesWith(Replacement);
2138   
2139   // Delete the old constant!
2140   destroyConstant();
2141 }
2142
2143
2144 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2145 /// global into a string value.  Return an empty string if we can't do it.
2146 /// Parameter Chop determines if the result is chopped at the first null
2147 /// terminator.
2148 ///
2149 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2150   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2151     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2152       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2153       if (Init->isString()) {
2154         std::string Result = Init->getAsString();
2155         if (Offset < Result.size()) {
2156           // If we are pointing INTO The string, erase the beginning...
2157           Result.erase(Result.begin(), Result.begin()+Offset);
2158
2159           // Take off the null terminator, and any string fragments after it.
2160           if (Chop) {
2161             std::string::size_type NullPos = Result.find_first_of((char)0);
2162             if (NullPos != std::string::npos)
2163               Result.erase(Result.begin()+NullPos, Result.end());
2164           }
2165           return Result;
2166         }
2167       }
2168     }
2169   } else if (Constant *C = dyn_cast<Constant>(this)) {
2170     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
2171       return GV->getStringValue(Chop, Offset);
2172     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2173       if (CE->getOpcode() == Instruction::GetElementPtr) {
2174         // Turn a gep into the specified offset.
2175         if (CE->getNumOperands() == 3 &&
2176             cast<Constant>(CE->getOperand(1))->isNullValue() &&
2177             isa<ConstantInt>(CE->getOperand(2))) {
2178           Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2179           return CE->getOperand(0)->getStringValue(Chop, Offset);
2180         }
2181       }
2182     }
2183   }
2184   return "";
2185 }
2186