minor microoptimizations
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/MathExtras.h"
23 #include <algorithm>
24 #include <iostream>
25 using namespace llvm;
26
27 ConstantBool *ConstantBool::True  = new ConstantBool(true);
28 ConstantBool *ConstantBool::False = new ConstantBool(false);
29
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       std::cerr << "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 // Static constructor to create a '0' constant of arbitrary type...
64 Constant *Constant::getNullValue(const Type *Ty) {
65   switch (Ty->getTypeID()) {
66   case Type::BoolTyID: {
67     static Constant *NullBool = ConstantBool::get(false);
68     return NullBool;
69   }
70   case Type::SByteTyID: {
71     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
72     return NullSByte;
73   }
74   case Type::UByteTyID: {
75     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
76     return NullUByte;
77   }
78   case Type::ShortTyID: {
79     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
80     return NullShort;
81   }
82   case Type::UShortTyID: {
83     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
84     return NullUShort;
85   }
86   case Type::IntTyID: {
87     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
88     return NullInt;
89   }
90   case Type::UIntTyID: {
91     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
92     return NullUInt;
93   }
94   case Type::LongTyID: {
95     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
96     return NullLong;
97   }
98   case Type::ULongTyID: {
99     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
100     return NullULong;
101   }
102
103   case Type::FloatTyID: {
104     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
105     return NullFloat;
106   }
107   case Type::DoubleTyID: {
108     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
109     return NullDouble;
110   }
111
112   case Type::PointerTyID:
113     return ConstantPointerNull::get(cast<PointerType>(Ty));
114
115   case Type::StructTyID:
116   case Type::ArrayTyID:
117   case Type::PackedTyID:
118     return ConstantAggregateZero::get(Ty);
119   default:
120     // Function, Label, or Opaque type?
121     assert(!"Cannot create a null constant of that type!");
122     return 0;
123   }
124 }
125
126 // Static constructor to create the maximum constant of an integral type...
127 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
128   switch (Ty->getTypeID()) {
129   case Type::BoolTyID:   return ConstantBool::True;
130   case Type::SByteTyID:
131   case Type::ShortTyID:
132   case Type::IntTyID:
133   case Type::LongTyID: {
134     // Calculate 011111111111111...
135     unsigned TypeBits = Ty->getPrimitiveSize()*8;
136     int64_t Val = INT64_MAX;             // All ones
137     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
138     return ConstantSInt::get(Ty, Val);
139   }
140
141   case Type::UByteTyID:
142   case Type::UShortTyID:
143   case Type::UIntTyID:
144   case Type::ULongTyID:  return getAllOnesValue(Ty);
145
146   default: return 0;
147   }
148 }
149
150 // Static constructor to create the minimum constant for an integral type...
151 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
152   switch (Ty->getTypeID()) {
153   case Type::BoolTyID:   return ConstantBool::False;
154   case Type::SByteTyID:
155   case Type::ShortTyID:
156   case Type::IntTyID:
157   case Type::LongTyID: {
158      // Calculate 1111111111000000000000
159      unsigned TypeBits = Ty->getPrimitiveSize()*8;
160      int64_t Val = -1;                    // All ones
161      Val <<= TypeBits-1;                  // Shift over to the right spot
162      return ConstantSInt::get(Ty, Val);
163   }
164
165   case Type::UByteTyID:
166   case Type::UShortTyID:
167   case Type::UIntTyID:
168   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
169
170   default: return 0;
171   }
172 }
173
174 // Static constructor to create an integral constant with all bits set
175 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
176   switch (Ty->getTypeID()) {
177   case Type::BoolTyID:   return ConstantBool::True;
178   case Type::SByteTyID:
179   case Type::ShortTyID:
180   case Type::IntTyID:
181   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
182
183   case Type::UByteTyID:
184   case Type::UShortTyID:
185   case Type::UIntTyID:
186   case Type::ULongTyID: {
187     // Calculate ~0 of the right type...
188     unsigned TypeBits = Ty->getPrimitiveSize()*8;
189     uint64_t Val = ~0ULL;                // All ones
190     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
191     return ConstantUInt::get(Ty, Val);
192   }
193   default: return 0;
194   }
195 }
196
197 bool ConstantUInt::isAllOnesValue() const {
198   unsigned TypeBits = getType()->getPrimitiveSize()*8;
199   uint64_t Val = ~0ULL;                // All ones
200   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
201   return getValue() == Val;
202 }
203
204
205 //===----------------------------------------------------------------------===//
206 //                            ConstantXXX Classes
207 //===----------------------------------------------------------------------===//
208
209 //===----------------------------------------------------------------------===//
210 //                             Normal Constructors
211
212 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
213   : Constant(Ty, VT, 0, 0) {
214     Val.Unsigned = V;
215 }
216
217 ConstantBool::ConstantBool(bool V) 
218   : ConstantIntegral(Type::BoolTy, ConstantBoolVal, V) {
219 }
220
221 ConstantInt::ConstantInt(const Type *Ty, ValueTy VT, uint64_t V)
222   : ConstantIntegral(Ty, VT, V) {
223 }
224
225 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V)
226   : ConstantInt(Ty, ConstantSIntVal, V) {
227   assert(Ty->isInteger() && Ty->isSigned() &&
228          "Illegal type for signed integer constant!");
229   assert(isValueValidForType(Ty, V) && "Value too large for type!");
230 }
231
232 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V)
233   : ConstantInt(Ty, ConstantUIntVal, V) {
234   assert(Ty->isInteger() && Ty->isUnsigned() &&
235          "Illegal type for unsigned integer constant!");
236   assert(isValueValidForType(Ty, V) && "Value too large for type!");
237 }
238
239 ConstantFP::ConstantFP(const Type *Ty, double V)
240   : Constant(Ty, ConstantFPVal, 0, 0) {
241   assert(isValueValidForType(Ty, V) && "Value too large for type!");
242   Val = V;
243 }
244
245 ConstantArray::ConstantArray(const ArrayType *T,
246                              const std::vector<Constant*> &V)
247   : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
248   assert(V.size() == T->getNumElements() &&
249          "Invalid initializer vector for constant array");
250   Use *OL = OperandList;
251   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
252        I != E; ++I, ++OL) {
253     Constant *E = *I;
254     assert((E->getType() == T->getElementType() ||
255             (T->isAbstract() &&
256              E->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
257            "Initializer for array element doesn't match array element type!");
258     OL->init(E, this);
259   }
260 }
261
262 ConstantArray::~ConstantArray() {
263   delete [] OperandList;
264 }
265
266 ConstantStruct::ConstantStruct(const StructType *T,
267                                const std::vector<Constant*> &V)
268   : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
269   assert(V.size() == T->getNumElements() &&
270          "Invalid initializer vector for constant structure");
271   Use *OL = OperandList;
272   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
273        I != E; ++I, ++OL) {
274     Constant *E = *I;
275     assert((E->getType() == T->getElementType(I-V.begin()) ||
276             ((T->getElementType(I-V.begin())->isAbstract() ||
277               E->getType()->isAbstract()) &&
278              T->getElementType(I-V.begin())->getTypeID() == 
279                    E->getType()->getTypeID())) &&
280            "Initializer for struct element doesn't match struct element type!");
281     OL->init(E, this);
282   }
283 }
284
285 ConstantStruct::~ConstantStruct() {
286   delete [] OperandList;
287 }
288
289
290 ConstantPacked::ConstantPacked(const PackedType *T,
291                                const std::vector<Constant*> &V)
292   : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
293   Use *OL = OperandList;
294     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
295          I != E; ++I, ++OL) {
296       Constant *E = *I;
297       assert((E->getType() == T->getElementType() ||
298             (T->isAbstract() &&
299              E->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
300            "Initializer for packed element doesn't match packed element type!");
301     OL->init(E, this);
302   }
303 }
304
305 ConstantPacked::~ConstantPacked() {
306   delete [] OperandList;
307 }
308
309 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
310 /// behind the scenes to implement unary constant exprs.
311 class UnaryConstantExpr : public ConstantExpr {
312   Use Op;
313 public:
314   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
315     : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
316 };
317
318 static bool isSetCC(unsigned Opcode) {
319   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
320          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
321          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
322 }
323
324 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
325 /// behind the scenes to implement binary constant exprs.
326 class BinaryConstantExpr : public ConstantExpr {
327   Use Ops[2];
328 public:
329   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
330     : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
331                    Opcode, Ops, 2) {
332     Ops[0].init(C1, this);
333     Ops[1].init(C2, this);
334   }
335 };
336
337 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
338 /// behind the scenes to implement select constant exprs.
339 class SelectConstantExpr : public ConstantExpr {
340   Use Ops[3];
341 public:
342   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
343     : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
344     Ops[0].init(C1, this);
345     Ops[1].init(C2, this);
346     Ops[2].init(C3, this);
347   }
348 };
349
350 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
351 /// used behind the scenes to implement getelementpr constant exprs.
352 struct GetElementPtrConstantExpr : public ConstantExpr {
353   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
354                             const Type *DestTy)
355     : ConstantExpr(DestTy, Instruction::GetElementPtr,
356                    new Use[IdxList.size()+1], IdxList.size()+1) {
357     OperandList[0].init(C, this);
358     for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
359       OperandList[i+1].init(IdxList[i], this);
360   }
361   ~GetElementPtrConstantExpr() {
362     delete [] OperandList;
363   }
364 };
365
366 /// ConstantExpr::get* - Return some common constants without having to
367 /// specify the full Instruction::OPCODE identifier.
368 ///
369 Constant *ConstantExpr::getNeg(Constant *C) {
370   if (!C->getType()->isFloatingPoint())
371     return get(Instruction::Sub, getNullValue(C->getType()), C);
372   else
373     return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
374 }
375 Constant *ConstantExpr::getNot(Constant *C) {
376   assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
377   return get(Instruction::Xor, C,
378              ConstantIntegral::getAllOnesValue(C->getType()));
379 }
380 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
381   return get(Instruction::Add, C1, C2);
382 }
383 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
384   return get(Instruction::Sub, C1, C2);
385 }
386 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
387   return get(Instruction::Mul, C1, C2);
388 }
389 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
390   return get(Instruction::Div, C1, C2);
391 }
392 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
393   return get(Instruction::Rem, C1, C2);
394 }
395 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
396   return get(Instruction::And, C1, C2);
397 }
398 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
399   return get(Instruction::Or, C1, C2);
400 }
401 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
402   return get(Instruction::Xor, C1, C2);
403 }
404 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
405   return get(Instruction::SetEQ, C1, C2);
406 }
407 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
408   return get(Instruction::SetNE, C1, C2);
409 }
410 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
411   return get(Instruction::SetLT, C1, C2);
412 }
413 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
414   return get(Instruction::SetGT, C1, C2);
415 }
416 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
417   return get(Instruction::SetLE, C1, C2);
418 }
419 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
420   return get(Instruction::SetGE, C1, C2);
421 }
422 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
423   return get(Instruction::Shl, C1, C2);
424 }
425 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
426   return get(Instruction::Shr, C1, C2);
427 }
428
429 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
430   if (C1->getType()->isUnsigned()) return getShr(C1, C2);
431   return getCast(getShr(getCast(C1,
432                     C1->getType()->getUnsignedVersion()), C2), C1->getType());
433 }
434
435 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
436   if (C1->getType()->isSigned()) return getShr(C1, C2);
437   return getCast(getShr(getCast(C1,
438                         C1->getType()->getSignedVersion()), C2), C1->getType());
439 }
440
441
442 //===----------------------------------------------------------------------===//
443 //                      isValueValidForType implementations
444
445 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
446   switch (Ty->getTypeID()) {
447   default:
448     return false;         // These can't be represented as integers!!!
449     // Signed types...
450   case Type::SByteTyID:
451     return (Val <= INT8_MAX && Val >= INT8_MIN);
452   case Type::ShortTyID:
453     return (Val <= INT16_MAX && Val >= INT16_MIN);
454   case Type::IntTyID:
455     return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
456   case Type::LongTyID:
457     return true;          // This is the largest type...
458   }
459 }
460
461 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
462   switch (Ty->getTypeID()) {
463   default:
464     return false;         // These can't be represented as integers!!!
465
466     // Unsigned types...
467   case Type::UByteTyID:
468     return (Val <= UINT8_MAX);
469   case Type::UShortTyID:
470     return (Val <= UINT16_MAX);
471   case Type::UIntTyID:
472     return (Val <= UINT32_MAX);
473   case Type::ULongTyID:
474     return true;          // This is the largest type...
475   }
476 }
477
478 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
479   switch (Ty->getTypeID()) {
480   default:
481     return false;         // These can't be represented as floating point!
482
483     // TODO: Figure out how to test if a double can be cast to a float!
484   case Type::FloatTyID:
485   case Type::DoubleTyID:
486     return true;          // This is the largest type...
487   }
488 };
489
490 //===----------------------------------------------------------------------===//
491 //                replaceUsesOfWithOnConstant implementations
492
493 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
494                                                 bool DisableChecking) {
495   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
496
497   std::vector<Constant*> Values;
498   Values.reserve(getNumOperands());  // Build replacement array...
499   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
500     Constant *Val = getOperand(i);
501     if (Val == From) Val = cast<Constant>(To);
502     Values.push_back(Val);
503   }
504
505   Constant *Replacement = ConstantArray::get(getType(), Values);
506   assert(Replacement != this && "I didn't contain From!");
507
508   // Everyone using this now uses the replacement...
509   if (DisableChecking)
510     uncheckedReplaceAllUsesWith(Replacement);
511   else
512     replaceAllUsesWith(Replacement);
513
514   // Delete the old constant!
515   destroyConstant();
516 }
517
518 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
519                                                  bool DisableChecking) {
520   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
521
522   std::vector<Constant*> Values;
523   Values.reserve(getNumOperands());  // Build replacement array...
524   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
525     Constant *Val = getOperand(i);
526     if (Val == From) Val = cast<Constant>(To);
527     Values.push_back(Val);
528   }
529
530   Constant *Replacement = ConstantStruct::get(getType(), Values);
531   assert(Replacement != this && "I didn't contain From!");
532
533   // Everyone using this now uses the replacement...
534   if (DisableChecking)
535     uncheckedReplaceAllUsesWith(Replacement);
536   else
537     replaceAllUsesWith(Replacement);
538
539   // Delete the old constant!
540   destroyConstant();
541 }
542
543 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
544                                                  bool DisableChecking) {
545   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
546
547   std::vector<Constant*> Values;
548   Values.reserve(getNumOperands());  // Build replacement array...
549   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
550     Constant *Val = getOperand(i);
551     if (Val == From) Val = cast<Constant>(To);
552     Values.push_back(Val);
553   }
554
555   Constant *Replacement = ConstantPacked::get(getType(), Values);
556   assert(Replacement != this && "I didn't contain From!");
557
558   // Everyone using this now uses the replacement...
559   if (DisableChecking)
560     uncheckedReplaceAllUsesWith(Replacement);
561   else
562     replaceAllUsesWith(Replacement);
563
564   // Delete the old constant!
565   destroyConstant();
566 }
567
568 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
569                                                bool DisableChecking) {
570   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
571   Constant *To = cast<Constant>(ToV);
572
573   Constant *Replacement = 0;
574   if (getOpcode() == Instruction::GetElementPtr) {
575     std::vector<Constant*> Indices;
576     Constant *Pointer = getOperand(0);
577     Indices.reserve(getNumOperands()-1);
578     if (Pointer == From) Pointer = To;
579
580     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
581       Constant *Val = getOperand(i);
582       if (Val == From) Val = To;
583       Indices.push_back(Val);
584     }
585     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
586   } else if (getOpcode() == Instruction::Cast) {
587     assert(getOperand(0) == From && "Cast only has one use!");
588     Replacement = ConstantExpr::getCast(To, getType());
589   } else if (getOpcode() == Instruction::Select) {
590     Constant *C1 = getOperand(0);
591     Constant *C2 = getOperand(1);
592     Constant *C3 = getOperand(2);
593     if (C1 == From) C1 = To;
594     if (C2 == From) C2 = To;
595     if (C3 == From) C3 = To;
596     Replacement = ConstantExpr::getSelect(C1, C2, C3);
597   } else if (getNumOperands() == 2) {
598     Constant *C1 = getOperand(0);
599     Constant *C2 = getOperand(1);
600     if (C1 == From) C1 = To;
601     if (C2 == From) C2 = To;
602     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
603   } else {
604     assert(0 && "Unknown ConstantExpr type!");
605     return;
606   }
607
608   assert(Replacement != this && "I didn't contain From!");
609
610   // Everyone using this now uses the replacement...
611   if (DisableChecking)
612     uncheckedReplaceAllUsesWith(Replacement);
613   else
614     replaceAllUsesWith(Replacement);
615
616   // Delete the old constant!
617   destroyConstant();
618 }
619
620 //===----------------------------------------------------------------------===//
621 //                      Factory Function Implementation
622
623 // ConstantCreator - A class that is used to create constants by
624 // ValueMap*.  This class should be partially specialized if there is
625 // something strange that needs to be done to interface to the ctor for the
626 // constant.
627 //
628 namespace llvm {
629   template<class ConstantClass, class TypeClass, class ValType>
630   struct ConstantCreator {
631     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
632       return new ConstantClass(Ty, V);
633     }
634   };
635
636   template<class ConstantClass, class TypeClass>
637   struct ConvertConstantType {
638     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
639       assert(0 && "This type cannot be converted!\n");
640       abort();
641     }
642   };
643 }
644
645 namespace {
646   template<class ValType, class TypeClass, class ConstantClass>
647   class ValueMap : public AbstractTypeUser {
648     typedef std::pair<const TypeClass*, ValType> MapKey;
649     typedef std::map<MapKey, ConstantClass *> MapTy;
650     typedef typename MapTy::iterator MapIterator;
651     MapTy Map;
652
653     typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
654     AbstractTypeMapTy AbstractTypeMap;
655
656     friend void Constant::clearAllValueMaps();
657   private:
658     void clear(std::vector<Constant *> &Constants) {
659       for(MapIterator I = Map.begin(); I != Map.end(); ++I)
660         Constants.push_back(I->second);
661       Map.clear();
662       AbstractTypeMap.clear();
663     }
664
665   public:
666     // getOrCreate - Return the specified constant from the map, creating it if
667     // necessary.
668     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
669       MapKey Lookup(Ty, V);
670       MapIterator I = Map.lower_bound(Lookup);
671       if (I != Map.end() && I->first == Lookup)
672         return I->second;  // Is it in the map?
673
674       // If no preexisting value, create one now...
675       ConstantClass *Result =
676         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
677
678
679       /// FIXME: why does this assert fail when loading 176.gcc?
680       //assert(Result->getType() == Ty && "Type specified is not correct!");
681       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
682
683       // If the type of the constant is abstract, make sure that an entry exists
684       // for it in the AbstractTypeMap.
685       if (Ty->isAbstract()) {
686         typename AbstractTypeMapTy::iterator TI =
687           AbstractTypeMap.lower_bound(Ty);
688
689         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
690           // Add ourselves to the ATU list of the type.
691           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
692
693           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
694         }
695       }
696       return Result;
697     }
698
699     void remove(ConstantClass *CP) {
700       MapIterator I = Map.find(MapKey((TypeClass*)CP->getRawType(),
701                                       getValType(CP)));
702       if (I == Map.end() || I->second != CP) {
703         // FIXME: This should not use a linear scan.  If this gets to be a
704         // performance problem, someone should look at this.
705         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
706           /* empty */;
707       }
708
709       assert(I != Map.end() && "Constant not found in constant table!");
710       assert(I->second == CP && "Didn't find correct element?");
711
712       // Now that we found the entry, make sure this isn't the entry that
713       // the AbstractTypeMap points to.
714       const TypeClass *Ty = I->first.first;
715       if (Ty->isAbstract()) {
716         assert(AbstractTypeMap.count(Ty) &&
717                "Abstract type not in AbstractTypeMap?");
718         MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
719         if (ATMEntryIt == I) {
720           // Yes, we are removing the representative entry for this type.
721           // See if there are any other entries of the same type.
722           MapIterator TmpIt = ATMEntryIt;
723
724           // First check the entry before this one...
725           if (TmpIt != Map.begin()) {
726             --TmpIt;
727             if (TmpIt->first.first != Ty) // Not the same type, move back...
728               ++TmpIt;
729           }
730
731           // If we didn't find the same type, try to move forward...
732           if (TmpIt == ATMEntryIt) {
733             ++TmpIt;
734             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
735               --TmpIt;   // No entry afterwards with the same type
736           }
737
738           // If there is another entry in the map of the same abstract type,
739           // update the AbstractTypeMap entry now.
740           if (TmpIt != ATMEntryIt) {
741             ATMEntryIt = TmpIt;
742           } else {
743             // Otherwise, we are removing the last instance of this type
744             // from the table.  Remove from the ATM, and from user list.
745             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
746             AbstractTypeMap.erase(Ty);
747           }
748         }
749       }
750
751       Map.erase(I);
752     }
753
754     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
755       typename AbstractTypeMapTy::iterator I =
756         AbstractTypeMap.find(cast<TypeClass>(OldTy));
757
758       assert(I != AbstractTypeMap.end() &&
759              "Abstract type not in AbstractTypeMap?");
760
761       // Convert a constant at a time until the last one is gone.  The last one
762       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
763       // eliminated eventually.
764       do {
765         ConvertConstantType<ConstantClass,
766                             TypeClass>::convert(I->second->second,
767                                                 cast<TypeClass>(NewTy));
768
769         I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
770       } while (I != AbstractTypeMap.end());
771     }
772
773     // If the type became concrete without being refined to any other existing
774     // type, we just remove ourselves from the ATU list.
775     void typeBecameConcrete(const DerivedType *AbsTy) {
776       AbsTy->removeAbstractTypeUser(this);
777     }
778
779     void dump() const {
780       std::cerr << "Constant.cpp: ValueMap\n";
781     }
782   };
783 }
784
785 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
786 //
787 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
788 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
789
790 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
791   return SIntConstants.getOrCreate(Ty, V);
792 }
793
794 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
795   return UIntConstants.getOrCreate(Ty, V);
796 }
797
798 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
799   assert(V <= 127 && "Can only be used with very small positive constants!");
800   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
801   return ConstantUInt::get(Ty, V);
802 }
803
804 //---- ConstantFP::get() implementation...
805 //
806 namespace llvm {
807   template<>
808   struct ConstantCreator<ConstantFP, Type, uint64_t> {
809     static ConstantFP *create(const Type *Ty, uint64_t V) {
810       assert(Ty == Type::DoubleTy);
811       return new ConstantFP(Ty, BitsToDouble(V));
812     }
813   };
814   template<>
815   struct ConstantCreator<ConstantFP, Type, uint32_t> {
816     static ConstantFP *create(const Type *Ty, uint32_t V) {
817       assert(Ty == Type::FloatTy);
818       return new ConstantFP(Ty, BitsToFloat(V));
819     }
820   };
821 }
822
823 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
824 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
825
826 bool ConstantFP::isNullValue() const {
827   return DoubleToBits(Val) == 0;
828 }
829
830 bool ConstantFP::isExactlyValue(double V) const {
831   return DoubleToBits(V) == DoubleToBits(Val);
832 }
833
834
835 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
836   if (Ty == Type::FloatTy) {
837     // Force the value through memory to normalize it.
838     return FloatConstants.getOrCreate(Ty, FloatToBits(V));
839   } else {
840     assert(Ty == Type::DoubleTy);
841     return DoubleConstants.getOrCreate(Ty, DoubleToBits(V));
842   }
843 }
844
845 //---- ConstantAggregateZero::get() implementation...
846 //
847 namespace llvm {
848   // ConstantAggregateZero does not take extra "value" argument...
849   template<class ValType>
850   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
851     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
852       return new ConstantAggregateZero(Ty);
853     }
854   };
855
856   template<>
857   struct ConvertConstantType<ConstantAggregateZero, Type> {
858     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
859       // Make everyone now use a constant of the new type...
860       Constant *New = ConstantAggregateZero::get(NewTy);
861       assert(New != OldC && "Didn't replace constant??");
862       OldC->uncheckedReplaceAllUsesWith(New);
863       OldC->destroyConstant();     // This constant is now dead, destroy it.
864     }
865   };
866 }
867
868 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
869
870 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
871
872 Constant *ConstantAggregateZero::get(const Type *Ty) {
873   return AggZeroConstants.getOrCreate(Ty, 0);
874 }
875
876 // destroyConstant - Remove the constant from the constant table...
877 //
878 void ConstantAggregateZero::destroyConstant() {
879   AggZeroConstants.remove(this);
880   destroyConstantImpl();
881 }
882
883 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
884                                                         bool DisableChecking) {
885   assert(0 && "No uses!");
886   abort();
887 }
888
889
890
891 //---- ConstantArray::get() implementation...
892 //
893 namespace llvm {
894   template<>
895   struct ConvertConstantType<ConstantArray, ArrayType> {
896     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
897       // Make everyone now use a constant of the new type...
898       std::vector<Constant*> C;
899       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
900         C.push_back(cast<Constant>(OldC->getOperand(i)));
901       Constant *New = ConstantArray::get(NewTy, C);
902       assert(New != OldC && "Didn't replace constant??");
903       OldC->uncheckedReplaceAllUsesWith(New);
904       OldC->destroyConstant();    // This constant is now dead, destroy it.
905     }
906   };
907 }
908
909 static std::vector<Constant*> getValType(ConstantArray *CA) {
910   std::vector<Constant*> Elements;
911   Elements.reserve(CA->getNumOperands());
912   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
913     Elements.push_back(cast<Constant>(CA->getOperand(i)));
914   return Elements;
915 }
916
917 static ValueMap<std::vector<Constant*>, ArrayType,
918                 ConstantArray> ArrayConstants;
919
920 Constant *ConstantArray::get(const ArrayType *Ty,
921                              const std::vector<Constant*> &V) {
922   // If this is an all-zero array, return a ConstantAggregateZero object
923   if (!V.empty()) {
924     Constant *C = V[0];
925     if (!C->isNullValue())
926       return ArrayConstants.getOrCreate(Ty, V);
927     for (unsigned i = 1, e = V.size(); i != e; ++i)
928       if (V[i] != C)
929         return ArrayConstants.getOrCreate(Ty, V);
930   }
931   return ConstantAggregateZero::get(Ty);
932 }
933
934 // destroyConstant - Remove the constant from the constant table...
935 //
936 void ConstantArray::destroyConstant() {
937   ArrayConstants.remove(this);
938   destroyConstantImpl();
939 }
940
941 // ConstantArray::get(const string&) - Return an array that is initialized to
942 // contain the specified string.  A null terminator is added to the specified
943 // string so that it may be used in a natural way...
944 //
945 Constant *ConstantArray::get(const std::string &Str) {
946   std::vector<Constant*> ElementVals;
947
948   for (unsigned i = 0; i < Str.length(); ++i)
949     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
950
951   // Add a null terminator to the string...
952   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
953
954   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
955   return ConstantArray::get(ATy, ElementVals);
956 }
957
958 /// isString - This method returns true if the array is an array of sbyte or
959 /// ubyte, and if the elements of the array are all ConstantInt's.
960 bool ConstantArray::isString() const {
961   // Check the element type for sbyte or ubyte...
962   if (getType()->getElementType() != Type::UByteTy &&
963       getType()->getElementType() != Type::SByteTy)
964     return false;
965   // Check the elements to make sure they are all integers, not constant
966   // expressions.
967   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
968     if (!isa<ConstantInt>(getOperand(i)))
969       return false;
970   return true;
971 }
972
973 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
974 // then this method converts the array to an std::string and returns it.
975 // Otherwise, it asserts out.
976 //
977 std::string ConstantArray::getAsString() const {
978   assert(isString() && "Not a string!");
979   std::string Result;
980   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
981     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
982   return Result;
983 }
984
985
986 //---- ConstantStruct::get() implementation...
987 //
988
989 namespace llvm {
990   template<>
991   struct ConvertConstantType<ConstantStruct, StructType> {
992     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
993       // Make everyone now use a constant of the new type...
994       std::vector<Constant*> C;
995       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
996         C.push_back(cast<Constant>(OldC->getOperand(i)));
997       Constant *New = ConstantStruct::get(NewTy, C);
998       assert(New != OldC && "Didn't replace constant??");
999
1000       OldC->uncheckedReplaceAllUsesWith(New);
1001       OldC->destroyConstant();    // This constant is now dead, destroy it.
1002     }
1003   };
1004 }
1005
1006 static ValueMap<std::vector<Constant*>, StructType,
1007                 ConstantStruct> StructConstants;
1008
1009 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1010   std::vector<Constant*> Elements;
1011   Elements.reserve(CS->getNumOperands());
1012   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1013     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1014   return Elements;
1015 }
1016
1017 Constant *ConstantStruct::get(const StructType *Ty,
1018                               const std::vector<Constant*> &V) {
1019   // Create a ConstantAggregateZero value if all elements are zeros...
1020   for (unsigned i = 0, e = V.size(); i != e; ++i)
1021     if (!V[i]->isNullValue())
1022       return StructConstants.getOrCreate(Ty, V);
1023
1024   return ConstantAggregateZero::get(Ty);
1025 }
1026
1027 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1028   std::vector<const Type*> StructEls;
1029   StructEls.reserve(V.size());
1030   for (unsigned i = 0, e = V.size(); i != e; ++i)
1031     StructEls.push_back(V[i]->getType());
1032   return get(StructType::get(StructEls), V);
1033 }
1034
1035 // destroyConstant - Remove the constant from the constant table...
1036 //
1037 void ConstantStruct::destroyConstant() {
1038   StructConstants.remove(this);
1039   destroyConstantImpl();
1040 }
1041
1042 //---- ConstantPacked::get() implementation...
1043 //
1044 namespace llvm {
1045   template<>
1046   struct ConvertConstantType<ConstantPacked, PackedType> {
1047     static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1048       // Make everyone now use a constant of the new type...
1049       std::vector<Constant*> C;
1050       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1051         C.push_back(cast<Constant>(OldC->getOperand(i)));
1052       Constant *New = ConstantPacked::get(NewTy, C);
1053       assert(New != OldC && "Didn't replace constant??");
1054       OldC->uncheckedReplaceAllUsesWith(New);
1055       OldC->destroyConstant();    // This constant is now dead, destroy it.
1056     }
1057   };
1058 }
1059
1060 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1061   std::vector<Constant*> Elements;
1062   Elements.reserve(CP->getNumOperands());
1063   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1064     Elements.push_back(CP->getOperand(i));
1065   return Elements;
1066 }
1067
1068 static ValueMap<std::vector<Constant*>, PackedType,
1069                 ConstantPacked> PackedConstants;
1070
1071 Constant *ConstantPacked::get(const PackedType *Ty,
1072                               const std::vector<Constant*> &V) {
1073   // If this is an all-zero packed, return a ConstantAggregateZero object
1074   if (!V.empty()) {
1075     Constant *C = V[0];
1076     if (!C->isNullValue())
1077       return PackedConstants.getOrCreate(Ty, V);
1078     for (unsigned i = 1, e = V.size(); i != e; ++i)
1079       if (V[i] != C)
1080         return PackedConstants.getOrCreate(Ty, V);
1081   }
1082   return ConstantAggregateZero::get(Ty);
1083 }
1084
1085 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1086   assert(!V.empty() && "Cannot infer type if V is empty");
1087   return get(PackedType::get(V.front()->getType(),V.size()), V);
1088 }
1089
1090 // destroyConstant - Remove the constant from the constant table...
1091 //
1092 void ConstantPacked::destroyConstant() {
1093   PackedConstants.remove(this);
1094   destroyConstantImpl();
1095 }
1096
1097 //---- ConstantPointerNull::get() implementation...
1098 //
1099
1100 namespace llvm {
1101   // ConstantPointerNull does not take extra "value" argument...
1102   template<class ValType>
1103   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1104     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1105       return new ConstantPointerNull(Ty);
1106     }
1107   };
1108
1109   template<>
1110   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1111     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1112       // Make everyone now use a constant of the new type...
1113       Constant *New = ConstantPointerNull::get(NewTy);
1114       assert(New != OldC && "Didn't replace constant??");
1115       OldC->uncheckedReplaceAllUsesWith(New);
1116       OldC->destroyConstant();     // This constant is now dead, destroy it.
1117     }
1118   };
1119 }
1120
1121 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1122
1123 static char getValType(ConstantPointerNull *) {
1124   return 0;
1125 }
1126
1127
1128 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1129   return NullPtrConstants.getOrCreate(Ty, 0);
1130 }
1131
1132 // destroyConstant - Remove the constant from the constant table...
1133 //
1134 void ConstantPointerNull::destroyConstant() {
1135   NullPtrConstants.remove(this);
1136   destroyConstantImpl();
1137 }
1138
1139
1140 //---- UndefValue::get() implementation...
1141 //
1142
1143 namespace llvm {
1144   // UndefValue does not take extra "value" argument...
1145   template<class ValType>
1146   struct ConstantCreator<UndefValue, Type, ValType> {
1147     static UndefValue *create(const Type *Ty, const ValType &V) {
1148       return new UndefValue(Ty);
1149     }
1150   };
1151
1152   template<>
1153   struct ConvertConstantType<UndefValue, Type> {
1154     static void convert(UndefValue *OldC, const Type *NewTy) {
1155       // Make everyone now use a constant of the new type.
1156       Constant *New = UndefValue::get(NewTy);
1157       assert(New != OldC && "Didn't replace constant??");
1158       OldC->uncheckedReplaceAllUsesWith(New);
1159       OldC->destroyConstant();     // This constant is now dead, destroy it.
1160     }
1161   };
1162 }
1163
1164 static ValueMap<char, Type, UndefValue> UndefValueConstants;
1165
1166 static char getValType(UndefValue *) {
1167   return 0;
1168 }
1169
1170
1171 UndefValue *UndefValue::get(const Type *Ty) {
1172   return UndefValueConstants.getOrCreate(Ty, 0);
1173 }
1174
1175 // destroyConstant - Remove the constant from the constant table.
1176 //
1177 void UndefValue::destroyConstant() {
1178   UndefValueConstants.remove(this);
1179   destroyConstantImpl();
1180 }
1181
1182
1183
1184
1185 //---- ConstantExpr::get() implementations...
1186 //
1187 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1188
1189 namespace llvm {
1190   template<>
1191   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1192     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1193       if (V.first == Instruction::Cast)
1194         return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1195       if ((V.first >= Instruction::BinaryOpsBegin &&
1196            V.first < Instruction::BinaryOpsEnd) ||
1197           V.first == Instruction::Shl || V.first == Instruction::Shr)
1198         return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1199       if (V.first == Instruction::Select)
1200         return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1201
1202       assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1203
1204       std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1205       return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1206     }
1207   };
1208
1209   template<>
1210   struct ConvertConstantType<ConstantExpr, Type> {
1211     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1212       Constant *New;
1213       switch (OldC->getOpcode()) {
1214       case Instruction::Cast:
1215         New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1216         break;
1217       case Instruction::Select:
1218         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1219                                         OldC->getOperand(1),
1220                                         OldC->getOperand(2));
1221         break;
1222       case Instruction::Shl:
1223       case Instruction::Shr:
1224         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1225                                      OldC->getOperand(0), OldC->getOperand(1));
1226         break;
1227       default:
1228         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1229                OldC->getOpcode() < Instruction::BinaryOpsEnd);
1230         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1231                                   OldC->getOperand(1));
1232         break;
1233       case Instruction::GetElementPtr:
1234         // Make everyone now use a constant of the new type...
1235         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1236         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1237         break;
1238       }
1239
1240       assert(New != OldC && "Didn't replace constant??");
1241       OldC->uncheckedReplaceAllUsesWith(New);
1242       OldC->destroyConstant();    // This constant is now dead, destroy it.
1243     }
1244   };
1245 } // end namespace llvm
1246
1247
1248 static ExprMapKeyType getValType(ConstantExpr *CE) {
1249   std::vector<Constant*> Operands;
1250   Operands.reserve(CE->getNumOperands());
1251   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1252     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1253   return ExprMapKeyType(CE->getOpcode(), Operands);
1254 }
1255
1256 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1257
1258 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1259   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1260
1261   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1262     return FC;          // Fold a few common cases...
1263
1264   // Look up the constant in the table first to ensure uniqueness
1265   std::vector<Constant*> argVec(1, C);
1266   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1267   return ExprConstants.getOrCreate(Ty, Key);
1268 }
1269
1270 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1271   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1272          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1273          "This is an illegal sign extension!");
1274   if (C->getType() != Type::BoolTy) {
1275     C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1276     return ConstantExpr::getCast(C, Ty);
1277   } else {
1278     if (C == ConstantBool::True)
1279       return ConstantIntegral::getAllOnesValue(Ty);
1280     else
1281       return ConstantIntegral::getNullValue(Ty);
1282   }
1283 }
1284
1285 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1286   assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1287          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1288          "This is an illegal zero extension!");
1289   if (C->getType() != Type::BoolTy)
1290     C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1291   return ConstantExpr::getCast(C, Ty);
1292 }
1293
1294 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1295   // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1296   return getCast(
1297     getGetElementPtr(getNullValue(PointerType::get(Ty)),
1298                  std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1299     Type::ULongTy);
1300 }
1301
1302 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1303   // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1304   static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
1305
1306   return ConstantExpr::getGetElementPtr(C, Indices);
1307 }
1308
1309 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1310                               Constant *C1, Constant *C2) {
1311   if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1312     return getShiftTy(ReqTy, Opcode, C1, C2);
1313   // Check the operands for consistency first
1314   assert((Opcode >= Instruction::BinaryOpsBegin &&
1315           Opcode < Instruction::BinaryOpsEnd) &&
1316          "Invalid opcode in binary constant expression");
1317   assert(C1->getType() == C2->getType() &&
1318          "Operand types in binary constant expression should match");
1319
1320   if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1321                                  ReqTy == Type::BoolTy))
1322     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1323       return FC;          // Fold a few common cases...
1324
1325   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1326   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1327   return ExprConstants.getOrCreate(ReqTy, Key);
1328 }
1329
1330 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1331 #ifndef NDEBUG
1332   switch (Opcode) {
1333   case Instruction::Add: case Instruction::Sub:
1334   case Instruction::Mul: case Instruction::Div:
1335   case Instruction::Rem:
1336     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1337     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint()) &&
1338            "Tried to create an arithmetic operation on a non-arithmetic type!");
1339     break;
1340   case Instruction::And:
1341   case Instruction::Or:
1342   case Instruction::Xor:
1343     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1344     assert(C1->getType()->isIntegral() &&
1345            "Tried to create a logical operation on a non-integral type!");
1346     break;
1347   case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1348   case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1349     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1350     break;
1351   case Instruction::Shl:
1352   case Instruction::Shr:
1353     assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1354     assert(C1->getType()->isInteger() &&
1355            "Tried to create a shift operation on a non-integer type!");
1356     break;
1357   default:
1358     break;
1359   }
1360 #endif
1361
1362   if (Instruction::isRelational(Opcode))
1363     return getTy(Type::BoolTy, Opcode, C1, C2);
1364   else
1365     return getTy(C1->getType(), Opcode, C1, C2);
1366 }
1367
1368 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1369                                     Constant *V1, Constant *V2) {
1370   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1371   assert(V1->getType() == V2->getType() && "Select value types must match!");
1372   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1373
1374   if (ReqTy == V1->getType())
1375     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1376       return SC;        // Fold common cases
1377
1378   std::vector<Constant*> argVec(3, C);
1379   argVec[1] = V1;
1380   argVec[2] = V2;
1381   ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1382   return ExprConstants.getOrCreate(ReqTy, Key);
1383 }
1384
1385 /// getShiftTy - Return a shift left or shift right constant expr
1386 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1387                                    Constant *C1, Constant *C2) {
1388   // Check the operands for consistency first
1389   assert((Opcode == Instruction::Shl ||
1390           Opcode == Instruction::Shr) &&
1391          "Invalid opcode in binary constant expression");
1392   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1393          "Invalid operand types for Shift constant expr!");
1394
1395   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1396     return FC;          // Fold a few common cases...
1397
1398   // Look up the constant in the table first to ensure uniqueness
1399   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1400   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1401   return ExprConstants.getOrCreate(ReqTy, Key);
1402 }
1403
1404
1405 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1406                                            const std::vector<Value*> &IdxList) {
1407   assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1408          "GEP indices invalid!");
1409
1410   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1411     return FC;          // Fold a few common cases...
1412
1413   assert(isa<PointerType>(C->getType()) &&
1414          "Non-pointer type for constant GetElementPtr expression");
1415   // Look up the constant in the table first to ensure uniqueness
1416   std::vector<Constant*> ArgVec;
1417   ArgVec.reserve(IdxList.size()+1);
1418   ArgVec.push_back(C);
1419   for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1420     ArgVec.push_back(cast<Constant>(IdxList[i]));
1421   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1422   return ExprConstants.getOrCreate(ReqTy, Key);
1423 }
1424
1425 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1426                                          const std::vector<Constant*> &IdxList){
1427   // Get the result type of the getelementptr!
1428   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1429
1430   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1431                                                      true);
1432   assert(Ty && "GEP indices invalid!");
1433   return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1434 }
1435
1436 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1437                                          const std::vector<Value*> &IdxList) {
1438   // Get the result type of the getelementptr!
1439   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1440                                                      true);
1441   assert(Ty && "GEP indices invalid!");
1442   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1443 }
1444
1445
1446 // destroyConstant - Remove the constant from the constant table...
1447 //
1448 void ConstantExpr::destroyConstant() {
1449   ExprConstants.remove(this);
1450   destroyConstantImpl();
1451 }
1452
1453 const char *ConstantExpr::getOpcodeName() const {
1454   return Instruction::getOpcodeName(getOpcode());
1455 }
1456
1457 /// clearAllValueMaps - This method frees all internal memory used by the
1458 /// constant subsystem, which can be used in environments where this memory
1459 /// is otherwise reported as a leak.
1460 void Constant::clearAllValueMaps() {
1461   std::vector<Constant *> Constants;
1462
1463   DoubleConstants.clear(Constants);
1464   FloatConstants.clear(Constants);
1465   SIntConstants.clear(Constants);
1466   UIntConstants.clear(Constants);
1467   AggZeroConstants.clear(Constants);
1468   ArrayConstants.clear(Constants);
1469   StructConstants.clear(Constants);
1470   PackedConstants.clear(Constants);
1471   NullPtrConstants.clear(Constants);
1472   UndefValueConstants.clear(Constants);
1473   ExprConstants.clear(Constants);
1474
1475   for (std::vector<Constant *>::iterator I = Constants.begin(),
1476        E = Constants.end(); I != E; ++I)
1477     (*I)->dropAllReferences();
1478   for (std::vector<Constant *>::iterator I = Constants.begin(),
1479        E = Constants.end(); I != E; ++I)
1480     (*I)->destroyConstantImpl();
1481   Constants.clear();
1482 }