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