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