IR: Split MDNode into GenericMDNode and MDNodeFwdDecl
[oota-llvm.git] / include / llvm / IR / Metadata.h
1 //===-- llvm/Metadata.h - Metadata definitions ------------------*- 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 /// @file
11 /// This file contains the declarations for metadata subclasses.
12 /// They represent the different flavors of metadata that live in LLVM.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_IR_METADATA_H
17 #define LLVM_IR_METADATA_H
18
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/ilist_node.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/IR/Value.h"
25
26 namespace llvm {
27 class LLVMContext;
28 class Module;
29 template<typename ValueSubClass, typename ItemParentClass>
30   class SymbolTableListTraits;
31
32
33 enum LLVMConstants : uint32_t {
34   DEBUG_METADATA_VERSION = 2  // Current debug info version number.
35 };
36
37 /// \brief Root of the metadata hierarchy.
38 ///
39 /// This is a root class for typeless data in the IR.
40 ///
41 /// TODO: Detach from the Value hierarchy.
42 class Metadata : public Value {
43 protected:
44   Metadata(LLVMContext &Context, unsigned ID);
45
46 public:
47   static bool classof(const Value *V) {
48     return V->getValueID() == GenericMDNodeVal ||
49            V->getValueID() == MDNodeFwdDeclVal ||
50            V->getValueID() == MDStringVal;
51   }
52 };
53
54 //===----------------------------------------------------------------------===//
55 /// \brief A single uniqued string.
56 ///
57 /// These are used to efficiently contain a byte sequence for metadata.
58 /// MDString is always unnamed.
59 class MDString : public Metadata {
60   friend class StringMapEntry<MDString>;
61
62   virtual void anchor();
63   MDString(const MDString &) LLVM_DELETED_FUNCTION;
64
65   explicit MDString(LLVMContext &Context)
66       : Metadata(Context, Value::MDStringVal) {}
67
68   /// \brief Shadow Value::getName() to prevent its use.
69   StringRef getName() const LLVM_DELETED_FUNCTION;
70
71 public:
72   static MDString *get(LLVMContext &Context, StringRef Str);
73   static MDString *get(LLVMContext &Context, const char *Str) {
74     return get(Context, Str ? StringRef(Str) : StringRef());
75   }
76
77   StringRef getString() const;
78
79   unsigned getLength() const { return (unsigned)getString().size(); }
80
81   typedef StringRef::iterator iterator;
82
83   /// \brief Pointer to the first byte of the string.
84   iterator begin() const { return getString().begin(); }
85
86   /// \brief Pointer to one byte past the end of the string.
87   iterator end() const { return getString().end(); }
88
89   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
90   static bool classof(const Value *V) {
91     return V->getValueID() == MDStringVal;
92   }
93 };
94
95 /// \brief A collection of metadata nodes that might be associated with a
96 /// memory access used by the alias-analysis infrastructure.
97 struct AAMDNodes {
98   explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
99                      MDNode *N = nullptr)
100       : TBAA(T), Scope(S), NoAlias(N) {}
101
102   bool operator==(const AAMDNodes &A) const {
103     return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
104   }
105
106   bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
107
108   LLVM_EXPLICIT operator bool() const { return TBAA || Scope || NoAlias; }
109
110   /// \brief The tag for type-based alias analysis.
111   MDNode *TBAA;
112
113   /// \brief The tag for alias scope specification (used with noalias).
114   MDNode *Scope;
115
116   /// \brief The tag specifying the noalias scope.
117   MDNode *NoAlias;
118 };
119
120 // Specialize DenseMapInfo for AAMDNodes.
121 template<>
122 struct DenseMapInfo<AAMDNodes> {
123   static inline AAMDNodes getEmptyKey() {
124     return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
125   }
126   static inline AAMDNodes getTombstoneKey() {
127     return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
128   }
129   static unsigned getHashValue(const AAMDNodes &Val) {
130     return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
131            DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
132            DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
133   }
134   static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
135     return LHS == RHS;
136   }
137 };
138
139 class MDNodeOperand;
140
141 //===----------------------------------------------------------------------===//
142 /// \brief Tuple of metadata.
143 class MDNode : public Metadata {
144   MDNode(const MDNode &) LLVM_DELETED_FUNCTION;
145   void operator=(const MDNode &) LLVM_DELETED_FUNCTION;
146   friend class MDNodeOperand;
147   friend class LLVMContextImpl;
148
149 protected:
150   // TODO: Sink this into GenericMDNode.  Can't do this until operands are
151   // allocated at the front (currently they're at the back).
152   unsigned Hash;
153
154   /// \brief Subclass data enums.
155   enum {
156     /// FunctionLocalBit - This bit is set if this MDNode is function local.
157     /// This is true when it (potentially transitively) contains a reference to
158     /// something in a function, like an argument, basicblock, or instruction.
159     FunctionLocalBit = 1 << 0,
160
161     /// NotUniquedBit - This is set on MDNodes that are not uniqued because they
162     /// have a null operand.
163     NotUniquedBit    = 1 << 1,
164
165     /// DestroyFlag - This bit is set by destroy() so the destructor can assert
166     /// that the node isn't being destroyed with a plain 'delete'.
167     DestroyFlag      = 1 << 2
168   };
169
170   /// \brief FunctionLocal enums.
171   enum FunctionLocalness {
172     FL_Unknown = -1,
173     FL_No = 0,
174     FL_Yes = 1
175   };
176
177   /// \brief Replace each instance of the given operand with a new value.
178   void replaceOperand(MDNodeOperand *Op, Value *NewVal);
179   ~MDNode();
180
181   MDNode(LLVMContext &C, unsigned ID, ArrayRef<Value *> Vals,
182          bool isFunctionLocal);
183
184   static MDNode *getMDNode(LLVMContext &C, ArrayRef<Value*> Vals,
185                            FunctionLocalness FL, bool Insert = true);
186 public:
187   static MDNode *get(LLVMContext &Context, ArrayRef<Value*> Vals);
188   /// \brief Construct MDNode with an explicit function-localness.
189   ///
190   /// Don't analyze Vals; trust isFunctionLocal.
191   static MDNode *getWhenValsUnresolved(LLVMContext &Context,
192                                        ArrayRef<Value*> Vals,
193                                        bool isFunctionLocal);
194
195   static MDNode *getIfExists(LLVMContext &Context, ArrayRef<Value*> Vals);
196
197   /// \brief Return a temporary MDNode
198   ///
199   /// For use in constructing cyclic MDNode structures. A temporary MDNode is
200   /// not uniqued, may be RAUW'd, and must be manually deleted with
201   /// deleteTemporary.
202   static MDNode *getTemporary(LLVMContext &Context, ArrayRef<Value*> Vals);
203
204   /// \brief Deallocate a node created by getTemporary.
205   ///
206   /// The node must not have any users.
207   static void deleteTemporary(MDNode *N);
208
209   /// \brief Replace a specific operand.
210   void replaceOperandWith(unsigned i, Value *NewVal);
211
212   /// \brief Return specified operand.
213   Value *getOperand(unsigned i) const LLVM_READONLY;
214
215   /// \brief Return number of MDNode operands.
216   unsigned getNumOperands() const { return NumOperands; }
217
218   /// \brief Return whether MDNode is local to a function.
219   bool isFunctionLocal() const {
220     return (getSubclassDataFromValue() & FunctionLocalBit) != 0;
221   }
222
223   /// \brief Return the first function-local operand's function.
224   ///
225   /// If this metadata is function-local and recursively has a function-local
226   /// operand, return the first such operand's parent function.  Otherwise,
227   /// return null. getFunction() should not be used for performance- critical
228   /// code because it recursively visits all the MDNode's operands.
229   const Function *getFunction() const;
230
231   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
232   static bool classof(const Value *V) {
233     return V->getValueID() == GenericMDNodeVal ||
234            V->getValueID() == MDNodeFwdDeclVal;
235   }
236
237   /// \brief Check whether MDNode is a vtable access.
238   bool isTBAAVtableAccess() const;
239
240   /// \brief Methods for metadata merging.
241   static MDNode *concatenate(MDNode *A, MDNode *B);
242   static MDNode *intersect(MDNode *A, MDNode *B);
243   static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
244   static AAMDNodes getMostGenericAA(const AAMDNodes &A, const AAMDNodes &B);
245   static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
246   static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
247
248 protected:
249   bool isNotUniqued() const {
250     return (getSubclassDataFromValue() & NotUniquedBit) != 0;
251   }
252   void setIsNotUniqued();
253
254   // Shadow Value::setValueSubclassData with a private forwarding method so that
255   // any future subclasses cannot accidentally use it.
256   void setValueSubclassData(unsigned short D) {
257     Value::setValueSubclassData(D);
258   }
259 };
260
261 /// \brief Generic metadata node.
262 ///
263 /// Generic metadata nodes, with opt-out support for uniquing.
264 ///
265 /// Although nodes are uniqued by default, \a GenericMDNode has no support for
266 /// RAUW.  If an operand change (due to RAUW or otherwise) causes a uniquing
267 /// collision, the uniquing bit is dropped.
268 ///
269 /// TODO: Make uniquing opt-out (status: mandatory, sometimes dropped).
270 /// TODO: Drop support for RAUW.
271 class GenericMDNode : public MDNode {
272   friend class MDNode;
273
274   GenericMDNode(LLVMContext &C, ArrayRef<Value *> Vals, bool isFunctionLocal)
275       : MDNode(C, GenericMDNodeVal, Vals, isFunctionLocal) {}
276   ~GenericMDNode();
277
278 public:
279   /// \brief Get the hash, if any.
280   unsigned getHash() const { return Hash; }
281
282   static bool classof(const Value *V) {
283     return V->getValueID() == GenericMDNodeVal;
284   }
285
286 private:
287   /// \brief Delete this node.  Only when there are no uses.
288   void destroy();
289   friend class MDNode;
290   friend class LLVMContextImpl;
291 };
292
293 /// \brief Forward declaration of metadata.
294 ///
295 /// Forward declaration of metadata, in the form of a metadata node.  Unlike \a
296 /// GenericMDNode, this class has support for RAUW and is suitable for forward
297 /// references.
298 class MDNodeFwdDecl : public MDNode {
299   friend class MDNode;
300
301   MDNodeFwdDecl(LLVMContext &C, ArrayRef<Value *> Vals, bool isFunctionLocal)
302       : MDNode(C, MDNodeFwdDeclVal, Vals, isFunctionLocal) {}
303   ~MDNodeFwdDecl() {}
304
305 public:
306   static bool classof(const Value *V) {
307     return V->getValueID() == MDNodeFwdDeclVal;
308   }
309
310 private:
311   /// \brief Delete this node.  Only when there are no uses.
312   void destroy();
313   friend class MDNode;
314 };
315
316 //===----------------------------------------------------------------------===//
317 /// \brief A tuple of MDNodes.
318 ///
319 /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
320 /// to modules, have names, and contain lists of MDNodes.
321 ///
322 /// TODO: Inherit from Metadata.
323 class NamedMDNode : public ilist_node<NamedMDNode> {
324   friend class SymbolTableListTraits<NamedMDNode, Module>;
325   friend struct ilist_traits<NamedMDNode>;
326   friend class LLVMContextImpl;
327   friend class Module;
328   NamedMDNode(const NamedMDNode &) LLVM_DELETED_FUNCTION;
329
330   std::string Name;
331   Module *Parent;
332   void *Operands; // SmallVector<TrackingVH<MDNode>, 4>
333
334   void setParent(Module *M) { Parent = M; }
335
336   explicit NamedMDNode(const Twine &N);
337
338   template<class T1, class T2>
339   class op_iterator_impl :
340       public std::iterator<std::bidirectional_iterator_tag, T2> {
341     const NamedMDNode *Node;
342     unsigned Idx;
343     op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
344
345     friend class NamedMDNode;
346
347   public:
348     op_iterator_impl() : Node(nullptr), Idx(0) { }
349
350     bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
351     bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
352     op_iterator_impl &operator++() {
353       ++Idx;
354       return *this;
355     }
356     op_iterator_impl operator++(int) {
357       op_iterator_impl tmp(*this);
358       operator++();
359       return tmp;
360     }
361     op_iterator_impl &operator--() {
362       --Idx;
363       return *this;
364     }
365     op_iterator_impl operator--(int) {
366       op_iterator_impl tmp(*this);
367       operator--();
368       return tmp;
369     }
370
371     T1 operator*() const { return Node->getOperand(Idx); }
372   };
373
374 public:
375   /// \brief Drop all references and remove the node from parent module.
376   void eraseFromParent();
377
378   /// \brief Remove all uses and clear node vector.
379   void dropAllReferences();
380
381   ~NamedMDNode();
382
383   /// \brief Get the module that holds this named metadata collection.
384   inline Module *getParent() { return Parent; }
385   inline const Module *getParent() const { return Parent; }
386
387   MDNode *getOperand(unsigned i) const;
388   unsigned getNumOperands() const;
389   void addOperand(MDNode *M);
390   StringRef getName() const;
391   void print(raw_ostream &ROS) const;
392   void dump() const;
393
394   // ---------------------------------------------------------------------------
395   // Operand Iterator interface...
396   //
397   typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
398   op_iterator op_begin() { return op_iterator(this, 0); }
399   op_iterator op_end()   { return op_iterator(this, getNumOperands()); }
400
401   typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
402   const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
403   const_op_iterator op_end()   const { return const_op_iterator(this, getNumOperands()); }
404
405   inline iterator_range<op_iterator>  operands() {
406     return iterator_range<op_iterator>(op_begin(), op_end());
407   }
408   inline iterator_range<const_op_iterator> operands() const {
409     return iterator_range<const_op_iterator>(op_begin(), op_end());
410   }
411 };
412
413 } // end llvm namespace
414
415 #endif