287127243e76e69ef08de6735cf9a9507baa2d90
[oota-llvm.git] / include / llvm / ADT / FoldingSet.h
1 //===-- llvm/ADT/FoldingSet.h - Uniquing Hash Set ---------------*- 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 defines a hash set that can be used to remove duplication of nodes
11 // in a graph.  This code was originally created by Chris Lattner for use with
12 // SelectionDAGCSEMap, but was isolated to provide use across the llvm code set. 
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_ADT_FOLDINGSET_H
17 #define LLVM_ADT_FOLDINGSET_H
18
19 #include "llvm/Support/DataTypes.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include <string>
22
23 namespace llvm {
24   class APFloat;
25   class APInt;
26
27 /// This folding set used for two purposes:
28 ///   1. Given information about a node we want to create, look up the unique
29 ///      instance of the node in the set.  If the node already exists, return
30 ///      it, otherwise return the bucket it should be inserted into.
31 ///   2. Given a node that has already been created, remove it from the set.
32 /// 
33 /// This class is implemented as a single-link chained hash table, where the
34 /// "buckets" are actually the nodes themselves (the next pointer is in the
35 /// node).  The last node points back to the bucket to simplify node removal.
36 ///
37 /// Any node that is to be included in the folding set must be a subclass of
38 /// FoldingSetNode.  The node class must also define a Profile method used to
39 /// establish the unique bits of data for the node.  The Profile method is
40 /// passed a FoldingSetNodeID object which is used to gather the bits.  Just 
41 /// call one of the Add* functions defined in the FoldingSetImpl::NodeID class.
42 /// NOTE: That the folding set does not own the nodes and it is the
43 /// responsibility of the user to dispose of the nodes.
44 ///
45 /// Eg.
46 ///    class MyNode : public FoldingSetNode {
47 ///    private:
48 ///      std::string Name;
49 ///      unsigned Value;
50 ///    public:
51 ///      MyNode(const char *N, unsigned V) : Name(N), Value(V) {}
52 ///       ...
53 ///      void Profile(FoldingSetNodeID &ID) {
54 ///        ID.AddString(Name);
55 ///        ID.AddInteger(Value);
56 ///       }
57 ///       ...
58 ///     };
59 ///
60 /// To define the folding set itself use the FoldingSet template;
61 ///
62 /// Eg.
63 ///    FoldingSet<MyNode> MyFoldingSet;
64 ///
65 /// Four public methods are available to manipulate the folding set; 
66 ///
67 /// 1) If you have an existing node that you want add to the set but unsure
68 /// that the node might already exist then call;
69 ///
70 ///    MyNode *M = MyFoldingSet.GetOrInsertNode(N);
71 ///
72 /// If The result is equal to the input then the node has been inserted.
73 /// Otherwise, the result is the node existing in the folding set, and the
74 /// input can be discarded (use the result instead.)
75 ///
76 /// 2) If you are ready to construct a node but want to check if it already
77 /// exists, then call FindNodeOrInsertPos with a FoldingSetNodeID of the bits to
78 /// check;
79 ///
80 ///   FoldingSetNodeID ID;
81 ///   ID.AddString(Name);
82 ///   ID.AddInteger(Value);
83 ///   void *InsertPoint;
84 ///
85 ///    MyNode *M = MyFoldingSet.FindNodeOrInsertPos(ID, InsertPoint);
86 ///
87 /// If found then M with be non-NULL, else InsertPoint will point to where it
88 /// should be inserted using InsertNode.
89 ///
90 /// 3) If you get a NULL result from FindNodeOrInsertPos then you can as a new
91 /// node with FindNodeOrInsertPos;
92 ///
93 ///    InsertNode(N, InsertPoint);
94 ///
95 /// 4) Finally, if you want to remove a node from the folding set call;
96 ///
97 ///    bool WasRemoved = RemoveNode(N);
98 ///
99 /// The result indicates whether the node existed in the folding set.
100   
101 class FoldingSetNodeID;
102   
103 //===----------------------------------------------------------------------===//
104 /// FoldingSetImpl - Implements the folding set functionality.  The main
105 /// structure is an array of buckets.  Each bucket is indexed by the hash of
106 /// the nodes it contains.  The bucket itself points to the nodes contained
107 /// in the bucket via a singly linked list.  The last node in the list points
108 /// back to the bucket to facilitate node removal.
109 /// 
110 class FoldingSetImpl {
111 protected:
112   /// Buckets - Array of bucket chains.
113   ///
114   void **Buckets;
115   
116   /// NumBuckets - Length of the Buckets array.  Always a power of 2.
117   ///
118   unsigned NumBuckets;
119   
120   /// NumNodes - Number of nodes in the folding set. Growth occurs when NumNodes
121   /// is greater than twice the number of buckets.
122   unsigned NumNodes;
123   
124 public:
125   explicit FoldingSetImpl(unsigned Log2InitSize = 6);
126   virtual ~FoldingSetImpl();
127   
128   //===--------------------------------------------------------------------===//
129   /// Node - This class is used to maintain the singly linked bucket list in
130   /// a folding set.
131   ///
132   class Node {
133   private:
134     // NextInFoldingSetBucket - next link in the bucket list.
135     void *NextInFoldingSetBucket;
136     
137   public:
138
139     Node() : NextInFoldingSetBucket(0) {}
140     
141     // Accessors
142     void *getNextInBucket() const { return NextInFoldingSetBucket; }
143     void SetNextInBucket(void *N) { NextInFoldingSetBucket = N; }
144   };
145
146   /// RemoveNode - Remove a node from the folding set, returning true if one
147   /// was removed or false if the node was not in the folding set.
148   bool RemoveNode(Node *N);
149   
150   /// GetOrInsertNode - If there is an existing simple Node exactly
151   /// equal to the specified node, return it.  Otherwise, insert 'N' and return
152   /// it instead.
153   Node *GetOrInsertNode(Node *N);
154   
155   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
156   /// return it.  If not, return the insertion token that will make insertion
157   /// faster.
158   Node *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
159   
160   /// InsertNode - Insert the specified node into the folding set, knowing that
161   /// it is not already in the folding set.  InsertPos must be obtained from 
162   /// FindNodeOrInsertPos.
163   void InsertNode(Node *N, void *InsertPos);
164   
165   /// size - Returns the number of nodes in the folding set.
166   unsigned size() const { return NumNodes; }
167
168   /// empty - Returns true if there are no nodes in the folding set.
169   bool empty() const { return NumNodes == 0; }
170   
171 private:
172
173   /// GrowHashTable - Double the size of the hash table and rehash everything.
174   ///
175   void GrowHashTable();
176   
177 protected:
178
179   /// GetNodeProfile - Instantiations of the FoldingSet template implement
180   /// this function to gather data bits for the given node.
181   virtual void GetNodeProfile(FoldingSetNodeID &ID, Node *N) const = 0;
182 };
183
184 //===----------------------------------------------------------------------===//
185 /// FoldingSetTrait - This trait class is used to define behavior of how
186 ///  to "profile" (in the FoldingSet parlance) an object of a given type.
187 ///  The default behavior is to invoke a 'Profile' method on an object, but
188 ///  through template specialization the behavior can be tailored for specific
189 ///  types.  Combined with the FoldingSetNodeWrapper classs, one can add objects
190 ///  to FoldingSets that were not originally designed to have that behavior.
191 ///
192 template<typename T> struct FoldingSetTrait {
193   static inline void Profile(const T& X, FoldingSetNodeID& ID) { X.Profile(ID);}
194   static inline void Profile(T& X, FoldingSetNodeID& ID) { X.Profile(ID); }
195 };
196   
197 //===--------------------------------------------------------------------===//
198 /// FoldingSetNodeID - This class is used to gather all the unique data bits of
199 /// a node.  When all the bits are gathered this class is used to produce a
200 /// hash value for the node.  
201 ///
202 class FoldingSetNodeID {
203   /// Bits - Vector of all the data bits that make the node unique.
204   /// Use a SmallVector to avoid a heap allocation in the common case.
205   SmallVector<unsigned, 32> Bits;
206   
207 public:
208   FoldingSetNodeID() {}
209   
210   /// getRawData - Return the ith entry in the Bits data.
211   ///
212   unsigned getRawData(unsigned i) const {
213     return Bits[i];
214   }
215   
216   /// Add* - Add various data types to Bit data.
217   ///
218   void AddPointer(const void *Ptr);
219   void AddInteger(signed I);
220   void AddInteger(unsigned I);
221   void AddInteger(int64_t I);
222   void AddInteger(uint64_t I);
223   void AddFloat(float F);
224   void AddDouble(double D);
225   void AddString(const std::string &String);
226   void AddString(const char* String);
227   
228   template <typename T>
229   inline void Add(const T& x) { FoldingSetTrait<T>::Profile(x, *this); }
230   
231   /// clear - Clear the accumulated profile, allowing this FoldingSetNodeID
232   ///  object to be used to compute a new profile.
233   inline void clear() { Bits.clear(); }
234   
235   /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used
236   ///  to lookup the node in the FoldingSetImpl.
237   unsigned ComputeHash() const;
238   
239   /// operator== - Used to compare two nodes to each other.
240   ///
241   bool operator==(const FoldingSetNodeID &RHS) const;
242 };  
243
244 // Convenience type to hide the implementation of the folding set.
245 typedef FoldingSetImpl::Node FoldingSetNode;
246 template<class T> class FoldingSetIterator;
247 template<class T> class FoldingSetBucketIterator;
248   
249 //===----------------------------------------------------------------------===//
250 /// FoldingSet - This template class is used to instantiate a specialized
251 /// implementation of the folding set to the node class T.  T must be a 
252 /// subclass of FoldingSetNode and implement a Profile function.
253 ///
254 template<class T> class FoldingSet : public FoldingSetImpl {
255 private:
256   /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
257   /// way to convert nodes into a unique specifier.
258   virtual void GetNodeProfile(FoldingSetNodeID &ID, Node *N) const {
259     T *TN = static_cast<T *>(N);
260     FoldingSetTrait<T>::Profile(*TN,ID);
261   }
262   
263 public:
264   explicit FoldingSet(unsigned Log2InitSize = 6)
265   : FoldingSetImpl(Log2InitSize)
266   {}
267   
268   typedef FoldingSetIterator<T> iterator;
269   iterator begin() { return iterator(Buckets); }
270   iterator end() { return iterator(Buckets+NumBuckets); }
271
272   typedef FoldingSetIterator<const T> const_iterator;
273   const_iterator begin() const { return const_iterator(Buckets); }
274   const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
275
276   typedef FoldingSetBucketIterator<T> bucket_iterator;  
277
278   bucket_iterator bucket_begin(unsigned hash) {
279     return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
280   }
281   
282   bucket_iterator bucket_end(unsigned hash) {
283     return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
284   }
285   
286   /// GetOrInsertNode - If there is an existing simple Node exactly
287   /// equal to the specified node, return it.  Otherwise, insert 'N' and
288   /// return it instead.
289   T *GetOrInsertNode(Node *N) {
290     return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
291   }
292   
293   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
294   /// return it.  If not, return the insertion token that will make insertion
295   /// faster.
296   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
297     return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
298   }
299 };
300
301 //===----------------------------------------------------------------------===//
302 /// FoldingSetIteratorImpl - This is the common iterator support shared by all
303 /// folding sets, which knows how to walk the folding set hash table.
304 class FoldingSetIteratorImpl {
305 protected:
306   FoldingSetNode *NodePtr;
307   FoldingSetIteratorImpl(void **Bucket);
308   void advance();
309   
310 public:
311   bool operator==(const FoldingSetIteratorImpl &RHS) const {
312     return NodePtr == RHS.NodePtr;
313   }
314   bool operator!=(const FoldingSetIteratorImpl &RHS) const {
315     return NodePtr != RHS.NodePtr;
316   }
317 };
318
319
320 template<class T>
321 class FoldingSetIterator : public FoldingSetIteratorImpl {
322 public:
323   explicit FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
324   
325   T &operator*() const {
326     return *static_cast<T*>(NodePtr);
327   }
328   
329   T *operator->() const {
330     return static_cast<T*>(NodePtr);
331   }
332   
333   inline FoldingSetIterator& operator++() {          // Preincrement
334     advance();
335     return *this;
336   }
337   FoldingSetIterator operator++(int) {        // Postincrement
338     FoldingSetIterator tmp = *this; ++*this; return tmp;
339   }
340 };
341   
342 //===----------------------------------------------------------------------===//
343 /// FoldingSetBucketIteratorImpl - This is the common bucket iterator support
344 ///  shared by all folding sets, which knows how to walk a particular bucket
345 ///  of a folding set hash table.
346   
347 class FoldingSetBucketIteratorImpl {
348 protected:
349   void *Ptr;
350
351   explicit FoldingSetBucketIteratorImpl(void **Bucket);
352   
353   FoldingSetBucketIteratorImpl(void **Bucket, bool)
354     : Ptr(Bucket) {}
355
356   void advance() {
357     void *Probe = static_cast<FoldingSetNode*>(Ptr)->getNextInBucket();
358     uintptr_t x = reinterpret_cast<uintptr_t>(Probe) & ~0x1;
359     Ptr = reinterpret_cast<void*>(x);
360   }
361   
362 public:
363   bool operator==(const FoldingSetBucketIteratorImpl &RHS) const {
364     return Ptr == RHS.Ptr;
365   }
366   bool operator!=(const FoldingSetBucketIteratorImpl &RHS) const {
367     return Ptr != RHS.Ptr;
368   }
369 };
370   
371   
372 template<class T>
373 class FoldingSetBucketIterator : public FoldingSetBucketIteratorImpl {
374 public:
375   explicit FoldingSetBucketIterator(void **Bucket) : 
376     FoldingSetBucketIteratorImpl(Bucket) {}
377   
378   FoldingSetBucketIterator(void **Bucket, bool) : 
379     FoldingSetBucketIteratorImpl(Bucket, true) {}
380   
381   T& operator*() const { return *static_cast<T*>(Ptr); }  
382   T* operator->() const { return static_cast<T*>(Ptr); }
383   
384   inline FoldingSetBucketIterator& operator++() { // Preincrement
385     advance();
386     return *this;
387   }          
388   FoldingSetBucketIterator operator++(int) {      // Postincrement
389     FoldingSetBucketIterator tmp = *this; ++*this; return tmp;
390   }
391 };
392   
393 //===----------------------------------------------------------------------===//
394 /// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
395 /// types in an enclosing object so that they can be inserted into FoldingSets.
396 template <typename T>
397 class FoldingSetNodeWrapper : public FoldingSetNode {
398   T data;
399 public:
400   explicit FoldingSetNodeWrapper(const T& x) : data(x) {}
401   virtual ~FoldingSetNodeWrapper() {}
402   
403   template<typename A1>
404   explicit FoldingSetNodeWrapper(const A1& a1)
405     : data(a1) {}
406   
407   template <typename A1, typename A2>
408   explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2)
409     : data(a1,a2) {}
410   
411   template <typename A1, typename A2, typename A3>
412   explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2, const A3& a3)
413     : data(a1,a2,a3) {}
414   
415   template <typename A1, typename A2, typename A3, typename A4>
416   explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2, const A3& a3,
417                                  const A4& a4)
418     : data(a1,a2,a3,a4) {}
419   
420   template <typename A1, typename A2, typename A3, typename A4, typename A5>
421   explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2, const A3& a3,
422                                  const A4& a4, const A5& a5)
423   : data(a1,a2,a3,a4,a5) {}
424
425   
426   void Profile(FoldingSetNodeID& ID) { FoldingSetTrait<T>::Profile(data, ID); }
427
428   T& getValue() { return data; }
429   const T& getValue() const { return data; }
430
431   operator T&() { return data; }
432   operator const T&() const { return data; }
433 };  
434   
435 //===----------------------------------------------------------------------===//
436 // Partial specializations of FoldingSetTrait.
437
438 template<typename T> struct FoldingSetTrait<T*> {
439   static inline void Profile(const T* X, FoldingSetNodeID& ID) {
440     ID.AddPointer(X);
441   }
442   static inline void Profile(T* X, FoldingSetNodeID& ID) {
443     ID.AddPointer(X);
444   }
445 };
446
447 } // End of namespace llvm.
448
449
450 #endif
451