blob: d634c0b202cbfaf58101588b8e089880495c14ba [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"
19#include "llvm/Operator.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/Support/ErrorHandling.h"
Chris Lattner34822f62009-08-23 04:44:11 +000022#include "llvm/Support/raw_ostream.h"
Owen Anderson9b676982009-08-04 22:55:26 +000023#include "llvm/System/Mutex.h"
24#include "llvm/System/RWMutex.h"
25#include <map>
26
27namespace llvm {
28template<class ValType>
29struct ConstantTraits;
30
31/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
32/// behind the scenes to implement unary constant exprs.
33class UnaryConstantExpr : public ConstantExpr {
34 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
35public:
36 // allocate space for exactly one operand
37 void *operator new(size_t s) {
38 return User::operator new(s, 1);
39 }
40 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
41 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
42 Op<0>() = C;
43 }
44 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
45};
46
47/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
48/// behind the scenes to implement binary constant exprs.
49class BinaryConstantExpr : public ConstantExpr {
50 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
51public:
52 // allocate space for exactly two operands
53 void *operator new(size_t s) {
54 return User::operator new(s, 2);
55 }
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +000056 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
Owen Anderson9b676982009-08-04 22:55:26 +000057 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
58 Op<0>() = C1;
59 Op<1>() = C2;
60 }
61 /// Transparently provide more efficient getOperand methods.
62 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
63};
64
65/// SelectConstantExpr - This class is private to Constants.cpp, and is used
66/// behind the scenes to implement select constant exprs.
67class SelectConstantExpr : public ConstantExpr {
68 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
69public:
70 // allocate space for exactly three operands
71 void *operator new(size_t s) {
72 return User::operator new(s, 3);
73 }
74 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
75 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
76 Op<0>() = C1;
77 Op<1>() = C2;
78 Op<2>() = C3;
79 }
80 /// Transparently provide more efficient getOperand methods.
81 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
82};
83
84/// ExtractElementConstantExpr - This class is private to
85/// Constants.cpp, and is used behind the scenes to implement
86/// extractelement constant exprs.
87class ExtractElementConstantExpr : public ConstantExpr {
88 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
89public:
90 // allocate space for exactly two operands
91 void *operator new(size_t s) {
92 return User::operator new(s, 2);
93 }
94 ExtractElementConstantExpr(Constant *C1, Constant *C2)
95 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
96 Instruction::ExtractElement, &Op<0>(), 2) {
97 Op<0>() = C1;
98 Op<1>() = C2;
99 }
100 /// Transparently provide more efficient getOperand methods.
101 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
102};
103
104/// InsertElementConstantExpr - This class is private to
105/// Constants.cpp, and is used behind the scenes to implement
106/// insertelement constant exprs.
107class InsertElementConstantExpr : public ConstantExpr {
108 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
109public:
110 // allocate space for exactly three operands
111 void *operator new(size_t s) {
112 return User::operator new(s, 3);
113 }
114 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
115 : ConstantExpr(C1->getType(), Instruction::InsertElement,
116 &Op<0>(), 3) {
117 Op<0>() = C1;
118 Op<1>() = C2;
119 Op<2>() = C3;
120 }
121 /// Transparently provide more efficient getOperand methods.
122 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
123};
124
125/// ShuffleVectorConstantExpr - This class is private to
126/// Constants.cpp, and is used behind the scenes to implement
127/// shufflevector constant exprs.
128class ShuffleVectorConstantExpr : public ConstantExpr {
129 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
130public:
131 // allocate space for exactly three operands
132 void *operator new(size_t s) {
133 return User::operator new(s, 3);
134 }
135 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
136 : ConstantExpr(VectorType::get(
137 cast<VectorType>(C1->getType())->getElementType(),
138 cast<VectorType>(C3->getType())->getNumElements()),
139 Instruction::ShuffleVector,
140 &Op<0>(), 3) {
141 Op<0>() = C1;
142 Op<1>() = C2;
143 Op<2>() = C3;
144 }
145 /// Transparently provide more efficient getOperand methods.
146 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
147};
148
149/// ExtractValueConstantExpr - This class is private to
150/// Constants.cpp, and is used behind the scenes to implement
151/// extractvalue constant exprs.
152class ExtractValueConstantExpr : public ConstantExpr {
153 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
154public:
155 // allocate space for exactly one operand
156 void *operator new(size_t s) {
157 return User::operator new(s, 1);
158 }
159 ExtractValueConstantExpr(Constant *Agg,
160 const SmallVector<unsigned, 4> &IdxList,
161 const Type *DestTy)
162 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
163 Indices(IdxList) {
164 Op<0>() = Agg;
165 }
166
167 /// Indices - These identify which value to extract.
168 const SmallVector<unsigned, 4> Indices;
169
170 /// Transparently provide more efficient getOperand methods.
171 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
172};
173
174/// InsertValueConstantExpr - This class is private to
175/// Constants.cpp, and is used behind the scenes to implement
176/// insertvalue constant exprs.
177class InsertValueConstantExpr : public ConstantExpr {
178 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
179public:
180 // allocate space for exactly one operand
181 void *operator new(size_t s) {
182 return User::operator new(s, 2);
183 }
184 InsertValueConstantExpr(Constant *Agg, Constant *Val,
185 const SmallVector<unsigned, 4> &IdxList,
186 const Type *DestTy)
187 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
188 Indices(IdxList) {
189 Op<0>() = Agg;
190 Op<1>() = Val;
191 }
192
193 /// Indices - These identify the position for the insertion.
194 const SmallVector<unsigned, 4> Indices;
195
196 /// Transparently provide more efficient getOperand methods.
197 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
198};
199
200
201/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
202/// used behind the scenes to implement getelementpr constant exprs.
203class GetElementPtrConstantExpr : public ConstantExpr {
204 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
205 const Type *DestTy);
206public:
207 static GetElementPtrConstantExpr *Create(Constant *C,
208 const std::vector<Constant*>&IdxList,
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +0000209 const Type *DestTy) {
210 return
Owen Anderson9b676982009-08-04 22:55:26 +0000211 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
212 }
213 /// Transparently provide more efficient getOperand methods.
214 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
215};
216
217// CompareConstantExpr - This class is private to Constants.cpp, and is used
218// behind the scenes to implement ICmp and FCmp constant expressions. This is
219// needed in order to store the predicate value for these instructions.
220struct CompareConstantExpr : public ConstantExpr {
221 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
222 // allocate space for exactly two operands
223 void *operator new(size_t s) {
224 return User::operator new(s, 2);
225 }
226 unsigned short predicate;
227 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
228 unsigned short pred, Constant* LHS, Constant* RHS)
229 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
230 Op<0>() = LHS;
231 Op<1>() = RHS;
232 }
233 /// Transparently provide more efficient getOperand methods.
234 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
235};
236
237template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000238struct OperandTraits<UnaryConstantExpr> : public FixedNumOperandTraits<1> {
Owen Anderson9b676982009-08-04 22:55:26 +0000239};
240DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
241
242template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000243struct OperandTraits<BinaryConstantExpr> : public FixedNumOperandTraits<2> {
Owen Anderson9b676982009-08-04 22:55:26 +0000244};
245DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
246
247template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000248struct OperandTraits<SelectConstantExpr> : public FixedNumOperandTraits<3> {
Owen Anderson9b676982009-08-04 22:55:26 +0000249};
250DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
251
252template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000253struct OperandTraits<ExtractElementConstantExpr> : public FixedNumOperandTraits<2> {
Owen Anderson9b676982009-08-04 22:55:26 +0000254};
255DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
256
257template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000258struct OperandTraits<InsertElementConstantExpr> : public FixedNumOperandTraits<3> {
Owen Anderson9b676982009-08-04 22:55:26 +0000259};
260DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
261
262template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000263struct OperandTraits<ShuffleVectorConstantExpr> : public FixedNumOperandTraits<3> {
Owen Anderson9b676982009-08-04 22:55:26 +0000264};
265DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
266
267template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000268struct OperandTraits<ExtractValueConstantExpr> : public FixedNumOperandTraits<1> {
Owen Anderson9b676982009-08-04 22:55:26 +0000269};
270DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
271
272template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000273struct OperandTraits<InsertValueConstantExpr> : public FixedNumOperandTraits<2> {
Owen Anderson9b676982009-08-04 22:55:26 +0000274};
275DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
276
277template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000278struct OperandTraits<GetElementPtrConstantExpr> : public VariadicOperandTraits<1> {
Owen Anderson9b676982009-08-04 22:55:26 +0000279};
280
281DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
282
283
284template <>
Duncan Sands0f5bbb52009-09-06 08:55:57 +0000285struct OperandTraits<CompareConstantExpr> : public FixedNumOperandTraits<2> {
Owen Anderson9b676982009-08-04 22:55:26 +0000286};
287DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
288
289struct ExprMapKeyType {
290 typedef SmallVector<unsigned, 4> IndexList;
291
292 ExprMapKeyType(unsigned opc,
293 const std::vector<Constant*> &ops,
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +0000294 unsigned short pred = 0,
Owen Anderson9b676982009-08-04 22:55:26 +0000295 const IndexList &inds = IndexList())
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +0000296 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
297 uint16_t opcode;
298 uint16_t predicate;
Owen Anderson9b676982009-08-04 22:55:26 +0000299 std::vector<Constant*> operands;
300 IndexList indices;
301 bool operator==(const ExprMapKeyType& that) const {
302 return this->opcode == that.opcode &&
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +0000303 this->predicate == that.predicate &&
Owen Anderson9b676982009-08-04 22:55:26 +0000304 this->operands == that.operands &&
305 this->indices == that.indices;
306 }
307 bool operator<(const ExprMapKeyType & that) const {
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +0000308 return this->opcode < that.opcode ||
309 (this->opcode == that.opcode && this->predicate < that.predicate) ||
310 (this->opcode == that.opcode && this->predicate == that.predicate &&
311 this->operands < that.operands) ||
312 (this->opcode == that.opcode && this->predicate == that.predicate &&
313 this->operands == that.operands && this->indices < that.indices);
Owen Anderson9b676982009-08-04 22:55:26 +0000314 }
315
316 bool operator!=(const ExprMapKeyType& that) const {
317 return !(*this == that);
318 }
319};
320
321// The number of operands for each ConstantCreator::create method is
322// determined by the ConstantTraits template.
323// ConstantCreator - A class that is used to create constants by
324// ValueMap*. This class should be partially specialized if there is
325// something strange that needs to be done to interface to the ctor for the
326// constant.
327//
328template<typename T, typename Alloc>
329struct ConstantTraits< std::vector<T, Alloc> > {
330 static unsigned uses(const std::vector<T, Alloc>& v) {
331 return v.size();
332 }
333};
334
335template<class ConstantClass, class TypeClass, class ValType>
336struct ConstantCreator {
337 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
338 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
339 }
340};
341
342template<class ConstantClass, class TypeClass>
Devang Patelf7188322009-09-03 01:39:20 +0000343struct ConvertConstantType {
Owen Anderson9b676982009-08-04 22:55:26 +0000344 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
345 llvm_unreachable("This type cannot be converted!");
346 }
347};
348
349template<>
350struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
351 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
352 unsigned short pred = 0) {
353 if (Instruction::isCast(V.opcode))
354 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
355 if ((V.opcode >= Instruction::BinaryOpsBegin &&
356 V.opcode < Instruction::BinaryOpsEnd))
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +0000357 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
Owen Anderson9b676982009-08-04 22:55:26 +0000358 if (V.opcode == Instruction::Select)
359 return new SelectConstantExpr(V.operands[0], V.operands[1],
360 V.operands[2]);
361 if (V.opcode == Instruction::ExtractElement)
362 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
363 if (V.opcode == Instruction::InsertElement)
364 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
365 V.operands[2]);
366 if (V.opcode == Instruction::ShuffleVector)
367 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
368 V.operands[2]);
369 if (V.opcode == Instruction::InsertValue)
370 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
371 V.indices, Ty);
372 if (V.opcode == Instruction::ExtractValue)
373 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
374 if (V.opcode == Instruction::GetElementPtr) {
375 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +0000376 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
Owen Anderson9b676982009-08-04 22:55:26 +0000377 }
378
379 // The compare instructions are weird. We have to encode the predicate
380 // value and it is combined with the instruction opcode by multiplying
381 // the opcode by one hundred. We must decode this to get the predicate.
382 if (V.opcode == Instruction::ICmp)
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +0000383 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
Owen Anderson9b676982009-08-04 22:55:26 +0000384 V.operands[0], V.operands[1]);
385 if (V.opcode == Instruction::FCmp)
Daniel Dunbar10ea8bb2009-09-06 00:11:24 +0000386 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
Owen Anderson9b676982009-08-04 22:55:26 +0000387 V.operands[0], V.operands[1]);
388 llvm_unreachable("Invalid ConstantExpr!");
389 return 0;
390 }
391};
392
393template<>
Devang Patelf7188322009-09-03 01:39:20 +0000394struct ConvertConstantType<ConstantExpr, Type> {
Owen Anderson9b676982009-08-04 22:55:26 +0000395 static void convert(ConstantExpr *OldC, const Type *NewTy) {
396 Constant *New;
397 switch (OldC->getOpcode()) {
398 case Instruction::Trunc:
399 case Instruction::ZExt:
400 case Instruction::SExt:
401 case Instruction::FPTrunc:
402 case Instruction::FPExt:
403 case Instruction::UIToFP:
404 case Instruction::SIToFP:
405 case Instruction::FPToUI:
406 case Instruction::FPToSI:
407 case Instruction::PtrToInt:
408 case Instruction::IntToPtr:
409 case Instruction::BitCast:
410 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
411 NewTy);
412 break;
413 case Instruction::Select:
414 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
415 OldC->getOperand(1),
416 OldC->getOperand(2));
417 break;
418 default:
419 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
420 OldC->getOpcode() < Instruction::BinaryOpsEnd);
421 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
422 OldC->getOperand(1));
423 break;
424 case Instruction::GetElementPtr:
425 // Make everyone now use a constant of the new type...
426 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
427 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
428 &Idx[0], Idx.size());
429 break;
430 }
431
432 assert(New != OldC && "Didn't replace constant??");
433 OldC->uncheckedReplaceAllUsesWith(New);
434 OldC->destroyConstant(); // This constant is now dead, destroy it.
435 }
436};
437
438// ConstantAggregateZero does not take extra "value" argument...
439template<class ValType>
440struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
441 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
442 return new ConstantAggregateZero(Ty);
443 }
444};
445
446template<>
Devang Patelf7188322009-09-03 01:39:20 +0000447struct ConvertConstantType<ConstantVector, VectorType> {
Owen Anderson9b676982009-08-04 22:55:26 +0000448 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
449 // Make everyone now use a constant of the new type...
450 std::vector<Constant*> C;
451 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
452 C.push_back(cast<Constant>(OldC->getOperand(i)));
453 Constant *New = ConstantVector::get(NewTy, C);
454 assert(New != OldC && "Didn't replace constant??");
455 OldC->uncheckedReplaceAllUsesWith(New);
456 OldC->destroyConstant(); // This constant is now dead, destroy it.
457 }
458};
459
460template<>
Devang Patelf7188322009-09-03 01:39:20 +0000461struct ConvertConstantType<ConstantAggregateZero, Type> {
Owen Anderson9b676982009-08-04 22:55:26 +0000462 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
463 // Make everyone now use a constant of the new type...
464 Constant *New = ConstantAggregateZero::get(NewTy);
465 assert(New != OldC && "Didn't replace constant??");
466 OldC->uncheckedReplaceAllUsesWith(New);
467 OldC->destroyConstant(); // This constant is now dead, destroy it.
468 }
469};
470
471template<>
Devang Patelf7188322009-09-03 01:39:20 +0000472struct ConvertConstantType<ConstantArray, ArrayType> {
Owen Anderson9b676982009-08-04 22:55:26 +0000473 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
474 // Make everyone now use a constant of the new type...
475 std::vector<Constant*> C;
476 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
477 C.push_back(cast<Constant>(OldC->getOperand(i)));
478 Constant *New = ConstantArray::get(NewTy, C);
479 assert(New != OldC && "Didn't replace constant??");
480 OldC->uncheckedReplaceAllUsesWith(New);
481 OldC->destroyConstant(); // This constant is now dead, destroy it.
482 }
483};
484
485template<>
Devang Patelf7188322009-09-03 01:39:20 +0000486struct ConvertConstantType<ConstantStruct, StructType> {
Owen Anderson9b676982009-08-04 22:55:26 +0000487 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
488 // Make everyone now use a constant of the new type...
489 std::vector<Constant*> C;
490 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
491 C.push_back(cast<Constant>(OldC->getOperand(i)));
492 Constant *New = ConstantStruct::get(NewTy, C);
493 assert(New != OldC && "Didn't replace constant??");
494
495 OldC->uncheckedReplaceAllUsesWith(New);
496 OldC->destroyConstant(); // This constant is now dead, destroy it.
497 }
498};
499
500// ConstantPointerNull does not take extra "value" argument...
501template<class ValType>
502struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
503 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
504 return new ConstantPointerNull(Ty);
505 }
506};
507
508template<>
Devang Patelf7188322009-09-03 01:39:20 +0000509struct ConvertConstantType<ConstantPointerNull, PointerType> {
Owen Anderson9b676982009-08-04 22:55:26 +0000510 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
511 // Make everyone now use a constant of the new type...
512 Constant *New = ConstantPointerNull::get(NewTy);
513 assert(New != OldC && "Didn't replace constant??");
514 OldC->uncheckedReplaceAllUsesWith(New);
515 OldC->destroyConstant(); // This constant is now dead, destroy it.
516 }
517};
518
519// UndefValue does not take extra "value" argument...
520template<class ValType>
521struct ConstantCreator<UndefValue, Type, ValType> {
522 static UndefValue *create(const Type *Ty, const ValType &V) {
523 return new UndefValue(Ty);
524 }
525};
526
527template<>
Devang Patelf7188322009-09-03 01:39:20 +0000528struct ConvertConstantType<UndefValue, Type> {
Owen Anderson9b676982009-08-04 22:55:26 +0000529 static void convert(UndefValue *OldC, const Type *NewTy) {
530 // Make everyone now use a constant of the new type.
531 Constant *New = UndefValue::get(NewTy);
532 assert(New != OldC && "Didn't replace constant??");
533 OldC->uncheckedReplaceAllUsesWith(New);
534 OldC->destroyConstant(); // This constant is now dead, destroy it.
535 }
536};
537
538template<class ValType, class TypeClass, class ConstantClass,
539 bool HasLargeKey = false /*true for arrays and structs*/ >
540class ValueMap : public AbstractTypeUser {
541public:
542 typedef std::pair<const Type*, ValType> MapKey;
Devang Patelf7188322009-09-03 01:39:20 +0000543 typedef std::map<MapKey, Constant *> MapTy;
544 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
Owen Anderson9b676982009-08-04 22:55:26 +0000545 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
546private:
547 /// Map - This is the main map from the element descriptor to the Constants.
548 /// This is the primary way we avoid creating two of the same shape
549 /// constant.
550 MapTy Map;
551
552 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
553 /// from the constants to their element in Map. This is important for
554 /// removal of constants from the array, which would otherwise have to scan
555 /// through the map with very large keys.
556 InverseMapTy InverseMap;
557
558 /// AbstractTypeMap - Map for abstract type constants.
559 ///
560 AbstractTypeMapTy AbstractTypeMap;
561
562 /// ValueMapLock - Mutex for this map.
563 sys::SmartMutex<true> ValueMapLock;
564
565public:
566 // NOTE: This function is not locked. It is the caller's responsibility
567 // to enforce proper synchronization.
Devang Patelc5aa8c62009-08-11 06:31:57 +0000568 typename MapTy::iterator map_begin() { return Map.begin(); }
Owen Anderson9b676982009-08-04 22:55:26 +0000569 typename MapTy::iterator map_end() { return Map.end(); }
Torok Edwind18e6682009-08-31 16:14:59 +0000570
571 void freeConstants() {
572 for (typename MapTy::iterator I=Map.begin(), E=Map.end();
573 I != E; ++I) {
574 if (I->second->use_empty())
575 delete I->second;
576 }
577 }
Owen Anderson9b676982009-08-04 22:55:26 +0000578
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
594private:
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 }
643public:
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 {
Devang Patelf7188322009-09-03 01:39:20 +0000762 ConvertConstantType<ConstantClass,
763 TypeClass>::convert(
Owen Anderson9b676982009-08-04 22:55:26 +0000764 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 {
Chris Lattner34822f62009-08-23 04:44:11 +0000778 DEBUG(errs() << "Constant.cpp: ValueMap\n");
Owen Anderson9b676982009-08-04 22:55:26 +0000779 }
780};
781
782}
783
784#endif