Revert "Include optional subclass flags, such as inbounds, nsw, etc., ...", this
[oota-llvm.git] / lib / VMCore / ConstantsContext.h
1 //===-- ConstantsContext.h - Constants-related Context Interals -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines various helper methods and classes used by
11 // LLVMContextImpl for creating and managing constants.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CONSTANTSCONTEXT_H
16 #define LLVM_CONSTANTSCONTEXT_H
17
18 #include "llvm/Instructions.h"
19 #include "llvm/Operator.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/System/Mutex.h"
24 #include "llvm/System/RWMutex.h"
25 #include <map>
26
27 namespace llvm {
28 template<class ValType>
29 struct ConstantTraits;
30
31 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
32 /// behind the scenes to implement unary constant exprs.
33 class UnaryConstantExpr : public ConstantExpr {
34   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
35 public:
36   // allocate space for exactly one operand
37   void *operator new(size_t s) {
38     return User::operator new(s, 1);
39   }
40   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
41     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
42     Op<0>() = C;
43   }
44   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
45 };
46
47 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
48 /// behind the scenes to implement binary constant exprs.
49 class BinaryConstantExpr : public ConstantExpr {
50   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
51 public:
52   // allocate space for exactly two operands
53   void *operator new(size_t s) {
54     return User::operator new(s, 2);
55   }
56   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
57     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
58     Op<0>() = C1;
59     Op<1>() = C2;
60   }
61   /// Transparently provide more efficient getOperand methods.
62   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
63 };
64
65 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
66 /// behind the scenes to implement select constant exprs.
67 class SelectConstantExpr : public ConstantExpr {
68   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
69 public:
70   // allocate space for exactly three operands
71   void *operator new(size_t s) {
72     return User::operator new(s, 3);
73   }
74   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
75     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
76     Op<0>() = C1;
77     Op<1>() = C2;
78     Op<2>() = C3;
79   }
80   /// Transparently provide more efficient getOperand methods.
81   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
82 };
83
84 /// ExtractElementConstantExpr - This class is private to
85 /// Constants.cpp, and is used behind the scenes to implement
86 /// extractelement constant exprs.
87 class ExtractElementConstantExpr : public ConstantExpr {
88   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
89 public:
90   // allocate space for exactly two operands
91   void *operator new(size_t s) {
92     return User::operator new(s, 2);
93   }
94   ExtractElementConstantExpr(Constant *C1, Constant *C2)
95     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
96                    Instruction::ExtractElement, &Op<0>(), 2) {
97     Op<0>() = C1;
98     Op<1>() = C2;
99   }
100   /// Transparently provide more efficient getOperand methods.
101   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
102 };
103
104 /// InsertElementConstantExpr - This class is private to
105 /// Constants.cpp, and is used behind the scenes to implement
106 /// insertelement constant exprs.
107 class InsertElementConstantExpr : public ConstantExpr {
108   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
109 public:
110   // allocate space for exactly three operands
111   void *operator new(size_t s) {
112     return User::operator new(s, 3);
113   }
114   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
115     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
116                    &Op<0>(), 3) {
117     Op<0>() = C1;
118     Op<1>() = C2;
119     Op<2>() = C3;
120   }
121   /// Transparently provide more efficient getOperand methods.
122   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
123 };
124
125 /// ShuffleVectorConstantExpr - This class is private to
126 /// Constants.cpp, and is used behind the scenes to implement
127 /// shufflevector constant exprs.
128 class ShuffleVectorConstantExpr : public ConstantExpr {
129   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
130 public:
131   // allocate space for exactly three operands
132   void *operator new(size_t s) {
133     return User::operator new(s, 3);
134   }
135   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
136   : ConstantExpr(VectorType::get(
137                    cast<VectorType>(C1->getType())->getElementType(),
138                    cast<VectorType>(C3->getType())->getNumElements()),
139                  Instruction::ShuffleVector, 
140                  &Op<0>(), 3) {
141     Op<0>() = C1;
142     Op<1>() = C2;
143     Op<2>() = C3;
144   }
145   /// Transparently provide more efficient getOperand methods.
146   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
147 };
148
149 /// ExtractValueConstantExpr - This class is private to
150 /// Constants.cpp, and is used behind the scenes to implement
151 /// extractvalue constant exprs.
152 class ExtractValueConstantExpr : public ConstantExpr {
153   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
154 public:
155   // allocate space for exactly one operand
156   void *operator new(size_t s) {
157     return User::operator new(s, 1);
158   }
159   ExtractValueConstantExpr(Constant *Agg,
160                            const SmallVector<unsigned, 4> &IdxList,
161                            const Type *DestTy)
162     : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
163       Indices(IdxList) {
164     Op<0>() = Agg;
165   }
166
167   /// Indices - These identify which value to extract.
168   const SmallVector<unsigned, 4> Indices;
169
170   /// Transparently provide more efficient getOperand methods.
171   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
172 };
173
174 /// InsertValueConstantExpr - This class is private to
175 /// Constants.cpp, and is used behind the scenes to implement
176 /// insertvalue constant exprs.
177 class InsertValueConstantExpr : public ConstantExpr {
178   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
179 public:
180   // allocate space for exactly one operand
181   void *operator new(size_t s) {
182     return User::operator new(s, 2);
183   }
184   InsertValueConstantExpr(Constant *Agg, Constant *Val,
185                           const SmallVector<unsigned, 4> &IdxList,
186                           const Type *DestTy)
187     : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
188       Indices(IdxList) {
189     Op<0>() = Agg;
190     Op<1>() = Val;
191   }
192
193   /// Indices - These identify the position for the insertion.
194   const SmallVector<unsigned, 4> Indices;
195
196   /// Transparently provide more efficient getOperand methods.
197   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
198 };
199
200
201 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
202 /// used behind the scenes to implement getelementpr constant exprs.
203 class GetElementPtrConstantExpr : public ConstantExpr {
204   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
205                             const Type *DestTy);
206 public:
207   static GetElementPtrConstantExpr *Create(Constant *C,
208                                            const std::vector<Constant*>&IdxList,
209                                            const Type *DestTy) {
210     return
211       new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
212   }
213   /// Transparently provide more efficient getOperand methods.
214   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
215 };
216
217 // CompareConstantExpr - This class is private to Constants.cpp, and is used
218 // behind the scenes to implement ICmp and FCmp constant expressions. This is
219 // needed in order to store the predicate value for these instructions.
220 struct CompareConstantExpr : public ConstantExpr {
221   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
222   // allocate space for exactly two operands
223   void *operator new(size_t s) {
224     return User::operator new(s, 2);
225   }
226   unsigned short predicate;
227   CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
228                       unsigned short pred,  Constant* LHS, Constant* RHS)
229     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
230     Op<0>() = LHS;
231     Op<1>() = RHS;
232   }
233   /// Transparently provide more efficient getOperand methods.
234   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
235 };
236
237 template <>
238 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
239 };
240 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
241
242 template <>
243 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
244 };
245 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
246
247 template <>
248 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
249 };
250 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
251
252 template <>
253 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
254 };
255 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
256
257 template <>
258 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
259 };
260 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
261
262 template <>
263 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
264 };
265 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
266
267 template <>
268 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
269 };
270 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
271
272 template <>
273 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
274 };
275 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
276
277 template <>
278 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
279 };
280
281 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
282
283
284 template <>
285 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
286 };
287 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
288
289 struct ExprMapKeyType {
290   typedef SmallVector<unsigned, 4> IndexList;
291
292   ExprMapKeyType(unsigned opc,
293       const std::vector<Constant*> &ops,
294       unsigned short pred = 0,
295       const IndexList &inds = IndexList())
296         : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
297   uint16_t opcode;
298   uint16_t predicate;
299   std::vector<Constant*> operands;
300   IndexList indices;
301   bool operator==(const ExprMapKeyType& that) const {
302     return this->opcode == that.opcode &&
303            this->predicate == that.predicate &&
304            this->operands == that.operands &&
305            this->indices == that.indices;
306   }
307   bool operator<(const ExprMapKeyType & that) const {
308     return this->opcode < that.opcode ||
309       (this->opcode == that.opcode && this->predicate < that.predicate) ||
310       (this->opcode == that.opcode && this->predicate == that.predicate &&
311        this->operands < that.operands) ||
312       (this->opcode == that.opcode && this->predicate == that.predicate &&
313        this->operands == that.operands && this->indices < that.indices);
314   }
315
316   bool operator!=(const ExprMapKeyType& that) const {
317     return !(*this == that);
318   }
319 };
320
321 // The number of operands for each ConstantCreator::create method is
322 // determined by the ConstantTraits template.
323 // ConstantCreator - A class that is used to create constants by
324 // ValueMap*.  This class should be partially specialized if there is
325 // something strange that needs to be done to interface to the ctor for the
326 // constant.
327 //
328 template<typename T, typename Alloc>
329 struct ConstantTraits< std::vector<T, Alloc> > {
330   static unsigned uses(const std::vector<T, Alloc>& v) {
331     return v.size();
332   }
333 };
334
335 template<class ConstantClass, class TypeClass, class ValType>
336 struct ConstantCreator {
337   static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
338     return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
339   }
340 };
341
342 template<class ConstantClass, class TypeClass>
343 struct ConvertConstantType {
344   static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
345     llvm_unreachable("This type cannot be converted!");
346   }
347 };
348
349 template<>
350 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
351   static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
352       unsigned short pred = 0) {
353     if (Instruction::isCast(V.opcode))
354       return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
355     if ((V.opcode >= Instruction::BinaryOpsBegin &&
356          V.opcode < Instruction::BinaryOpsEnd))
357       return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
358     if (V.opcode == Instruction::Select)
359       return new SelectConstantExpr(V.operands[0], V.operands[1], 
360                                     V.operands[2]);
361     if (V.opcode == Instruction::ExtractElement)
362       return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
363     if (V.opcode == Instruction::InsertElement)
364       return new InsertElementConstantExpr(V.operands[0], V.operands[1],
365                                            V.operands[2]);
366     if (V.opcode == Instruction::ShuffleVector)
367       return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
368                                            V.operands[2]);
369     if (V.opcode == Instruction::InsertValue)
370       return new InsertValueConstantExpr(V.operands[0], V.operands[1],
371                                          V.indices, Ty);
372     if (V.opcode == Instruction::ExtractValue)
373       return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
374     if (V.opcode == Instruction::GetElementPtr) {
375       std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
376       return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
377     }
378
379     // The compare instructions are weird. We have to encode the predicate
380     // value and it is combined with the instruction opcode by multiplying
381     // the opcode by one hundred. We must decode this to get the predicate.
382     if (V.opcode == Instruction::ICmp)
383       return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
384                                      V.operands[0], V.operands[1]);
385     if (V.opcode == Instruction::FCmp) 
386       return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
387                                      V.operands[0], V.operands[1]);
388     llvm_unreachable("Invalid ConstantExpr!");
389     return 0;
390   }
391 };
392
393 template<>
394 struct ConvertConstantType<ConstantExpr, Type> {
395   static void convert(ConstantExpr *OldC, const Type *NewTy) {
396     Constant *New;
397     switch (OldC->getOpcode()) {
398     case Instruction::Trunc:
399     case Instruction::ZExt:
400     case Instruction::SExt:
401     case Instruction::FPTrunc:
402     case Instruction::FPExt:
403     case Instruction::UIToFP:
404     case Instruction::SIToFP:
405     case Instruction::FPToUI:
406     case Instruction::FPToSI:
407     case Instruction::PtrToInt:
408     case Instruction::IntToPtr:
409     case Instruction::BitCast:
410       New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
411                                   NewTy);
412       break;
413     case Instruction::Select:
414       New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
415                                       OldC->getOperand(1),
416                                       OldC->getOperand(2));
417       break;
418     default:
419       assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
420              OldC->getOpcode() <  Instruction::BinaryOpsEnd);
421       New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
422                                 OldC->getOperand(1));
423       break;
424     case Instruction::GetElementPtr:
425       // Make everyone now use a constant of the new type...
426       std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
427       New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
428                                              &Idx[0], Idx.size());
429       break;
430     }
431
432     assert(New != OldC && "Didn't replace constant??");
433     OldC->uncheckedReplaceAllUsesWith(New);
434     OldC->destroyConstant();    // This constant is now dead, destroy it.
435   }
436 };
437
438 // ConstantAggregateZero does not take extra "value" argument...
439 template<class ValType>
440 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
441   static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
442     return new ConstantAggregateZero(Ty);
443   }
444 };
445
446 template<>
447 struct ConvertConstantType<ConstantVector, VectorType> {
448   static void convert(ConstantVector *OldC, const VectorType *NewTy) {
449     // Make everyone now use a constant of the new type...
450     std::vector<Constant*> C;
451     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
452       C.push_back(cast<Constant>(OldC->getOperand(i)));
453     Constant *New = ConstantVector::get(NewTy, C);
454     assert(New != OldC && "Didn't replace constant??");
455     OldC->uncheckedReplaceAllUsesWith(New);
456     OldC->destroyConstant();    // This constant is now dead, destroy it.
457   }
458 };
459
460 template<>
461 struct ConvertConstantType<ConstantAggregateZero, Type> {
462   static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
463     // Make everyone now use a constant of the new type...
464     Constant *New = ConstantAggregateZero::get(NewTy);
465     assert(New != OldC && "Didn't replace constant??");
466     OldC->uncheckedReplaceAllUsesWith(New);
467     OldC->destroyConstant();     // This constant is now dead, destroy it.
468   }
469 };
470
471 template<>
472 struct ConvertConstantType<ConstantArray, ArrayType> {
473   static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
474     // Make everyone now use a constant of the new type...
475     std::vector<Constant*> C;
476     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
477       C.push_back(cast<Constant>(OldC->getOperand(i)));
478     Constant *New = ConstantArray::get(NewTy, C);
479     assert(New != OldC && "Didn't replace constant??");
480     OldC->uncheckedReplaceAllUsesWith(New);
481     OldC->destroyConstant();    // This constant is now dead, destroy it.
482   }
483 };
484
485 template<>
486 struct ConvertConstantType<ConstantStruct, StructType> {
487   static void convert(ConstantStruct *OldC, const StructType *NewTy) {
488     // Make everyone now use a constant of the new type...
489     std::vector<Constant*> C;
490     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
491       C.push_back(cast<Constant>(OldC->getOperand(i)));
492     Constant *New = ConstantStruct::get(NewTy, C);
493     assert(New != OldC && "Didn't replace constant??");
494
495     OldC->uncheckedReplaceAllUsesWith(New);
496     OldC->destroyConstant();    // This constant is now dead, destroy it.
497   }
498 };
499
500 // ConstantPointerNull does not take extra "value" argument...
501 template<class ValType>
502 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
503   static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
504     return new ConstantPointerNull(Ty);
505   }
506 };
507
508 template<>
509 struct ConvertConstantType<ConstantPointerNull, PointerType> {
510   static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
511     // Make everyone now use a constant of the new type...
512     Constant *New = ConstantPointerNull::get(NewTy);
513     assert(New != OldC && "Didn't replace constant??");
514     OldC->uncheckedReplaceAllUsesWith(New);
515     OldC->destroyConstant();     // This constant is now dead, destroy it.
516   }
517 };
518
519 // UndefValue does not take extra "value" argument...
520 template<class ValType>
521 struct ConstantCreator<UndefValue, Type, ValType> {
522   static UndefValue *create(const Type *Ty, const ValType &V) {
523     return new UndefValue(Ty);
524   }
525 };
526
527 template<>
528 struct ConvertConstantType<UndefValue, Type> {
529   static void convert(UndefValue *OldC, const Type *NewTy) {
530     // Make everyone now use a constant of the new type.
531     Constant *New = UndefValue::get(NewTy);
532     assert(New != OldC && "Didn't replace constant??");
533     OldC->uncheckedReplaceAllUsesWith(New);
534     OldC->destroyConstant();     // This constant is now dead, destroy it.
535   }
536 };
537
538 template<class ValType, class TypeClass, class ConstantClass,
539          bool HasLargeKey = false /*true for arrays and structs*/ >
540 class ValueMap : public AbstractTypeUser {
541 public:
542   typedef std::pair<const Type*, ValType> MapKey;
543   typedef std::map<MapKey, Constant *> MapTy;
544   typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
545   typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
546 private:
547   /// Map - This is the main map from the element descriptor to the Constants.
548   /// This is the primary way we avoid creating two of the same shape
549   /// constant.
550   MapTy Map;
551     
552   /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
553   /// from the constants to their element in Map.  This is important for
554   /// removal of constants from the array, which would otherwise have to scan
555   /// through the map with very large keys.
556   InverseMapTy InverseMap;
557
558   /// AbstractTypeMap - Map for abstract type constants.
559   ///
560   AbstractTypeMapTy AbstractTypeMap;
561     
562   /// ValueMapLock - Mutex for this map.
563   sys::SmartMutex<true> ValueMapLock;
564
565 public:
566   // NOTE: This function is not locked.  It is the caller's responsibility
567   // to enforce proper synchronization.
568   typename MapTy::iterator map_begin() { return Map.begin(); }
569   typename MapTy::iterator map_end() { return Map.end(); }
570
571   void freeConstants() {
572     for (typename MapTy::iterator I=Map.begin(), E=Map.end();
573          I != E; ++I) {
574       if (I->second->use_empty())
575         delete I->second;
576     }
577   }
578     
579   /// InsertOrGetItem - Return an iterator for the specified element.
580   /// If the element exists in the map, the returned iterator points to the
581   /// entry and Exists=true.  If not, the iterator points to the newly
582   /// inserted entry and returns Exists=false.  Newly inserted entries have
583   /// I->second == 0, and should be filled in.
584   /// NOTE: This function is not locked.  It is the caller's responsibility
585   // to enforce proper synchronization.
586   typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
587                                  &InsertVal,
588                                  bool &Exists) {
589     std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
590     Exists = !IP.second;
591     return IP.first;
592   }
593     
594 private:
595   typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
596     if (HasLargeKey) {
597       typename InverseMapTy::iterator IMI = InverseMap.find(CP);
598       assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
599              IMI->second->second == CP &&
600              "InverseMap corrupt!");
601       return IMI->second;
602     }
603       
604     typename MapTy::iterator I =
605       Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
606                       getValType(CP)));
607     if (I == Map.end() || I->second != CP) {
608       // FIXME: This should not use a linear scan.  If this gets to be a
609       // performance problem, someone should look at this.
610       for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
611         /* empty */;
612     }
613     return I;
614   }
615     
616   ConstantClass* Create(const TypeClass *Ty, const ValType &V,
617                         typename MapTy::iterator I) {
618     ConstantClass* Result =
619       ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
620
621     assert(Result->getType() == Ty && "Type specified is not correct!");
622     I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
623
624     if (HasLargeKey)  // Remember the reverse mapping if needed.
625       InverseMap.insert(std::make_pair(Result, I));
626
627     // If the type of the constant is abstract, make sure that an entry
628     // exists for it in the AbstractTypeMap.
629     if (Ty->isAbstract()) {
630       typename AbstractTypeMapTy::iterator TI = 
631                                                AbstractTypeMap.find(Ty);
632
633       if (TI == AbstractTypeMap.end()) {
634         // Add ourselves to the ATU list of the type.
635         cast<DerivedType>(Ty)->addAbstractTypeUser(this);
636
637         AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
638       }
639     }
640       
641     return Result;
642   }
643 public:
644     
645   /// getOrCreate - Return the specified constant from the map, creating it if
646   /// necessary.
647   ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
648     sys::SmartScopedLock<true> Lock(ValueMapLock);
649     MapKey Lookup(Ty, V);
650     ConstantClass* Result = 0;
651     
652     typename MapTy::iterator I = Map.find(Lookup);
653     // Is it in the map?  
654     if (I != Map.end())
655       Result = static_cast<ConstantClass *>(I->second);
656         
657     if (!Result) {
658       // If no preexisting value, create one now...
659       Result = Create(Ty, V, I);
660     }
661         
662     return Result;
663   }
664
665   void remove(ConstantClass *CP) {
666     sys::SmartScopedLock<true> Lock(ValueMapLock);
667     typename MapTy::iterator I = FindExistingElement(CP);
668     assert(I != Map.end() && "Constant not found in constant table!");
669     assert(I->second == CP && "Didn't find correct element?");
670
671     if (HasLargeKey)  // Remember the reverse mapping if needed.
672       InverseMap.erase(CP);
673       
674     // Now that we found the entry, make sure this isn't the entry that
675     // the AbstractTypeMap points to.
676     const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
677     if (Ty->isAbstract()) {
678       assert(AbstractTypeMap.count(Ty) &&
679              "Abstract type not in AbstractTypeMap?");
680       typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
681       if (ATMEntryIt == I) {
682         // Yes, we are removing the representative entry for this type.
683         // See if there are any other entries of the same type.
684         typename MapTy::iterator TmpIt = ATMEntryIt;
685
686         // First check the entry before this one...
687         if (TmpIt != Map.begin()) {
688           --TmpIt;
689           if (TmpIt->first.first != Ty) // Not the same type, move back...
690             ++TmpIt;
691         }
692
693         // If we didn't find the same type, try to move forward...
694         if (TmpIt == ATMEntryIt) {
695           ++TmpIt;
696           if (TmpIt == Map.end() || TmpIt->first.first != Ty)
697             --TmpIt;   // No entry afterwards with the same type
698         }
699
700         // If there is another entry in the map of the same abstract type,
701         // update the AbstractTypeMap entry now.
702         if (TmpIt != ATMEntryIt) {
703           ATMEntryIt = TmpIt;
704         } else {
705           // Otherwise, we are removing the last instance of this type
706           // from the table.  Remove from the ATM, and from user list.
707           cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
708           AbstractTypeMap.erase(Ty);
709         }
710       }
711     }
712
713     Map.erase(I);
714   }
715
716     
717   /// MoveConstantToNewSlot - If we are about to change C to be the element
718   /// specified by I, update our internal data structures to reflect this
719   /// fact.
720   /// NOTE: This function is not locked. It is the responsibility of the
721   /// caller to enforce proper synchronization if using this method.
722   void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
723     // First, remove the old location of the specified constant in the map.
724     typename MapTy::iterator OldI = FindExistingElement(C);
725     assert(OldI != Map.end() && "Constant not found in constant table!");
726     assert(OldI->second == C && "Didn't find correct element?");
727       
728     // If this constant is the representative element for its abstract type,
729     // update the AbstractTypeMap so that the representative element is I.
730     if (C->getType()->isAbstract()) {
731       typename AbstractTypeMapTy::iterator ATI =
732           AbstractTypeMap.find(C->getType());
733       assert(ATI != AbstractTypeMap.end() &&
734              "Abstract type not in AbstractTypeMap?");
735       if (ATI->second == OldI)
736         ATI->second = I;
737     }
738       
739     // Remove the old entry from the map.
740     Map.erase(OldI);
741     
742     // Update the inverse map so that we know that this constant is now
743     // located at descriptor I.
744     if (HasLargeKey) {
745       assert(I->second == C && "Bad inversemap entry!");
746       InverseMap[C] = I;
747     }
748   }
749     
750   void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
751     sys::SmartScopedLock<true> Lock(ValueMapLock);
752     typename AbstractTypeMapTy::iterator I =
753       AbstractTypeMap.find(cast<Type>(OldTy));
754
755     assert(I != AbstractTypeMap.end() &&
756            "Abstract type not in AbstractTypeMap?");
757
758     // Convert a constant at a time until the last one is gone.  The last one
759     // leaving will remove() itself, causing the AbstractTypeMapEntry to be
760     // eliminated eventually.
761     do {
762       ConvertConstantType<ConstantClass,
763                           TypeClass>::convert(
764                               static_cast<ConstantClass *>(I->second->second),
765                                               cast<TypeClass>(NewTy));
766
767       I = AbstractTypeMap.find(cast<Type>(OldTy));
768     } while (I != AbstractTypeMap.end());
769   }
770
771   // If the type became concrete without being refined to any other existing
772   // type, we just remove ourselves from the ATU list.
773   void typeBecameConcrete(const DerivedType *AbsTy) {
774     AbsTy->removeAbstractTypeUser(this);
775   }
776
777   void dump() const {
778     DEBUG(errs() << "Constant.cpp: ValueMap\n");
779   }
780 };
781
782 }
783
784 #endif