[PM] Add pass run listeners to the pass manager.
[oota-llvm.git] / lib / IR / LLVMContextImpl.h
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 "AttributeImpl.h"
19 #include "ConstantsContext.h"
20 #include "LeaksContext.h"
21 #include "llvm/ADT/APFloat.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/FoldingSet.h"
26 #include "llvm/ADT/Hashing.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include <vector>
35
36 namespace llvm {
37
38 class ConstantInt;
39 class ConstantFP;
40 class LLVMContext;
41 class Type;
42 class Value;
43 struct PassRunListener;
44
45 struct DenseMapAPIntKeyInfo {
46   struct KeyTy {
47     APInt val;
48     Type* type;
49     KeyTy(const APInt& V, Type* Ty) : val(V), type(Ty) {}
50     bool operator==(const KeyTy& that) const {
51       return type == that.type && this->val == that.val;
52     }
53     bool operator!=(const KeyTy& that) const {
54       return !this->operator==(that);
55     }
56     friend hash_code hash_value(const KeyTy &Key) {
57       return hash_combine(Key.type, Key.val);
58     }
59   };
60   static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), nullptr); }
61   static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), nullptr); }
62   static unsigned getHashValue(const KeyTy &Key) {
63     return static_cast<unsigned>(hash_value(Key));
64   }
65   static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
66     return LHS == RHS;
67   }
68 };
69
70 struct DenseMapAPFloatKeyInfo {
71   struct KeyTy {
72     APFloat val;
73     KeyTy(const APFloat& V) : val(V){}
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
98 struct 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 StructType* ST) :
105       ETypes(ArrayRef<Type*>(ST->element_begin(), ST->element_end())),
106       isPacked(ST->isPacked()) {}
107     bool operator==(const KeyTy& that) const {
108       if (isPacked != that.isPacked)
109         return false;
110       if (ETypes != that.ETypes)
111         return false;
112       return true;
113     }
114     bool operator!=(const KeyTy& that) const {
115       return !this->operator==(that);
116     }
117   };
118   static inline StructType* getEmptyKey() {
119     return DenseMapInfo<StructType*>::getEmptyKey();
120   }
121   static inline StructType* getTombstoneKey() {
122     return DenseMapInfo<StructType*>::getTombstoneKey();
123   }
124   static unsigned getHashValue(const KeyTy& Key) {
125     return hash_combine(hash_combine_range(Key.ETypes.begin(),
126                                            Key.ETypes.end()),
127                         Key.isPacked);
128   }
129   static unsigned getHashValue(const StructType *ST) {
130     return getHashValue(KeyTy(ST));
131   }
132   static bool isEqual(const KeyTy& LHS, const StructType *RHS) {
133     if (RHS == getEmptyKey() || RHS == getTombstoneKey())
134       return false;
135     return LHS == KeyTy(RHS);
136   }
137   static bool isEqual(const StructType *LHS, const StructType *RHS) {
138     return LHS == RHS;
139   }
140 };
141
142 struct FunctionTypeKeyInfo {
143   struct KeyTy {
144     const Type *ReturnType;
145     ArrayRef<Type*> Params;
146     bool isVarArg;
147     KeyTy(const Type* R, const ArrayRef<Type*>& P, bool V) :
148       ReturnType(R), Params(P), isVarArg(V) {}
149     KeyTy(const FunctionType* FT) :
150       ReturnType(FT->getReturnType()),
151       Params(ArrayRef<Type*>(FT->param_begin(), FT->param_end())),
152       isVarArg(FT->isVarArg()) {}
153     bool operator==(const KeyTy& that) const {
154       if (ReturnType != that.ReturnType)
155         return false;
156       if (isVarArg != that.isVarArg)
157         return false;
158       if (Params != that.Params)
159         return false;
160       return true;
161     }
162     bool operator!=(const KeyTy& that) const {
163       return !this->operator==(that);
164     }
165   };
166   static inline FunctionType* getEmptyKey() {
167     return DenseMapInfo<FunctionType*>::getEmptyKey();
168   }
169   static inline FunctionType* getTombstoneKey() {
170     return DenseMapInfo<FunctionType*>::getTombstoneKey();
171   }
172   static unsigned getHashValue(const KeyTy& Key) {
173     return hash_combine(Key.ReturnType,
174                         hash_combine_range(Key.Params.begin(),
175                                            Key.Params.end()),
176                         Key.isVarArg);
177   }
178   static unsigned getHashValue(const FunctionType *FT) {
179     return getHashValue(KeyTy(FT));
180   }
181   static bool isEqual(const KeyTy& LHS, const FunctionType *RHS) {
182     if (RHS == getEmptyKey() || RHS == getTombstoneKey())
183       return false;
184     return LHS == KeyTy(RHS);
185   }
186   static bool isEqual(const FunctionType *LHS, const FunctionType *RHS) {
187     return LHS == RHS;
188   }
189 };
190
191 // Provide a FoldingSetTrait::Equals specialization for MDNode that can use a
192 // shortcut to avoid comparing all operands.
193 template<> struct FoldingSetTrait<MDNode> : DefaultFoldingSetTrait<MDNode> {
194   static bool Equals(const MDNode &X, const FoldingSetNodeID &ID,
195                      unsigned IDHash, FoldingSetNodeID &TempID) {
196     assert(!X.isNotUniqued() && "Non-uniqued MDNode in FoldingSet?");
197     // First, check if the cached hashes match.  If they don't we can skip the
198     // expensive operand walk.
199     if (X.Hash != IDHash)
200       return false;
201
202     // If they match we have to compare the operands.
203     X.Profile(TempID);
204     return TempID == ID;
205   }
206   static unsigned ComputeHash(const MDNode &X, FoldingSetNodeID &) {
207     return X.Hash; // Return cached hash.
208   }
209 };
210
211 /// DebugRecVH - This is a CallbackVH used to keep the Scope -> index maps
212 /// up to date as MDNodes mutate.  This class is implemented in DebugLoc.cpp.
213 class DebugRecVH : public CallbackVH {
214   /// Ctx - This is the LLVM Context being referenced.
215   LLVMContextImpl *Ctx;
216   
217   /// Idx - The index into either ScopeRecordIdx or ScopeInlinedAtRecords that
218   /// this reference lives in.  If this is zero, then it represents a
219   /// non-canonical entry that has no DenseMap value.  This can happen due to
220   /// RAUW.
221   int Idx;
222 public:
223   DebugRecVH(MDNode *n, LLVMContextImpl *ctx, int idx)
224     : CallbackVH(n), Ctx(ctx), Idx(idx) {}
225   
226   MDNode *get() const {
227     return cast_or_null<MDNode>(getValPtr());
228   }
229
230   void deleted() override;
231   void allUsesReplacedWith(Value *VNew) override;
232 };
233   
234 class LLVMContextImpl {
235 public:
236   /// OwnedModules - The set of modules instantiated in this context, and which
237   /// will be automatically deleted if this context is deleted.
238   SmallPtrSet<Module*, 4> OwnedModules;
239   
240   LLVMContext::InlineAsmDiagHandlerTy InlineAsmDiagHandler;
241   void *InlineAsmDiagContext;
242
243   LLVMContext::DiagnosticHandlerTy DiagnosticHandler;
244   void *DiagnosticContext;
245
246   typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt *,
247                    DenseMapAPIntKeyInfo> IntMapTy;
248   IntMapTy IntConstants;
249   
250   typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*, 
251                          DenseMapAPFloatKeyInfo> FPMapTy;
252   FPMapTy FPConstants;
253
254   FoldingSet<AttributeImpl> AttrsSet;
255   FoldingSet<AttributeSetImpl> AttrsLists;
256   FoldingSet<AttributeSetNode> AttrsSetNodes;
257
258   StringMap<Value*> MDStringCache;
259
260   FoldingSet<MDNode> MDNodeSet;
261
262   // MDNodes may be uniqued or not uniqued.  When they're not uniqued, they
263   // aren't in the MDNodeSet, but they're still shared between objects, so no
264   // one object can destroy them.  This set allows us to at least destroy them
265   // on Context destruction.
266   SmallPtrSet<MDNode*, 1> NonUniquedMDNodes;
267   
268   DenseMap<Type*, ConstantAggregateZero*> CAZConstants;
269
270   typedef ConstantAggrUniqueMap<ArrayType, ConstantArray> ArrayConstantsTy;
271   ArrayConstantsTy ArrayConstants;
272   
273   typedef ConstantAggrUniqueMap<StructType, ConstantStruct> StructConstantsTy;
274   StructConstantsTy StructConstants;
275   
276   typedef ConstantAggrUniqueMap<VectorType, ConstantVector> VectorConstantsTy;
277   VectorConstantsTy VectorConstants;
278   
279   DenseMap<PointerType*, ConstantPointerNull*> CPNConstants;
280
281   DenseMap<Type*, UndefValue*> UVConstants;
282   
283   StringMap<ConstantDataSequential*> CDSConstants;
284
285   DenseMap<std::pair<const Function *, const BasicBlock *>, BlockAddress *>
286     BlockAddresses;
287   ConstantUniqueMap<ExprMapKeyType, const ExprMapKeyType&, Type, ConstantExpr>
288     ExprConstants;
289
290   ConstantUniqueMap<InlineAsmKeyType, const InlineAsmKeyType&, PointerType,
291                     InlineAsm> InlineAsms;
292   
293   ConstantInt *TheTrueVal;
294   ConstantInt *TheFalseVal;
295   
296   LeakDetectorImpl<Value> LLVMObjects;
297   
298   // Basic type instances.
299   Type VoidTy, LabelTy, HalfTy, FloatTy, DoubleTy, MetadataTy;
300   Type X86_FP80Ty, FP128Ty, PPC_FP128Ty, X86_MMXTy;
301   IntegerType Int1Ty, Int8Ty, Int16Ty, Int32Ty, Int64Ty;
302
303   
304   /// TypeAllocator - All dynamically allocated types are allocated from this.
305   /// They live forever until the context is torn down.
306   BumpPtrAllocator TypeAllocator;
307   
308   DenseMap<unsigned, IntegerType*> IntegerTypes;
309   
310   typedef DenseMap<FunctionType*, bool, FunctionTypeKeyInfo> FunctionTypeMap;
311   FunctionTypeMap FunctionTypes;
312   typedef DenseMap<StructType*, bool, AnonStructTypeKeyInfo> StructTypeMap;
313   StructTypeMap AnonStructTypes;
314   StringMap<StructType*> NamedStructTypes;
315   unsigned NamedStructTypesUniqueID;
316     
317   DenseMap<std::pair<Type *, uint64_t>, ArrayType*> ArrayTypes;
318   DenseMap<std::pair<Type *, unsigned>, VectorType*> VectorTypes;
319   DenseMap<Type*, PointerType*> PointerTypes;  // Pointers in AddrSpace = 0
320   DenseMap<std::pair<Type*, unsigned>, PointerType*> ASPointerTypes;
321
322
323   /// ValueHandles - This map keeps track of all of the value handles that are
324   /// watching a Value*.  The Value::HasValueHandle bit is used to know
325   /// whether or not a value has an entry in this map.
326   typedef DenseMap<Value*, ValueHandleBase*> ValueHandlesTy;
327   ValueHandlesTy ValueHandles;
328   
329   /// CustomMDKindNames - Map to hold the metadata string to ID mapping.
330   StringMap<unsigned> CustomMDKindNames;
331   
332   typedef std::pair<unsigned, TrackingVH<MDNode> > MDPairTy;
333   typedef SmallVector<MDPairTy, 2> MDMapTy;
334
335   /// MetadataStore - Collection of per-instruction metadata used in this
336   /// context.
337   DenseMap<const Instruction *, MDMapTy> MetadataStore;
338   
339   /// ScopeRecordIdx - This is the index in ScopeRecords for an MDNode scope
340   /// entry with no "inlined at" element.
341   DenseMap<MDNode*, int> ScopeRecordIdx;
342   
343   /// ScopeRecords - These are the actual mdnodes (in a value handle) for an
344   /// index.  The ValueHandle ensures that ScopeRecordIdx stays up to date if
345   /// the MDNode is RAUW'd.
346   std::vector<DebugRecVH> ScopeRecords;
347   
348   /// ScopeInlinedAtIdx - This is the index in ScopeInlinedAtRecords for an
349   /// scope/inlined-at pair.
350   DenseMap<std::pair<MDNode*, MDNode*>, int> ScopeInlinedAtIdx;
351   
352   /// ScopeInlinedAtRecords - These are the actual mdnodes (in value handles)
353   /// for an index.  The ValueHandle ensures that ScopeINlinedAtIdx stays up
354   /// to date.
355   std::vector<std::pair<DebugRecVH, DebugRecVH> > ScopeInlinedAtRecords;
356
357   /// DiscriminatorTable - This table maps file:line locations to an
358   /// integer representing the next DWARF path discriminator to assign to
359   /// instructions in different blocks at the same location.
360   DenseMap<std::pair<const char *, unsigned>, unsigned> DiscriminatorTable;
361
362   /// IntrinsicIDCache - Cache of intrinsic name (string) to numeric ID mappings
363   /// requested in this context
364   typedef DenseMap<const Function*, unsigned> IntrinsicIDCacheTy;
365   IntrinsicIDCacheTy IntrinsicIDCache;
366
367   /// \brief Mapping from a function to its prefix data, which is stored as the
368   /// operand of an unparented ReturnInst so that the prefix data has a Use.
369   typedef DenseMap<const Function *, ReturnInst *> PrefixDataMapTy;
370   PrefixDataMapTy PrefixDataMap;
371
372   /// \brief List of listeners to notify about a pass run.
373   SmallVector<PassRunListener *, 4> RunListeners;
374
375   /// \brief Return true if the given pass name should emit optimization
376   /// remarks.
377   bool optimizationRemarksEnabledFor(const char *PassName) const;
378
379   int getOrAddScopeRecordIdxEntry(MDNode *N, int ExistingIdx);
380   int getOrAddScopeInlinedAtIdxEntry(MDNode *Scope, MDNode *IA,int ExistingIdx);
381
382   /// \brief Notify that we finished running a pass.
383   void notifyPassRun(LLVMContext *, Pass *, Module *, Function *, BasicBlock *);
384   /// \brief Register the given PassRunListener to receive notifyPassRun()
385   /// callbacks whenever a pass ran. The context will take ownership of the
386   /// listener and free it when the context is destroyed.
387   void addRunListener(PassRunListener *);
388   /// \brief Unregister a PassRunListener so that it no longer receives
389   /// notifyPassRun() callbacks. Remove and free the listener from the context.
390   void removeRunListener(PassRunListener *);
391
392   LLVMContextImpl(LLVMContext &C);
393   ~LLVMContextImpl();
394 };
395
396 }
397
398 #endif