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