Privatize the last bit of Constant-creation state.
[oota-llvm.git] / lib / VMCore / LLVMContextImpl.h
1 //===----------------- LLVMContextImpl.h - Implementation ------*- C++ -*--===//
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 declares LLVMContextImpl, the opaque implementation 
11 //  of LLVMContext.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_LLVMCONTEXT_IMPL_H
16 #define LLVM_LLVMCONTEXT_IMPL_H
17
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Operator.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/System/Mutex.h"
26 #include "llvm/System/RWMutex.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/FoldingSet.h"
31 #include "llvm/ADT/StringMap.h"
32 #include <map>
33 #include <vector>
34
35 namespace llvm {
36 template<class ValType>
37 struct ConstantTraits;
38
39
40 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
41 /// behind the scenes to implement unary constant exprs.
42 class UnaryConstantExpr : public ConstantExpr {
43   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
44 public:
45   // allocate space for exactly one operand
46   void *operator new(size_t s) {
47     return User::operator new(s, 1);
48   }
49   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
50     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
51     Op<0>() = C;
52   }
53   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
54 };
55
56 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
57 /// behind the scenes to implement binary constant exprs.
58 class BinaryConstantExpr : public ConstantExpr {
59   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
60 public:
61   // allocate space for exactly two operands
62   void *operator new(size_t s) {
63     return User::operator new(s, 2);
64   }
65   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
66     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
67     Op<0>() = C1;
68     Op<1>() = C2;
69   }
70   /// Transparently provide more efficient getOperand methods.
71   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
72 };
73
74 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
75 /// behind the scenes to implement select constant exprs.
76 class SelectConstantExpr : public ConstantExpr {
77   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
78 public:
79   // allocate space for exactly three operands
80   void *operator new(size_t s) {
81     return User::operator new(s, 3);
82   }
83   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
84     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
85     Op<0>() = C1;
86     Op<1>() = C2;
87     Op<2>() = C3;
88   }
89   /// Transparently provide more efficient getOperand methods.
90   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
91 };
92
93 /// ExtractElementConstantExpr - This class is private to
94 /// Constants.cpp, and is used behind the scenes to implement
95 /// extractelement constant exprs.
96 class ExtractElementConstantExpr : public ConstantExpr {
97   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
98 public:
99   // allocate space for exactly two operands
100   void *operator new(size_t s) {
101     return User::operator new(s, 2);
102   }
103   ExtractElementConstantExpr(Constant *C1, Constant *C2)
104     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
105                    Instruction::ExtractElement, &Op<0>(), 2) {
106     Op<0>() = C1;
107     Op<1>() = C2;
108   }
109   /// Transparently provide more efficient getOperand methods.
110   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
111 };
112
113 /// InsertElementConstantExpr - This class is private to
114 /// Constants.cpp, and is used behind the scenes to implement
115 /// insertelement constant exprs.
116 class InsertElementConstantExpr : public ConstantExpr {
117   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
118 public:
119   // allocate space for exactly three operands
120   void *operator new(size_t s) {
121     return User::operator new(s, 3);
122   }
123   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
124     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
125                    &Op<0>(), 3) {
126     Op<0>() = C1;
127     Op<1>() = C2;
128     Op<2>() = C3;
129   }
130   /// Transparently provide more efficient getOperand methods.
131   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
132 };
133
134 /// ShuffleVectorConstantExpr - This class is private to
135 /// Constants.cpp, and is used behind the scenes to implement
136 /// shufflevector constant exprs.
137 class ShuffleVectorConstantExpr : public ConstantExpr {
138   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
139 public:
140   // allocate space for exactly three operands
141   void *operator new(size_t s) {
142     return User::operator new(s, 3);
143   }
144   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
145   : ConstantExpr(VectorType::get(
146                    cast<VectorType>(C1->getType())->getElementType(),
147                    cast<VectorType>(C3->getType())->getNumElements()),
148                  Instruction::ShuffleVector, 
149                  &Op<0>(), 3) {
150     Op<0>() = C1;
151     Op<1>() = C2;
152     Op<2>() = C3;
153   }
154   /// Transparently provide more efficient getOperand methods.
155   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
156 };
157
158 /// ExtractValueConstantExpr - This class is private to
159 /// Constants.cpp, and is used behind the scenes to implement
160 /// extractvalue constant exprs.
161 class ExtractValueConstantExpr : public ConstantExpr {
162   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
163 public:
164   // allocate space for exactly one operand
165   void *operator new(size_t s) {
166     return User::operator new(s, 1);
167   }
168   ExtractValueConstantExpr(Constant *Agg,
169                            const SmallVector<unsigned, 4> &IdxList,
170                            const Type *DestTy)
171     : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
172       Indices(IdxList) {
173     Op<0>() = Agg;
174   }
175
176   /// Indices - These identify which value to extract.
177   const SmallVector<unsigned, 4> Indices;
178
179   /// Transparently provide more efficient getOperand methods.
180   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
181 };
182
183 /// InsertValueConstantExpr - This class is private to
184 /// Constants.cpp, and is used behind the scenes to implement
185 /// insertvalue constant exprs.
186 class InsertValueConstantExpr : public ConstantExpr {
187   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
188 public:
189   // allocate space for exactly one operand
190   void *operator new(size_t s) {
191     return User::operator new(s, 2);
192   }
193   InsertValueConstantExpr(Constant *Agg, Constant *Val,
194                           const SmallVector<unsigned, 4> &IdxList,
195                           const Type *DestTy)
196     : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
197       Indices(IdxList) {
198     Op<0>() = Agg;
199     Op<1>() = Val;
200   }
201
202   /// Indices - These identify the position for the insertion.
203   const SmallVector<unsigned, 4> Indices;
204
205   /// Transparently provide more efficient getOperand methods.
206   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
207 };
208
209
210 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
211 /// used behind the scenes to implement getelementpr constant exprs.
212 class GetElementPtrConstantExpr : public ConstantExpr {
213   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
214                             const Type *DestTy);
215 public:
216   static GetElementPtrConstantExpr *Create(Constant *C,
217                                            const std::vector<Constant*>&IdxList,
218                                            const Type *DestTy) {
219     return
220       new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
221   }
222   /// Transparently provide more efficient getOperand methods.
223   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
224 };
225
226 // CompareConstantExpr - This class is private to Constants.cpp, and is used
227 // behind the scenes to implement ICmp and FCmp constant expressions. This is
228 // needed in order to store the predicate value for these instructions.
229 struct CompareConstantExpr : public ConstantExpr {
230   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
231   // allocate space for exactly two operands
232   void *operator new(size_t s) {
233     return User::operator new(s, 2);
234   }
235   unsigned short predicate;
236   CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
237                       unsigned short pred,  Constant* LHS, Constant* RHS)
238     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
239     Op<0>() = LHS;
240     Op<1>() = RHS;
241   }
242   /// Transparently provide more efficient getOperand methods.
243   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
244 };
245
246 template <>
247 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
248 };
249 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
250
251 template <>
252 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
253 };
254 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
255
256 template <>
257 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
258 };
259 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
260
261 template <>
262 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
263 };
264 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
265
266 template <>
267 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
268 };
269 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
270
271 template <>
272 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
273 };
274 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
275
276 template <>
277 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
278 };
279 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
280
281 template <>
282 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
283 };
284 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
285
286 template <>
287 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
288 };
289
290 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
291
292
293 template <>
294 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
295 };
296 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
297
298 struct ExprMapKeyType {
299   typedef SmallVector<unsigned, 4> IndexList;
300
301   ExprMapKeyType(unsigned opc,
302       const std::vector<Constant*> &ops,
303       unsigned short pred = 0,
304       const IndexList &inds = IndexList())
305         : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
306   uint16_t opcode;
307   uint16_t predicate;
308   std::vector<Constant*> operands;
309   IndexList indices;
310   bool operator==(const ExprMapKeyType& that) const {
311     return this->opcode == that.opcode &&
312            this->predicate == that.predicate &&
313            this->operands == that.operands &&
314            this->indices == that.indices;
315   }
316   bool operator<(const ExprMapKeyType & that) const {
317     return this->opcode < that.opcode ||
318       (this->opcode == that.opcode && this->predicate < that.predicate) ||
319       (this->opcode == that.opcode && this->predicate == that.predicate &&
320        this->operands < that.operands) ||
321       (this->opcode == that.opcode && this->predicate == that.predicate &&
322        this->operands == that.operands && this->indices < that.indices);
323   }
324
325   bool operator!=(const ExprMapKeyType& that) const {
326     return !(*this == that);
327   }
328 };
329
330 // The number of operands for each ConstantCreator::create method is
331 // determined by the ConstantTraits template.
332 // ConstantCreator - A class that is used to create constants by
333 // ValueMap*.  This class should be partially specialized if there is
334 // something strange that needs to be done to interface to the ctor for the
335 // constant.
336 //
337 template<typename T, typename Alloc>
338 struct ConstantTraits< std::vector<T, Alloc> > {
339   static unsigned uses(const std::vector<T, Alloc>& v) {
340     return v.size();
341   }
342 };
343
344 template<class ConstantClass, class TypeClass, class ValType>
345 struct ConstantCreator {
346   static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
347     return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
348   }
349 };
350
351 template<class ConstantClass, class TypeClass>
352 struct ConvertConstantType {
353   static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
354     llvm_unreachable("This type cannot be converted!");
355   }
356 };
357
358 template<>
359 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
360   static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
361       unsigned short pred = 0) {
362     if (Instruction::isCast(V.opcode))
363       return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
364     if ((V.opcode >= Instruction::BinaryOpsBegin &&
365          V.opcode < Instruction::BinaryOpsEnd))
366       return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
367     if (V.opcode == Instruction::Select)
368       return new SelectConstantExpr(V.operands[0], V.operands[1], 
369                                     V.operands[2]);
370     if (V.opcode == Instruction::ExtractElement)
371       return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
372     if (V.opcode == Instruction::InsertElement)
373       return new InsertElementConstantExpr(V.operands[0], V.operands[1],
374                                            V.operands[2]);
375     if (V.opcode == Instruction::ShuffleVector)
376       return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
377                                            V.operands[2]);
378     if (V.opcode == Instruction::InsertValue)
379       return new InsertValueConstantExpr(V.operands[0], V.operands[1],
380                                          V.indices, Ty);
381     if (V.opcode == Instruction::ExtractValue)
382       return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
383     if (V.opcode == Instruction::GetElementPtr) {
384       std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
385       return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
386     }
387
388     // The compare instructions are weird. We have to encode the predicate
389     // value and it is combined with the instruction opcode by multiplying
390     // the opcode by one hundred. We must decode this to get the predicate.
391     if (V.opcode == Instruction::ICmp)
392       return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
393                                      V.operands[0], V.operands[1]);
394     if (V.opcode == Instruction::FCmp) 
395       return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
396                                      V.operands[0], V.operands[1]);
397     llvm_unreachable("Invalid ConstantExpr!");
398     return 0;
399   }
400 };
401
402 template<>
403 struct ConvertConstantType<ConstantExpr, Type> {
404   static void convert(ConstantExpr *OldC, const Type *NewTy) {
405     Constant *New;
406     switch (OldC->getOpcode()) {
407     case Instruction::Trunc:
408     case Instruction::ZExt:
409     case Instruction::SExt:
410     case Instruction::FPTrunc:
411     case Instruction::FPExt:
412     case Instruction::UIToFP:
413     case Instruction::SIToFP:
414     case Instruction::FPToUI:
415     case Instruction::FPToSI:
416     case Instruction::PtrToInt:
417     case Instruction::IntToPtr:
418     case Instruction::BitCast:
419       New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
420                                   NewTy);
421       break;
422     case Instruction::Select:
423       New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
424                                       OldC->getOperand(1),
425                                       OldC->getOperand(2));
426       break;
427     default:
428       assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
429              OldC->getOpcode() <  Instruction::BinaryOpsEnd);
430       New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
431                                 OldC->getOperand(1));
432       break;
433     case Instruction::GetElementPtr:
434       // Make everyone now use a constant of the new type...
435       std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
436       New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
437                                              &Idx[0], Idx.size());
438       break;
439     }
440
441     assert(New != OldC && "Didn't replace constant??");
442     OldC->uncheckedReplaceAllUsesWith(New);
443     OldC->destroyConstant();    // This constant is now dead, destroy it.
444   }
445 };
446
447 // ConstantAggregateZero does not take extra "value" argument...
448 template<class ValType>
449 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
450   static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
451     return new ConstantAggregateZero(Ty);
452   }
453 };
454
455 template<>
456 struct ConvertConstantType<ConstantVector, VectorType> {
457   static void convert(ConstantVector *OldC, const VectorType *NewTy) {
458     // Make everyone now use a constant of the new type...
459     std::vector<Constant*> C;
460     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
461       C.push_back(cast<Constant>(OldC->getOperand(i)));
462     Constant *New = ConstantVector::get(NewTy, C);
463     assert(New != OldC && "Didn't replace constant??");
464     OldC->uncheckedReplaceAllUsesWith(New);
465     OldC->destroyConstant();    // This constant is now dead, destroy it.
466   }
467 };
468
469 template<>
470 struct ConvertConstantType<ConstantAggregateZero, Type> {
471   static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
472     // Make everyone now use a constant of the new type...
473     Constant *New = ConstantAggregateZero::get(NewTy);
474     assert(New != OldC && "Didn't replace constant??");
475     OldC->uncheckedReplaceAllUsesWith(New);
476     OldC->destroyConstant();     // This constant is now dead, destroy it.
477   }
478 };
479
480 template<>
481 struct ConvertConstantType<ConstantArray, ArrayType> {
482   static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
483     // Make everyone now use a constant of the new type...
484     std::vector<Constant*> C;
485     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
486       C.push_back(cast<Constant>(OldC->getOperand(i)));
487     Constant *New = ConstantArray::get(NewTy, C);
488     assert(New != OldC && "Didn't replace constant??");
489     OldC->uncheckedReplaceAllUsesWith(New);
490     OldC->destroyConstant();    // This constant is now dead, destroy it.
491   }
492 };
493
494 template<>
495 struct ConvertConstantType<ConstantStruct, StructType> {
496   static void convert(ConstantStruct *OldC, const StructType *NewTy) {
497     // Make everyone now use a constant of the new type...
498     std::vector<Constant*> C;
499     for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
500       C.push_back(cast<Constant>(OldC->getOperand(i)));
501     Constant *New = ConstantStruct::get(NewTy, C);
502     assert(New != OldC && "Didn't replace constant??");
503
504     OldC->uncheckedReplaceAllUsesWith(New);
505     OldC->destroyConstant();    // This constant is now dead, destroy it.
506   }
507 };
508
509 // ConstantPointerNull does not take extra "value" argument...
510 template<class ValType>
511 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
512   static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
513     return new ConstantPointerNull(Ty);
514   }
515 };
516
517 template<>
518 struct ConvertConstantType<ConstantPointerNull, PointerType> {
519   static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
520     // Make everyone now use a constant of the new type...
521     Constant *New = ConstantPointerNull::get(NewTy);
522     assert(New != OldC && "Didn't replace constant??");
523     OldC->uncheckedReplaceAllUsesWith(New);
524     OldC->destroyConstant();     // This constant is now dead, destroy it.
525   }
526 };
527
528 // UndefValue does not take extra "value" argument...
529 template<class ValType>
530 struct ConstantCreator<UndefValue, Type, ValType> {
531   static UndefValue *create(const Type *Ty, const ValType &V) {
532     return new UndefValue(Ty);
533   }
534 };
535
536 template<>
537 struct ConvertConstantType<UndefValue, Type> {
538   static void convert(UndefValue *OldC, const Type *NewTy) {
539     // Make everyone now use a constant of the new type.
540     Constant *New = UndefValue::get(NewTy);
541     assert(New != OldC && "Didn't replace constant??");
542     OldC->uncheckedReplaceAllUsesWith(New);
543     OldC->destroyConstant();     // This constant is now dead, destroy it.
544   }
545 };
546
547 template<class ValType, class TypeClass, class ConstantClass,
548          bool HasLargeKey = false /*true for arrays and structs*/ >
549 class ValueMap : public AbstractTypeUser {
550 public:
551   typedef std::pair<const Type*, ValType> MapKey;
552   typedef std::map<MapKey, Constant *> MapTy;
553   typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
554   typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
555 private:
556   /// Map - This is the main map from the element descriptor to the Constants.
557   /// This is the primary way we avoid creating two of the same shape
558   /// constant.
559   MapTy Map;
560     
561   /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
562   /// from the constants to their element in Map.  This is important for
563   /// removal of constants from the array, which would otherwise have to scan
564   /// through the map with very large keys.
565   InverseMapTy InverseMap;
566
567   /// AbstractTypeMap - Map for abstract type constants.
568   ///
569   AbstractTypeMapTy AbstractTypeMap;
570     
571   /// ValueMapLock - Mutex for this map.
572   sys::SmartMutex<true> ValueMapLock;
573
574 public:
575   // NOTE: This function is not locked.  It is the caller's responsibility
576   // to enforce proper synchronization.
577   typename MapTy::iterator map_end() { return Map.end(); }
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     DOUT << "Constant.cpp: ValueMap\n";
779   }
780 };
781
782
783 class ConstantInt;
784 class ConstantFP;
785 class MDString;
786 class MDNode;
787 class LLVMContext;
788 class Type;
789 class Value;
790
791 struct DenseMapAPIntKeyInfo {
792   struct KeyTy {
793     APInt val;
794     const Type* type;
795     KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
796     KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
797     bool operator==(const KeyTy& that) const {
798       return type == that.type && this->val == that.val;
799     }
800     bool operator!=(const KeyTy& that) const {
801       return !this->operator==(that);
802     }
803   };
804   static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
805   static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
806   static unsigned getHashValue(const KeyTy &Key) {
807     return DenseMapInfo<void*>::getHashValue(Key.type) ^ 
808       Key.val.getHashValue();
809   }
810   static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
811     return LHS == RHS;
812   }
813   static bool isPod() { return false; }
814 };
815
816 struct DenseMapAPFloatKeyInfo {
817   struct KeyTy {
818     APFloat val;
819     KeyTy(const APFloat& V) : val(V){}
820     KeyTy(const KeyTy& that) : val(that.val) {}
821     bool operator==(const KeyTy& that) const {
822       return this->val.bitwiseIsEqual(that.val);
823     }
824     bool operator!=(const KeyTy& that) const {
825       return !this->operator==(that);
826     }
827   };
828   static inline KeyTy getEmptyKey() { 
829     return KeyTy(APFloat(APFloat::Bogus,1));
830   }
831   static inline KeyTy getTombstoneKey() { 
832     return KeyTy(APFloat(APFloat::Bogus,2)); 
833   }
834   static unsigned getHashValue(const KeyTy &Key) {
835     return Key.val.getHashValue();
836   }
837   static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
838     return LHS == RHS;
839   }
840   static bool isPod() { return false; }
841 };
842
843 struct LLVMContextImpl {
844   sys::SmartRWMutex<true> ConstantsLock;
845   
846   typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*, 
847                    DenseMapAPIntKeyInfo> IntMapTy;
848   IntMapTy IntConstants;
849   
850   typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*, 
851                    DenseMapAPFloatKeyInfo> FPMapTy;
852   FPMapTy FPConstants;
853   
854   StringMap<MDString*> MDStringCache;
855   
856   FoldingSet<MDNode> MDNodeSet;
857   
858   ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
859   
860   typedef ValueMap<std::vector<Constant*>, ArrayType, 
861     ConstantArray, true /*largekey*/> ArrayConstantsTy;
862   ArrayConstantsTy ArrayConstants;
863   
864   typedef ValueMap<std::vector<Constant*>, StructType,
865                    ConstantStruct, true /*largekey*/> StructConstantsTy;
866   StructConstantsTy StructConstants;
867   
868   typedef ValueMap<std::vector<Constant*>, VectorType,
869                    ConstantVector> VectorConstantsTy;
870   VectorConstantsTy VectorConstants;
871   
872   ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
873   
874   ValueMap<char, Type, UndefValue> UndefValueConstants;
875   
876   ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
877   
878   LLVMContext &Context;
879   ConstantInt *TheTrueVal;
880   ConstantInt *TheFalseVal;
881   
882   LLVMContextImpl(LLVMContext &C);
883 private:
884   LLVMContextImpl();
885   LLVMContextImpl(const LLVMContextImpl&);
886 };
887
888 }
889
890 #endif