1 //===----------------- LLVMContextImpl.h - Implementation ------*- C++ -*--===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares LLVMContextImpl, the opaque implementation
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_LLVMCONTEXT_IMPL_H
16 #define LLVM_LLVMCONTEXT_IMPL_H
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/System/Mutex.h"
24 #include "llvm/System/RWMutex.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/FoldingSet.h"
29 #include "llvm/ADT/StringMap.h"
34 template<class ValType>
35 struct ConstantTraits;
37 // The number of operands for each ConstantCreator::create method is
38 // determined by the ConstantTraits template.
39 // ConstantCreator - A class that is used to create constants by
40 // ValueMap*. This class should be partially specialized if there is
41 // something strange that needs to be done to interface to the ctor for the
44 template<typename T, typename Alloc>
45 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
46 static unsigned uses(const std::vector<T, Alloc>& v) {
51 template<class ConstantClass, class TypeClass, class ValType>
52 struct VISIBILITY_HIDDEN ConstantCreator {
53 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
54 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
58 template<class ConstantClass, class TypeClass>
59 struct VISIBILITY_HIDDEN ConvertConstantType {
60 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
61 llvm_unreachable("This type cannot be converted!");
65 // ConstantAggregateZero does not take extra "value" argument...
66 template<class ValType>
67 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
68 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
69 return new ConstantAggregateZero(Ty);
74 struct ConvertConstantType<ConstantAggregateZero, Type> {
75 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
76 // Make everyone now use a constant of the new type...
77 Constant *New = NewTy->getContext().getConstantAggregateZero(NewTy);
78 assert(New != OldC && "Didn't replace constant??");
79 OldC->uncheckedReplaceAllUsesWith(New);
80 OldC->destroyConstant(); // This constant is now dead, destroy it.
85 struct ConvertConstantType<ConstantArray, ArrayType> {
86 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
87 // Make everyone now use a constant of the new type...
88 std::vector<Constant*> C;
89 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
90 C.push_back(cast<Constant>(OldC->getOperand(i)));
91 Constant *New = NewTy->getContext().getConstantArray(NewTy, C);
92 assert(New != OldC && "Didn't replace constant??");
93 OldC->uncheckedReplaceAllUsesWith(New);
94 OldC->destroyConstant(); // This constant is now dead, destroy it.
99 struct ConvertConstantType<ConstantStruct, StructType> {
100 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
101 // Make everyone now use a constant of the new type...
102 std::vector<Constant*> C;
103 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
104 C.push_back(cast<Constant>(OldC->getOperand(i)));
105 Constant *New = ConstantStruct::get(NewTy, C);
106 assert(New != OldC && "Didn't replace constant??");
108 OldC->uncheckedReplaceAllUsesWith(New);
109 OldC->destroyConstant(); // This constant is now dead, destroy it.
114 struct ConvertConstantType<ConstantVector, VectorType> {
115 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
116 // Make everyone now use a constant of the new type...
117 std::vector<Constant*> C;
118 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
119 C.push_back(cast<Constant>(OldC->getOperand(i)));
120 Constant *New = OldC->getContext().getConstantVector(NewTy, C);
121 assert(New != OldC && "Didn't replace constant??");
122 OldC->uncheckedReplaceAllUsesWith(New);
123 OldC->destroyConstant(); // This constant is now dead, destroy it.
127 template<class ValType, class TypeClass, class ConstantClass,
128 bool HasLargeKey = false /*true for arrays and structs*/ >
129 class ValueMap : public AbstractTypeUser {
131 typedef std::pair<const Type*, ValType> MapKey;
132 typedef std::map<MapKey, Constant *> MapTy;
133 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
134 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
136 /// Map - This is the main map from the element descriptor to the Constants.
137 /// This is the primary way we avoid creating two of the same shape
141 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
142 /// from the constants to their element in Map. This is important for
143 /// removal of constants from the array, which would otherwise have to scan
144 /// through the map with very large keys.
145 InverseMapTy InverseMap;
147 /// AbstractTypeMap - Map for abstract type constants.
149 AbstractTypeMapTy AbstractTypeMap;
151 /// ValueMapLock - Mutex for this map.
152 sys::SmartMutex<true> ValueMapLock;
155 // NOTE: This function is not locked. It is the caller's responsibility
156 // to enforce proper synchronization.
157 typename MapTy::iterator map_end() { return Map.end(); }
159 /// InsertOrGetItem - Return an iterator for the specified element.
160 /// If the element exists in the map, the returned iterator points to the
161 /// entry and Exists=true. If not, the iterator points to the newly
162 /// inserted entry and returns Exists=false. Newly inserted entries have
163 /// I->second == 0, and should be filled in.
164 /// NOTE: This function is not locked. It is the caller's responsibility
165 // to enforce proper synchronization.
166 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
169 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
175 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
177 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
178 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
179 IMI->second->second == CP &&
180 "InverseMap corrupt!");
184 typename MapTy::iterator I =
185 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
187 if (I == Map.end() || I->second != CP) {
188 // FIXME: This should not use a linear scan. If this gets to be a
189 // performance problem, someone should look at this.
190 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
196 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
197 typename MapTy::iterator I) {
198 ConstantClass* Result =
199 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
201 assert(Result->getType() == Ty && "Type specified is not correct!");
202 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
204 if (HasLargeKey) // Remember the reverse mapping if needed.
205 InverseMap.insert(std::make_pair(Result, I));
207 // If the type of the constant is abstract, make sure that an entry
208 // exists for it in the AbstractTypeMap.
209 if (Ty->isAbstract()) {
210 typename AbstractTypeMapTy::iterator TI =
211 AbstractTypeMap.find(Ty);
213 if (TI == AbstractTypeMap.end()) {
214 // Add ourselves to the ATU list of the type.
215 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
217 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
225 /// getOrCreate - Return the specified constant from the map, creating it if
227 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
228 sys::SmartScopedLock<true> Lock(ValueMapLock);
229 MapKey Lookup(Ty, V);
230 ConstantClass* Result = 0;
232 typename MapTy::iterator I = Map.find(Lookup);
235 Result = static_cast<ConstantClass *>(I->second);
238 // If no preexisting value, create one now...
239 Result = Create(Ty, V, I);
245 void remove(ConstantClass *CP) {
246 sys::SmartScopedLock<true> Lock(ValueMapLock);
247 typename MapTy::iterator I = FindExistingElement(CP);
248 assert(I != Map.end() && "Constant not found in constant table!");
249 assert(I->second == CP && "Didn't find correct element?");
251 if (HasLargeKey) // Remember the reverse mapping if needed.
252 InverseMap.erase(CP);
254 // Now that we found the entry, make sure this isn't the entry that
255 // the AbstractTypeMap points to.
256 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
257 if (Ty->isAbstract()) {
258 assert(AbstractTypeMap.count(Ty) &&
259 "Abstract type not in AbstractTypeMap?");
260 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
261 if (ATMEntryIt == I) {
262 // Yes, we are removing the representative entry for this type.
263 // See if there are any other entries of the same type.
264 typename MapTy::iterator TmpIt = ATMEntryIt;
266 // First check the entry before this one...
267 if (TmpIt != Map.begin()) {
269 if (TmpIt->first.first != Ty) // Not the same type, move back...
273 // If we didn't find the same type, try to move forward...
274 if (TmpIt == ATMEntryIt) {
276 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
277 --TmpIt; // No entry afterwards with the same type
280 // If there is another entry in the map of the same abstract type,
281 // update the AbstractTypeMap entry now.
282 if (TmpIt != ATMEntryIt) {
285 // Otherwise, we are removing the last instance of this type
286 // from the table. Remove from the ATM, and from user list.
287 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
288 AbstractTypeMap.erase(Ty);
297 /// MoveConstantToNewSlot - If we are about to change C to be the element
298 /// specified by I, update our internal data structures to reflect this
300 /// NOTE: This function is not locked. It is the responsibility of the
301 /// caller to enforce proper synchronization if using this method.
302 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
303 // First, remove the old location of the specified constant in the map.
304 typename MapTy::iterator OldI = FindExistingElement(C);
305 assert(OldI != Map.end() && "Constant not found in constant table!");
306 assert(OldI->second == C && "Didn't find correct element?");
308 // If this constant is the representative element for its abstract type,
309 // update the AbstractTypeMap so that the representative element is I.
310 if (C->getType()->isAbstract()) {
311 typename AbstractTypeMapTy::iterator ATI =
312 AbstractTypeMap.find(C->getType());
313 assert(ATI != AbstractTypeMap.end() &&
314 "Abstract type not in AbstractTypeMap?");
315 if (ATI->second == OldI)
319 // Remove the old entry from the map.
322 // Update the inverse map so that we know that this constant is now
323 // located at descriptor I.
325 assert(I->second == C && "Bad inversemap entry!");
330 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
331 sys::SmartScopedLock<true> Lock(ValueMapLock);
332 typename AbstractTypeMapTy::iterator I =
333 AbstractTypeMap.find(cast<Type>(OldTy));
335 assert(I != AbstractTypeMap.end() &&
336 "Abstract type not in AbstractTypeMap?");
338 // Convert a constant at a time until the last one is gone. The last one
339 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
340 // eliminated eventually.
342 ConvertConstantType<ConstantClass,
344 static_cast<ConstantClass *>(I->second->second),
345 cast<TypeClass>(NewTy));
347 I = AbstractTypeMap.find(cast<Type>(OldTy));
348 } while (I != AbstractTypeMap.end());
351 // If the type became concrete without being refined to any other existing
352 // type, we just remove ourselves from the ATU list.
353 void typeBecameConcrete(const DerivedType *AbsTy) {
354 AbsTy->removeAbstractTypeUser(this);
358 DOUT << "Constant.cpp: ValueMap\n";
371 struct DenseMapAPIntKeyInfo {
375 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
376 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
377 bool operator==(const KeyTy& that) const {
378 return type == that.type && this->val == that.val;
380 bool operator!=(const KeyTy& that) const {
381 return !this->operator==(that);
384 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
385 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
386 static unsigned getHashValue(const KeyTy &Key) {
387 return DenseMapInfo<void*>::getHashValue(Key.type) ^
388 Key.val.getHashValue();
390 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
393 static bool isPod() { return false; }
396 struct DenseMapAPFloatKeyInfo {
399 KeyTy(const APFloat& V) : val(V){}
400 KeyTy(const KeyTy& that) : val(that.val) {}
401 bool operator==(const KeyTy& that) const {
402 return this->val.bitwiseIsEqual(that.val);
404 bool operator!=(const KeyTy& that) const {
405 return !this->operator==(that);
408 static inline KeyTy getEmptyKey() {
409 return KeyTy(APFloat(APFloat::Bogus,1));
411 static inline KeyTy getTombstoneKey() {
412 return KeyTy(APFloat(APFloat::Bogus,2));
414 static unsigned getHashValue(const KeyTy &Key) {
415 return Key.val.getHashValue();
417 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
420 static bool isPod() { return false; }
423 class LLVMContextImpl {
424 sys::SmartRWMutex<true> ConstantsLock;
426 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
427 DenseMapAPIntKeyInfo> IntMapTy;
428 IntMapTy IntConstants;
430 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
431 DenseMapAPFloatKeyInfo> FPMapTy;
434 StringMap<MDString*> MDStringCache;
436 FoldingSet<MDNode> MDNodeSet;
438 ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
440 typedef ValueMap<std::vector<Constant*>, ArrayType,
441 ConstantArray, true /*largekey*/> ArrayConstantsTy;
442 ArrayConstantsTy ArrayConstants;
444 typedef ValueMap<std::vector<Constant*>, StructType,
445 ConstantStruct, true /*largekey*/> StructConstantsTy;
446 StructConstantsTy StructConstants;
448 typedef ValueMap<std::vector<Constant*>, VectorType,
449 ConstantVector> VectorConstantsTy;
450 VectorConstantsTy VectorConstants;
452 LLVMContext &Context;
453 ConstantInt *TheTrueVal;
454 ConstantInt *TheFalseVal;
457 LLVMContextImpl(const LLVMContextImpl&);
459 friend class ConstantInt;
460 friend class ConstantFP;
461 friend class ConstantStruct;
463 LLVMContextImpl(LLVMContext &C);
465 MDString *getMDString(const char *StrBegin, unsigned StrLength);
467 MDNode *getMDNode(Value*const* Vals, unsigned NumVals);
469 ConstantAggregateZero *getConstantAggregateZero(const Type *Ty);
471 Constant *getConstantArray(const ArrayType *Ty,
472 const std::vector<Constant*> &V);
474 Constant *getConstantVector(const VectorType *Ty,
475 const std::vector<Constant*> &V);
477 ConstantInt *getTrue() {
481 return (TheTrueVal = ConstantInt::get(IntegerType::get(1), 1));
484 ConstantInt *getFalse() {
488 return (TheFalseVal = ConstantInt::get(IntegerType::get(1), 0));
491 void erase(MDString *M);
492 void erase(MDNode *M);
493 void erase(ConstantAggregateZero *Z);
494 void erase(ConstantArray *C);
495 void erase(ConstantVector *V);
499 Constant *replaceUsesOfWithOnConstant(ConstantArray *CA, Value *From,