1//===-- LLVMContextImpl.h - The LLVMContextImpl opaque class ----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file declares LLVMContextImpl, the opaque implementation
11//  of LLVMContext.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_LLVMCONTEXT_IMPL_H
16#define LLVM_LLVMCONTEXT_IMPL_H
17
18#include "llvm/LLVMContext.h"
19#include "ConstantsContext.h"
20#include "LeaksContext.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Metadata.h"
24#include "llvm/Support/ValueHandle.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/StringMap.h"
32#include "llvm/ADT/Hashing.h"
33#include <vector>
34
35namespace llvm {
36
37class ConstantInt;
38class ConstantFP;
39class LLVMContext;
40class Type;
41class Value;
42
43struct DenseMapAPIntKeyInfo {
44  struct KeyTy {
45    APInt val;
46    Type* type;
47    KeyTy(const APInt& V, Type* Ty) : val(V), type(Ty) {}
48    KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
49    bool operator==(const KeyTy& that) const {
50      return type == that.type && this->val == that.val;
51    }
52    bool operator!=(const KeyTy& that) const {
53      return !this->operator==(that);
54    }
55    friend hash_code hash_value(const KeyTy &Key) {
56      return hash_combine(Key.type, Key.val);
57    }
58  };
59  static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
60  static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
61  static unsigned getHashValue(const KeyTy &Key) {
62    return static_cast<unsigned>(hash_value(Key));
63  }
64  static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
65    return LHS == RHS;
66  }
67};
68
69struct DenseMapAPFloatKeyInfo {
70  struct KeyTy {
71    APFloat val;
72    KeyTy(const APFloat& V) : val(V){}
73    KeyTy(const KeyTy& that) : val(that.val) {}
74    bool operator==(const KeyTy& that) const {
75      return this->val.bitwiseIsEqual(that.val);
76    }
77    bool operator!=(const KeyTy& that) const {
78      return !this->operator==(that);
79    }
80    friend hash_code hash_value(const KeyTy &Key) {
81      return hash_combine(Key.val);
82    }
83  };
84  static inline KeyTy getEmptyKey() {
85    return KeyTy(APFloat(APFloat::Bogus,1));
86  }
87  static inline KeyTy getTombstoneKey() {
88    return KeyTy(APFloat(APFloat::Bogus,2));
89  }
90  static unsigned getHashValue(const KeyTy &Key) {
91    return static_cast<unsigned>(hash_value(Key));
92  }
93  static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
94    return LHS == RHS;
95  }
96};
97
98struct AnonStructTypeKeyInfo {
99  struct KeyTy {
100    ArrayRef<Type*> ETypes;
101    bool isPacked;
102    KeyTy(const ArrayRef<Type*>& E, bool P) :
103      ETypes(E), isPacked(P) {}
104    KeyTy(const KeyTy& that) :
105      ETypes(that.ETypes), isPacked(that.isPacked) {}
106    KeyTy(const StructType* ST) :
107      ETypes(ArrayRef<Type*>(ST->element_begin(), ST->element_end())),
108      isPacked(ST->isPacked()) {}
109    bool operator==(const KeyTy& that) const {
110      if (isPacked != that.isPacked)
111        return false;
112      if (ETypes != that.ETypes)
113        return false;
114      return true;
115    }
116    bool operator!=(const KeyTy& that) const {
117      return !this->operator==(that);
118    }
119  };
120  static inline StructType* getEmptyKey() {
121    return DenseMapInfo<StructType*>::getEmptyKey();
122  }
123  static inline StructType* getTombstoneKey() {
124    return DenseMapInfo<StructType*>::getTombstoneKey();
125  }
126  static unsigned getHashValue(const KeyTy& Key) {
127    return hash_combine(hash_combine_range(Key.ETypes.begin(),
128                                           Key.ETypes.end()),
129                        Key.isPacked);
130  }
131  static unsigned getHashValue(const StructType *ST) {
132    return getHashValue(KeyTy(ST));
133  }
134  static bool isEqual(const KeyTy& LHS, const StructType *RHS) {
135    if (RHS == getEmptyKey() || RHS == getTombstoneKey())
136      return false;
137    return LHS == KeyTy(RHS);
138  }
139  static bool isEqual(const StructType *LHS, const StructType *RHS) {
140    return LHS == RHS;
141  }
142};
143
144struct FunctionTypeKeyInfo {
145  struct KeyTy {
146    const Type *ReturnType;
147    ArrayRef<Type*> Params;
148    bool isVarArg;
149    KeyTy(const Type* R, const ArrayRef<Type*>& P, bool V) :
150      ReturnType(R), Params(P), isVarArg(V) {}
151    KeyTy(const KeyTy& that) :
152      ReturnType(that.ReturnType),
153      Params(that.Params),
154      isVarArg(that.isVarArg) {}
155    KeyTy(const FunctionType* FT) :
156      ReturnType(FT->getReturnType()),
157      Params(ArrayRef<Type*>(FT->param_begin(), FT->param_end())),
158      isVarArg(FT->isVarArg()) {}
159    bool operator==(const KeyTy& that) const {
160      if (ReturnType != that.ReturnType)
161        return false;
162      if (isVarArg != that.isVarArg)
163        return false;
164      if (Params != that.Params)
165        return false;
166      return true;
167    }
168    bool operator!=(const KeyTy& that) const {
169      return !this->operator==(that);
170    }
171  };
172  static inline FunctionType* getEmptyKey() {
173    return DenseMapInfo<FunctionType*>::getEmptyKey();
174  }
175  static inline FunctionType* getTombstoneKey() {
176    return DenseMapInfo<FunctionType*>::getTombstoneKey();
177  }
178  static unsigned getHashValue(const KeyTy& Key) {
179    return hash_combine(Key.ReturnType,
180                        hash_combine_range(Key.Params.begin(),
181                                           Key.Params.end()),
182                        Key.isVarArg);
183  }
184  static unsigned getHashValue(const FunctionType *FT) {
185    return getHashValue(KeyTy(FT));
186  }
187  static bool isEqual(const KeyTy& LHS, const FunctionType *RHS) {
188    if (RHS == getEmptyKey() || RHS == getTombstoneKey())
189      return false;
190    return LHS == KeyTy(RHS);
191  }
192  static bool isEqual(const FunctionType *LHS, const FunctionType *RHS) {
193    return LHS == RHS;
194  }
195};
196
197// Provide a FoldingSetTrait::Equals specialization for MDNode that can use a
198// shortcut to avoid comparing all operands.
199template<> struct FoldingSetTrait<MDNode> : DefaultFoldingSetTrait<MDNode> {
200  static bool Equals(const MDNode &X, const FoldingSetNodeID &ID,
201                     unsigned IDHash, FoldingSetNodeID &TempID) {
202    assert(!X.isNotUniqued() && "Non-uniqued MDNode in FoldingSet?");
203    // First, check if the cached hashes match.  If they don't we can skip the
204    // expensive operand walk.
205    if (X.Hash != IDHash)
206      return false;
207
208    // If they match we have to compare the operands.
209    X.Profile(TempID);
210    return TempID == ID;
211  }
212  static unsigned ComputeHash(const MDNode &X, FoldingSetNodeID &) {
213    return X.Hash; // Return cached hash.
214  }
215};
216
217/// DebugRecVH - This is a CallbackVH used to keep the Scope -> index maps
218/// up to date as MDNodes mutate.  This class is implemented in DebugLoc.cpp.
219class DebugRecVH : public CallbackVH {
220  /// Ctx - This is the LLVM Context being referenced.
221  LLVMContextImpl *Ctx;
222
223  /// Idx - The index into either ScopeRecordIdx or ScopeInlinedAtRecords that
224  /// this reference lives in.  If this is zero, then it represents a
225  /// non-canonical entry that has no DenseMap value.  This can happen due to
226  /// RAUW.
227  int Idx;
228public:
229  DebugRecVH(MDNode *n, LLVMContextImpl *ctx, int idx)
230    : CallbackVH(n), Ctx(ctx), Idx(idx) {}
231
232  MDNode *get() const {
233    return cast_or_null<MDNode>(getValPtr());
234  }
235
236  virtual void deleted();
237  virtual void allUsesReplacedWith(Value *VNew);
238};
239
240class LLVMContextImpl {
241public:
242  /// OwnedModules - The set of modules instantiated in this context, and which
243  /// will be automatically deleted if this context is deleted.
244  SmallPtrSet<Module*, 4> OwnedModules;
245
246  LLVMContext::InlineAsmDiagHandlerTy InlineAsmDiagHandler;
247  void *InlineAsmDiagContext;
248
249  typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
250                         DenseMapAPIntKeyInfo> IntMapTy;
251  IntMapTy IntConstants;
252
253  typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
254                         DenseMapAPFloatKeyInfo> FPMapTy;
255  FPMapTy FPConstants;
256
257  StringMap<Value*> MDStringCache;
258
259  FoldingSet<MDNode> MDNodeSet;
260  // MDNodes may be uniqued or not uniqued.  When they're not uniqued, they
261  // aren't in the MDNodeSet, but they're still shared between objects, so no
262  // one object can destroy them.  This set allows us to at least destroy them
263  // on Context destruction.
264  SmallPtrSet<MDNode*, 1> NonUniquedMDNodes;
265
266  DenseMap<Type*, ConstantAggregateZero*> CAZConstants;
267
268  typedef ConstantAggrUniqueMap<ArrayType, ConstantArray> ArrayConstantsTy;
269  ArrayConstantsTy ArrayConstants;
270
271  typedef ConstantAggrUniqueMap<StructType, ConstantStruct> StructConstantsTy;
272  StructConstantsTy StructConstants;
273
274  typedef ConstantAggrUniqueMap<VectorType, ConstantVector> VectorConstantsTy;
275  VectorConstantsTy VectorConstants;
276
277  DenseMap<PointerType*, ConstantPointerNull*> CPNConstants;
278
279  DenseMap<Type*, UndefValue*> UVConstants;
280
281  StringMap<ConstantDataSequential*> CDSConstants;
282
283
284  DenseMap<std::pair<Function*, BasicBlock*> , BlockAddress*> BlockAddresses;
285  ConstantUniqueMap<ExprMapKeyType, const ExprMapKeyType&, Type, ConstantExpr>
286    ExprConstants;
287
288  ConstantUniqueMap<InlineAsmKeyType, const InlineAsmKeyType&, PointerType,
289                    InlineAsm> InlineAsms;
290
291  ConstantInt *TheTrueVal;
292  ConstantInt *TheFalseVal;
293
294  LeakDetectorImpl<Value> LLVMObjects;
295
296  // Basic type instances.
297  Type VoidTy, LabelTy, HalfTy, FloatTy, DoubleTy, MetadataTy;
298  Type X86_FP80Ty, FP128Ty, PPC_FP128Ty, X86_MMXTy;
299  IntegerType Int1Ty, Int8Ty, Int16Ty, Int32Ty, Int64Ty;
300
301
302  /// TypeAllocator - All dynamically allocated types are allocated from this.
303  /// They live forever until the context is torn down.
304  BumpPtrAllocator TypeAllocator;
305
306  DenseMap<unsigned, IntegerType*> IntegerTypes;
307
308  typedef DenseMap<FunctionType*, bool, FunctionTypeKeyInfo> FunctionTypeMap;
309  FunctionTypeMap FunctionTypes;
310  typedef DenseMap<StructType*, bool, AnonStructTypeKeyInfo> StructTypeMap;
311  StructTypeMap AnonStructTypes;
312  StringMap<StructType*> NamedStructTypes;
313  unsigned NamedStructTypesUniqueID;
314
315  DenseMap<std::pair<Type *, uint64_t>, ArrayType*> ArrayTypes;
316  DenseMap<std::pair<Type *, unsigned>, VectorType*> VectorTypes;
317  DenseMap<Type*, PointerType*> PointerTypes;  // Pointers in AddrSpace = 0
318  DenseMap<std::pair<Type*, unsigned>, PointerType*> ASPointerTypes;
319
320
321  /// ValueHandles - This map keeps track of all of the value handles that are
322  /// watching a Value*.  The Value::HasValueHandle bit is used to know
323  // whether or not a value has an entry in this map.
324  typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
325  ValueHandlesTy ValueHandles;
326
327  /// CustomMDKindNames - Map to hold the metadata string to ID mapping.
328  StringMap<unsigned> CustomMDKindNames;
329
330  typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
331  typedef SmallVector<MDPairTy, 2> MDMapTy;
332
333  /// MetadataStore - Collection of per-instruction metadata used in this
334  /// context.
335  DenseMap<const Instruction *, MDMapTy> MetadataStore;
336
337  /// ScopeRecordIdx - This is the index in ScopeRecords for an MDNode scope
338  /// entry with no "inlined at" element.
339  DenseMap<MDNode*, int> ScopeRecordIdx;
340
341  /// ScopeRecords - These are the actual mdnodes (in a value handle) for an
342  /// index.  The ValueHandle ensures that ScopeRecordIdx stays up to date if
343  /// the MDNode is RAUW'd.
344  std::vector<DebugRecVH> ScopeRecords;
345
346  /// ScopeInlinedAtIdx - This is the index in ScopeInlinedAtRecords for an
347  /// scope/inlined-at pair.
348  DenseMap<std::pair<MDNode*, MDNode*>, int> ScopeInlinedAtIdx;
349
350  /// ScopeInlinedAtRecords - These are the actual mdnodes (in value handles)
351  /// for an index.  The ValueHandle ensures that ScopeINlinedAtIdx stays up
352  /// to date.
353  std::vector<std::pair<DebugRecVH, DebugRecVH> > ScopeInlinedAtRecords;
354
355  int getOrAddScopeRecordIdxEntry(MDNode *N, int ExistingIdx);
356  int getOrAddScopeInlinedAtIdxEntry(MDNode *Scope, MDNode *IA,int ExistingIdx);
357
358  LLVMContextImpl(LLVMContext &C);
359  ~LLVMContextImpl();
360};
361
362}
363
364#endif
365