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