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/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/iterator.h"
22 #include "llvm/Support/Allocator.h"
23 #include "llvm/Support/DataTypes.h"
24 
25 namespace llvm {
26 /// This folding set used for two purposes:
27 ///   1. Given information about a node we want to create, look up the unique
28 ///      instance of the node in the set.  If the node already exists, return
29 ///      it, otherwise return the bucket it should be inserted into.
30 ///   2. Given a node that has already been created, remove it from the set.
31 ///
32 /// This class is implemented as a single-link chained hash table, where the
33 /// "buckets" are actually the nodes themselves (the next pointer is in the
34 /// node).  The last node points back to the bucket to simplify node removal.
35 ///
36 /// Any node that is to be included in the folding set must be a subclass of
37 /// FoldingSetNode.  The node class must also define a Profile method used to
38 /// establish the unique bits of data for the node.  The Profile method is
39 /// passed a FoldingSetNodeID object which is used to gather the bits.  Just
40 /// call one of the Add* functions defined in the FoldingSetImpl::NodeID class.
41 /// NOTE: That the folding set does not own the nodes and it is the
42 /// responsibility of the user to dispose of the nodes.
43 ///
44 /// Eg.
45 ///    class MyNode : public FoldingSetNode {
46 ///    private:
47 ///      std::string Name;
48 ///      unsigned Value;
49 ///    public:
50 ///      MyNode(const char *N, unsigned V) : Name(N), Value(V) {}
51 ///       ...
52 ///      void Profile(FoldingSetNodeID &ID) const {
53 ///        ID.AddString(Name);
54 ///        ID.AddInteger(Value);
55 ///      }
56 ///      ...
57 ///    };
58 ///
59 /// To define the folding set itself use the FoldingSet template;
60 ///
61 /// Eg.
62 ///    FoldingSet<MyNode> MyFoldingSet;
63 ///
64 /// Four public methods are available to manipulate the folding set;
65 ///
66 /// 1) If you have an existing node that you want add to the set but unsure
67 /// that the node might already exist then call;
68 ///
69 ///    MyNode *M = MyFoldingSet.GetOrInsertNode(N);
70 ///
71 /// If The result is equal to the input then the node has been inserted.
72 /// Otherwise, the result is the node existing in the folding set, and the
73 /// input can be discarded (use the result instead.)
74 ///
75 /// 2) If you are ready to construct a node but want to check if it already
76 /// exists, then call FindNodeOrInsertPos with a FoldingSetNodeID of the bits to
77 /// check;
78 ///
79 ///   FoldingSetNodeID ID;
80 ///   ID.AddString(Name);
81 ///   ID.AddInteger(Value);
82 ///   void *InsertPoint;
83 ///
84 ///    MyNode *M = MyFoldingSet.FindNodeOrInsertPos(ID, InsertPoint);
85 ///
86 /// If found then M with be non-NULL, else InsertPoint will point to where it
87 /// should be inserted using InsertNode.
88 ///
89 /// 3) If you get a NULL result from FindNodeOrInsertPos then you can as a new
90 /// node with FindNodeOrInsertPos;
91 ///
92 ///    InsertNode(N, InsertPoint);
93 ///
94 /// 4) Finally, if you want to remove a node from the folding set call;
95 ///
96 ///    bool WasRemoved = RemoveNode(N);
97 ///
98 /// The result indicates whether the node existed in the folding set.
99 
100 class FoldingSetNodeID;
101 
102 //===----------------------------------------------------------------------===//
103 /// FoldingSetImpl - Implements the folding set functionality.  The main
104 /// structure is an array of buckets.  Each bucket is indexed by the hash of
105 /// the nodes it contains.  The bucket itself points to the nodes contained
106 /// in the bucket via a singly linked list.  The last node in the list points
107 /// back to the bucket to facilitate node removal.
108 ///
109 class FoldingSetImpl {
110 
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   explicit FoldingSetImpl(unsigned Log2InitSize = 6);
125   FoldingSetImpl(FoldingSetImpl &&Arg);
126   FoldingSetImpl &operator=(FoldingSetImpl &&RHS);
127   ~FoldingSetImpl();
128 
129 public:
130   //===--------------------------------------------------------------------===//
131   /// Node - This class is used to maintain the singly linked bucket list in
132   /// a folding set.
133   ///
134   class Node {
135   private:
136     // NextInFoldingSetBucket - next link in the bucket list.
137     void *NextInFoldingSetBucket;
138 
139   public:
Node()140     Node() : NextInFoldingSetBucket(nullptr) {}
141 
142     // Accessors
getNextInBucket()143     void *getNextInBucket() const { return NextInFoldingSetBucket; }
SetNextInBucket(void * N)144     void SetNextInBucket(void *N) { NextInFoldingSetBucket = N; }
145   };
146 
147   /// clear - Remove all nodes from the folding set.
148   void clear();
149 
150   /// RemoveNode - Remove a node from the folding set, returning true if one
151   /// was removed or false if the node was not in the folding set.
152   bool RemoveNode(Node *N);
153 
154   /// GetOrInsertNode - If there is an existing simple Node exactly
155   /// equal to the specified node, return it.  Otherwise, insert 'N' and return
156   /// it instead.
157   Node *GetOrInsertNode(Node *N);
158 
159   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
160   /// return it.  If not, return the insertion token that will make insertion
161   /// faster.
162   Node *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
163 
164   /// InsertNode - Insert the specified node into the folding set, knowing that
165   /// it is not already in the folding set.  InsertPos must be obtained from
166   /// FindNodeOrInsertPos.
167   void InsertNode(Node *N, void *InsertPos);
168 
169   /// InsertNode - Insert the specified node into the folding set, knowing that
170   /// it is not already in the folding set.
InsertNode(Node * N)171   void InsertNode(Node *N) {
172     Node *Inserted = GetOrInsertNode(N);
173     (void)Inserted;
174     assert(Inserted == N && "Node already inserted!");
175   }
176 
177   /// size - Returns the number of nodes in the folding set.
size()178   unsigned size() const { return NumNodes; }
179 
180   /// empty - Returns true if there are no nodes in the folding set.
empty()181   bool empty() const { return NumNodes == 0; }
182 
183 private:
184   /// GrowHashTable - Double the size of the hash table and rehash everything.
185   ///
186   void GrowHashTable();
187 
188 protected:
189   /// GetNodeProfile - Instantiations of the FoldingSet template implement
190   /// this function to gather data bits for the given node.
191   virtual void GetNodeProfile(Node *N, FoldingSetNodeID &ID) const = 0;
192   /// NodeEquals - Instantiations of the FoldingSet template implement
193   /// this function to compare the given node with the given ID.
194   virtual bool NodeEquals(Node *N, const FoldingSetNodeID &ID, unsigned IDHash,
195                           FoldingSetNodeID &TempID) const=0;
196   /// ComputeNodeHash - Instantiations of the FoldingSet template implement
197   /// this function to compute a hash value for the given node.
198   virtual unsigned ComputeNodeHash(Node *N, FoldingSetNodeID &TempID) const = 0;
199 };
200 
201 //===----------------------------------------------------------------------===//
202 
203 template<typename T> struct FoldingSetTrait;
204 
205 /// DefaultFoldingSetTrait - This class provides default implementations
206 /// for FoldingSetTrait implementations.
207 ///
208 template<typename T> struct DefaultFoldingSetTrait {
ProfileDefaultFoldingSetTrait209   static void Profile(const T &X, FoldingSetNodeID &ID) {
210     X.Profile(ID);
211   }
ProfileDefaultFoldingSetTrait212   static void Profile(T &X, FoldingSetNodeID &ID) {
213     X.Profile(ID);
214   }
215 
216   // Equals - Test if the profile for X would match ID, using TempID
217   // to compute a temporary ID if necessary. The default implementation
218   // just calls Profile and does a regular comparison. Implementations
219   // can override this to provide more efficient implementations.
220   static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
221                             FoldingSetNodeID &TempID);
222 
223   // ComputeHash - Compute a hash value for X, using TempID to
224   // compute a temporary ID if necessary. The default implementation
225   // just calls Profile and does a regular hash computation.
226   // Implementations can override this to provide more efficient
227   // implementations.
228   static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID);
229 };
230 
231 /// FoldingSetTrait - This trait class is used to define behavior of how
232 /// to "profile" (in the FoldingSet parlance) an object of a given type.
233 /// The default behavior is to invoke a 'Profile' method on an object, but
234 /// through template specialization the behavior can be tailored for specific
235 /// types.  Combined with the FoldingSetNodeWrapper class, one can add objects
236 /// to FoldingSets that were not originally designed to have that behavior.
237 template<typename T> struct FoldingSetTrait
238   : public DefaultFoldingSetTrait<T> {};
239 
240 template<typename T, typename Ctx> struct ContextualFoldingSetTrait;
241 
242 /// DefaultContextualFoldingSetTrait - Like DefaultFoldingSetTrait, but
243 /// for ContextualFoldingSets.
244 template<typename T, typename Ctx>
245 struct DefaultContextualFoldingSetTrait {
ProfileDefaultContextualFoldingSetTrait246   static void Profile(T &X, FoldingSetNodeID &ID, Ctx Context) {
247     X.Profile(ID, Context);
248   }
249   static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
250                             FoldingSetNodeID &TempID, Ctx Context);
251   static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID,
252                                      Ctx Context);
253 };
254 
255 /// ContextualFoldingSetTrait - Like FoldingSetTrait, but for
256 /// ContextualFoldingSets.
257 template<typename T, typename Ctx> struct ContextualFoldingSetTrait
258   : public DefaultContextualFoldingSetTrait<T, Ctx> {};
259 
260 //===--------------------------------------------------------------------===//
261 /// FoldingSetNodeIDRef - This class describes a reference to an interned
262 /// FoldingSetNodeID, which can be a useful to store node id data rather
263 /// than using plain FoldingSetNodeIDs, since the 32-element SmallVector
264 /// is often much larger than necessary, and the possibility of heap
265 /// allocation means it requires a non-trivial destructor call.
266 class FoldingSetNodeIDRef {
267   const unsigned *Data;
268   size_t Size;
269 
270 public:
FoldingSetNodeIDRef()271   FoldingSetNodeIDRef() : Data(nullptr), Size(0) {}
FoldingSetNodeIDRef(const unsigned * D,size_t S)272   FoldingSetNodeIDRef(const unsigned *D, size_t S) : Data(D), Size(S) {}
273 
274   /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
275   /// used to lookup the node in the FoldingSetImpl.
276   unsigned ComputeHash() const;
277 
278   bool operator==(FoldingSetNodeIDRef) const;
279 
280   bool operator!=(FoldingSetNodeIDRef RHS) const { return !(*this == RHS); }
281 
282   /// Used to compare the "ordering" of two nodes as defined by the
283   /// profiled bits and their ordering defined by memcmp().
284   bool operator<(FoldingSetNodeIDRef) const;
285 
getData()286   const unsigned *getData() const { return Data; }
getSize()287   size_t getSize() const { return Size; }
288 };
289 
290 //===--------------------------------------------------------------------===//
291 /// FoldingSetNodeID - This class is used to gather all the unique data bits of
292 /// a node.  When all the bits are gathered this class is used to produce a
293 /// hash value for the node.
294 ///
295 class FoldingSetNodeID {
296   /// Bits - Vector of all the data bits that make the node unique.
297   /// Use a SmallVector to avoid a heap allocation in the common case.
298   SmallVector<unsigned, 32> Bits;
299 
300 public:
FoldingSetNodeID()301   FoldingSetNodeID() {}
302 
FoldingSetNodeID(FoldingSetNodeIDRef Ref)303   FoldingSetNodeID(FoldingSetNodeIDRef Ref)
304     : Bits(Ref.getData(), Ref.getData() + Ref.getSize()) {}
305 
306   /// Add* - Add various data types to Bit data.
307   ///
308   void AddPointer(const void *Ptr);
309   void AddInteger(signed I);
310   void AddInteger(unsigned I);
311   void AddInteger(long I);
312   void AddInteger(unsigned long I);
313   void AddInteger(long long I);
314   void AddInteger(unsigned long long I);
AddBoolean(bool B)315   void AddBoolean(bool B) { AddInteger(B ? 1U : 0U); }
316   void AddString(StringRef String);
317   void AddNodeID(const FoldingSetNodeID &ID);
318 
319   template <typename T>
Add(const T & x)320   inline void Add(const T &x) { FoldingSetTrait<T>::Profile(x, *this); }
321 
322   /// clear - Clear the accumulated profile, allowing this FoldingSetNodeID
323   /// object to be used to compute a new profile.
clear()324   inline void clear() { Bits.clear(); }
325 
326   /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used
327   /// to lookup the node in the FoldingSetImpl.
328   unsigned ComputeHash() const;
329 
330   /// operator== - Used to compare two nodes to each other.
331   ///
332   bool operator==(const FoldingSetNodeID &RHS) const;
333   bool operator==(const FoldingSetNodeIDRef RHS) const;
334 
335   bool operator!=(const FoldingSetNodeID &RHS) const { return !(*this == RHS); }
336   bool operator!=(const FoldingSetNodeIDRef RHS) const { return !(*this ==RHS);}
337 
338   /// Used to compare the "ordering" of two nodes as defined by the
339   /// profiled bits and their ordering defined by memcmp().
340   bool operator<(const FoldingSetNodeID &RHS) const;
341   bool operator<(const FoldingSetNodeIDRef RHS) const;
342 
343   /// Intern - Copy this node's data to a memory region allocated from the
344   /// given allocator and return a FoldingSetNodeIDRef describing the
345   /// interned data.
346   FoldingSetNodeIDRef Intern(BumpPtrAllocator &Allocator) const;
347 };
348 
349 // Convenience type to hide the implementation of the folding set.
350 typedef FoldingSetImpl::Node FoldingSetNode;
351 template<class T> class FoldingSetIterator;
352 template<class T> class FoldingSetBucketIterator;
353 
354 // Definitions of FoldingSetTrait and ContextualFoldingSetTrait functions, which
355 // require the definition of FoldingSetNodeID.
356 template<typename T>
357 inline bool
Equals(T & X,const FoldingSetNodeID & ID,unsigned,FoldingSetNodeID & TempID)358 DefaultFoldingSetTrait<T>::Equals(T &X, const FoldingSetNodeID &ID,
359                                   unsigned /*IDHash*/,
360                                   FoldingSetNodeID &TempID) {
361   FoldingSetTrait<T>::Profile(X, TempID);
362   return TempID == ID;
363 }
364 template<typename T>
365 inline unsigned
ComputeHash(T & X,FoldingSetNodeID & TempID)366 DefaultFoldingSetTrait<T>::ComputeHash(T &X, FoldingSetNodeID &TempID) {
367   FoldingSetTrait<T>::Profile(X, TempID);
368   return TempID.ComputeHash();
369 }
370 template<typename T, typename Ctx>
371 inline bool
Equals(T & X,const FoldingSetNodeID & ID,unsigned,FoldingSetNodeID & TempID,Ctx Context)372 DefaultContextualFoldingSetTrait<T, Ctx>::Equals(T &X,
373                                                  const FoldingSetNodeID &ID,
374                                                  unsigned /*IDHash*/,
375                                                  FoldingSetNodeID &TempID,
376                                                  Ctx Context) {
377   ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
378   return TempID == ID;
379 }
380 template<typename T, typename Ctx>
381 inline unsigned
ComputeHash(T & X,FoldingSetNodeID & TempID,Ctx Context)382 DefaultContextualFoldingSetTrait<T, Ctx>::ComputeHash(T &X,
383                                                       FoldingSetNodeID &TempID,
384                                                       Ctx Context) {
385   ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
386   return TempID.ComputeHash();
387 }
388 
389 //===----------------------------------------------------------------------===//
390 /// FoldingSet - This template class is used to instantiate a specialized
391 /// implementation of the folding set to the node class T.  T must be a
392 /// subclass of FoldingSetNode and implement a Profile function.
393 ///
394 /// Note that this set type is movable and move-assignable. However, its
395 /// moved-from state is not a valid state for anything other than
396 /// move-assigning and destroying. This is primarily to enable movable APIs
397 /// that incorporate these objects.
398 template <class T> class FoldingSet final : public FoldingSetImpl {
399 private:
400   /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
401   /// way to convert nodes into a unique specifier.
GetNodeProfile(Node * N,FoldingSetNodeID & ID)402   void GetNodeProfile(Node *N, FoldingSetNodeID &ID) const override {
403     T *TN = static_cast<T *>(N);
404     FoldingSetTrait<T>::Profile(*TN, ID);
405   }
406   /// NodeEquals - Instantiations may optionally provide a way to compare a
407   /// node with a specified ID.
NodeEquals(Node * N,const FoldingSetNodeID & ID,unsigned IDHash,FoldingSetNodeID & TempID)408   bool NodeEquals(Node *N, const FoldingSetNodeID &ID, unsigned IDHash,
409                   FoldingSetNodeID &TempID) const override {
410     T *TN = static_cast<T *>(N);
411     return FoldingSetTrait<T>::Equals(*TN, ID, IDHash, TempID);
412   }
413   /// ComputeNodeHash - Instantiations may optionally provide a way to compute a
414   /// hash value directly from a node.
ComputeNodeHash(Node * N,FoldingSetNodeID & TempID)415   unsigned ComputeNodeHash(Node *N, FoldingSetNodeID &TempID) const override {
416     T *TN = static_cast<T *>(N);
417     return FoldingSetTrait<T>::ComputeHash(*TN, TempID);
418   }
419 
420 public:
421   explicit FoldingSet(unsigned Log2InitSize = 6)
FoldingSetImpl(Log2InitSize)422       : FoldingSetImpl(Log2InitSize) {}
423 
FoldingSet(FoldingSet && Arg)424   FoldingSet(FoldingSet &&Arg) : FoldingSetImpl(std::move(Arg)) {}
425   FoldingSet &operator=(FoldingSet &&RHS) {
426     (void)FoldingSetImpl::operator=(std::move(RHS));
427     return *this;
428   }
429 
430   typedef FoldingSetIterator<T> iterator;
begin()431   iterator begin() { return iterator(Buckets); }
end()432   iterator end() { return iterator(Buckets+NumBuckets); }
433 
434   typedef FoldingSetIterator<const T> const_iterator;
begin()435   const_iterator begin() const { return const_iterator(Buckets); }
end()436   const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
437 
438   typedef FoldingSetBucketIterator<T> bucket_iterator;
439 
bucket_begin(unsigned hash)440   bucket_iterator bucket_begin(unsigned hash) {
441     return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
442   }
443 
bucket_end(unsigned hash)444   bucket_iterator bucket_end(unsigned hash) {
445     return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
446   }
447 
448   /// GetOrInsertNode - If there is an existing simple Node exactly
449   /// equal to the specified node, return it.  Otherwise, insert 'N' and
450   /// return it instead.
GetOrInsertNode(Node * N)451   T *GetOrInsertNode(Node *N) {
452     return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
453   }
454 
455   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
456   /// return it.  If not, return the insertion token that will make insertion
457   /// faster.
FindNodeOrInsertPos(const FoldingSetNodeID & ID,void * & InsertPos)458   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
459     return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
460   }
461 };
462 
463 //===----------------------------------------------------------------------===//
464 /// ContextualFoldingSet - This template class is a further refinement
465 /// of FoldingSet which provides a context argument when calling
466 /// Profile on its nodes.  Currently, that argument is fixed at
467 /// initialization time.
468 ///
469 /// T must be a subclass of FoldingSetNode and implement a Profile
470 /// function with signature
471 ///   void Profile(llvm::FoldingSetNodeID &, Ctx);
472 template <class T, class Ctx>
473 class ContextualFoldingSet final : public FoldingSetImpl {
474   // Unfortunately, this can't derive from FoldingSet<T> because the
475   // construction vtable for FoldingSet<T> requires
476   // FoldingSet<T>::GetNodeProfile to be instantiated, which in turn
477   // requires a single-argument T::Profile().
478 
479 private:
480   Ctx Context;
481 
482   /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
483   /// way to convert nodes into a unique specifier.
GetNodeProfile(FoldingSetImpl::Node * N,FoldingSetNodeID & ID)484   void GetNodeProfile(FoldingSetImpl::Node *N,
485                       FoldingSetNodeID &ID) const override {
486     T *TN = static_cast<T *>(N);
487     ContextualFoldingSetTrait<T, Ctx>::Profile(*TN, ID, Context);
488   }
NodeEquals(FoldingSetImpl::Node * N,const FoldingSetNodeID & ID,unsigned IDHash,FoldingSetNodeID & TempID)489   bool NodeEquals(FoldingSetImpl::Node *N, const FoldingSetNodeID &ID,
490                   unsigned IDHash, FoldingSetNodeID &TempID) const override {
491     T *TN = static_cast<T *>(N);
492     return ContextualFoldingSetTrait<T, Ctx>::Equals(*TN, ID, IDHash, TempID,
493                                                      Context);
494   }
ComputeNodeHash(FoldingSetImpl::Node * N,FoldingSetNodeID & TempID)495   unsigned ComputeNodeHash(FoldingSetImpl::Node *N,
496                            FoldingSetNodeID &TempID) const override {
497     T *TN = static_cast<T *>(N);
498     return ContextualFoldingSetTrait<T, Ctx>::ComputeHash(*TN, TempID, Context);
499   }
500 
501 public:
502   explicit ContextualFoldingSet(Ctx Context, unsigned Log2InitSize = 6)
FoldingSetImpl(Log2InitSize)503   : FoldingSetImpl(Log2InitSize), Context(Context)
504   {}
505 
getContext()506   Ctx getContext() const { return Context; }
507 
508   typedef FoldingSetIterator<T> iterator;
begin()509   iterator begin() { return iterator(Buckets); }
end()510   iterator end() { return iterator(Buckets+NumBuckets); }
511 
512   typedef FoldingSetIterator<const T> const_iterator;
begin()513   const_iterator begin() const { return const_iterator(Buckets); }
end()514   const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
515 
516   typedef FoldingSetBucketIterator<T> bucket_iterator;
517 
bucket_begin(unsigned hash)518   bucket_iterator bucket_begin(unsigned hash) {
519     return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
520   }
521 
bucket_end(unsigned hash)522   bucket_iterator bucket_end(unsigned hash) {
523     return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
524   }
525 
526   /// GetOrInsertNode - If there is an existing simple Node exactly
527   /// equal to the specified node, return it.  Otherwise, insert 'N'
528   /// and return it instead.
GetOrInsertNode(Node * N)529   T *GetOrInsertNode(Node *N) {
530     return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
531   }
532 
533   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it
534   /// exists, return it.  If not, return the insertion token that will
535   /// make insertion faster.
FindNodeOrInsertPos(const FoldingSetNodeID & ID,void * & InsertPos)536   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
537     return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
538   }
539 };
540 
541 //===----------------------------------------------------------------------===//
542 /// FoldingSetVector - This template class combines a FoldingSet and a vector
543 /// to provide the interface of FoldingSet but with deterministic iteration
544 /// order based on the insertion order. T must be a subclass of FoldingSetNode
545 /// and implement a Profile function.
546 template <class T, class VectorT = SmallVector<T*, 8> >
547 class FoldingSetVector {
548   FoldingSet<T> Set;
549   VectorT Vector;
550 
551 public:
552   explicit FoldingSetVector(unsigned Log2InitSize = 6)
Set(Log2InitSize)553       : Set(Log2InitSize) {
554   }
555 
556   typedef pointee_iterator<typename VectorT::iterator> iterator;
begin()557   iterator begin() { return Vector.begin(); }
end()558   iterator end()   { return Vector.end(); }
559 
560   typedef pointee_iterator<typename VectorT::const_iterator> const_iterator;
begin()561   const_iterator begin() const { return Vector.begin(); }
end()562   const_iterator end()   const { return Vector.end(); }
563 
564   /// clear - Remove all nodes from the folding set.
clear()565   void clear() { Set.clear(); Vector.clear(); }
566 
567   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
568   /// return it.  If not, return the insertion token that will make insertion
569   /// faster.
FindNodeOrInsertPos(const FoldingSetNodeID & ID,void * & InsertPos)570   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
571     return Set.FindNodeOrInsertPos(ID, InsertPos);
572   }
573 
574   /// GetOrInsertNode - If there is an existing simple Node exactly
575   /// equal to the specified node, return it.  Otherwise, insert 'N' and
576   /// return it instead.
GetOrInsertNode(T * N)577   T *GetOrInsertNode(T *N) {
578     T *Result = Set.GetOrInsertNode(N);
579     if (Result == N) Vector.push_back(N);
580     return Result;
581   }
582 
583   /// InsertNode - Insert the specified node into the folding set, knowing that
584   /// it is not already in the folding set.  InsertPos must be obtained from
585   /// FindNodeOrInsertPos.
InsertNode(T * N,void * InsertPos)586   void InsertNode(T *N, void *InsertPos) {
587     Set.InsertNode(N, InsertPos);
588     Vector.push_back(N);
589   }
590 
591   /// InsertNode - Insert the specified node into the folding set, knowing that
592   /// it is not already in the folding set.
InsertNode(T * N)593   void InsertNode(T *N) {
594     Set.InsertNode(N);
595     Vector.push_back(N);
596   }
597 
598   /// size - Returns the number of nodes in the folding set.
size()599   unsigned size() const { return Set.size(); }
600 
601   /// empty - Returns true if there are no nodes in the folding set.
empty()602   bool empty() const { return Set.empty(); }
603 };
604 
605 //===----------------------------------------------------------------------===//
606 /// FoldingSetIteratorImpl - This is the common iterator support shared by all
607 /// folding sets, which knows how to walk the folding set hash table.
608 class FoldingSetIteratorImpl {
609 protected:
610   FoldingSetNode *NodePtr;
611   FoldingSetIteratorImpl(void **Bucket);
612   void advance();
613 
614 public:
615   bool operator==(const FoldingSetIteratorImpl &RHS) const {
616     return NodePtr == RHS.NodePtr;
617   }
618   bool operator!=(const FoldingSetIteratorImpl &RHS) const {
619     return NodePtr != RHS.NodePtr;
620   }
621 };
622 
623 template <class T> class FoldingSetIterator : public FoldingSetIteratorImpl {
624 public:
FoldingSetIterator(void ** Bucket)625   explicit FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
626 
627   T &operator*() const {
628     return *static_cast<T*>(NodePtr);
629   }
630 
631   T *operator->() const {
632     return static_cast<T*>(NodePtr);
633   }
634 
635   inline FoldingSetIterator &operator++() {          // Preincrement
636     advance();
637     return *this;
638   }
639   FoldingSetIterator operator++(int) {        // Postincrement
640     FoldingSetIterator tmp = *this; ++*this; return tmp;
641   }
642 };
643 
644 //===----------------------------------------------------------------------===//
645 /// FoldingSetBucketIteratorImpl - This is the common bucket iterator support
646 /// shared by all folding sets, which knows how to walk a particular bucket
647 /// of a folding set hash table.
648 
649 class FoldingSetBucketIteratorImpl {
650 protected:
651   void *Ptr;
652 
653   explicit FoldingSetBucketIteratorImpl(void **Bucket);
654 
FoldingSetBucketIteratorImpl(void ** Bucket,bool)655   FoldingSetBucketIteratorImpl(void **Bucket, bool)
656     : Ptr(Bucket) {}
657 
advance()658   void advance() {
659     void *Probe = static_cast<FoldingSetNode*>(Ptr)->getNextInBucket();
660     uintptr_t x = reinterpret_cast<uintptr_t>(Probe) & ~0x1;
661     Ptr = reinterpret_cast<void*>(x);
662   }
663 
664 public:
665   bool operator==(const FoldingSetBucketIteratorImpl &RHS) const {
666     return Ptr == RHS.Ptr;
667   }
668   bool operator!=(const FoldingSetBucketIteratorImpl &RHS) const {
669     return Ptr != RHS.Ptr;
670   }
671 };
672 
673 template <class T>
674 class FoldingSetBucketIterator : public FoldingSetBucketIteratorImpl {
675 public:
FoldingSetBucketIterator(void ** Bucket)676   explicit FoldingSetBucketIterator(void **Bucket) :
677     FoldingSetBucketIteratorImpl(Bucket) {}
678 
FoldingSetBucketIterator(void ** Bucket,bool)679   FoldingSetBucketIterator(void **Bucket, bool) :
680     FoldingSetBucketIteratorImpl(Bucket, true) {}
681 
682   T &operator*() const { return *static_cast<T*>(Ptr); }
683   T *operator->() const { return static_cast<T*>(Ptr); }
684 
685   inline FoldingSetBucketIterator &operator++() { // Preincrement
686     advance();
687     return *this;
688   }
689   FoldingSetBucketIterator operator++(int) {      // Postincrement
690     FoldingSetBucketIterator tmp = *this; ++*this; return tmp;
691   }
692 };
693 
694 //===----------------------------------------------------------------------===//
695 /// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
696 /// types in an enclosing object so that they can be inserted into FoldingSets.
697 template <typename T>
698 class FoldingSetNodeWrapper : public FoldingSetNode {
699   T data;
700 
701 public:
702   template <typename... Ts>
FoldingSetNodeWrapper(Ts &&...Args)703   explicit FoldingSetNodeWrapper(Ts &&... Args)
704       : data(std::forward<Ts>(Args)...) {}
705 
Profile(FoldingSetNodeID & ID)706   void Profile(FoldingSetNodeID &ID) { FoldingSetTrait<T>::Profile(data, ID); }
707 
getValue()708   T &getValue() { return data; }
getValue()709   const T &getValue() const { return data; }
710 
711   operator T&() { return data; }
712   operator const T&() const { return data; }
713 };
714 
715 //===----------------------------------------------------------------------===//
716 /// FastFoldingSetNode - This is a subclass of FoldingSetNode which stores
717 /// a FoldingSetNodeID value rather than requiring the node to recompute it
718 /// each time it is needed. This trades space for speed (which can be
719 /// significant if the ID is long), and it also permits nodes to drop
720 /// information that would otherwise only be required for recomputing an ID.
721 class FastFoldingSetNode : public FoldingSetNode {
722   FoldingSetNodeID FastID;
723 
724 protected:
FastFoldingSetNode(const FoldingSetNodeID & ID)725   explicit FastFoldingSetNode(const FoldingSetNodeID &ID) : FastID(ID) {}
726 
727 public:
Profile(FoldingSetNodeID & ID)728   void Profile(FoldingSetNodeID &ID) const { ID.AddNodeID(FastID); }
729 };
730 
731 //===----------------------------------------------------------------------===//
732 // Partial specializations of FoldingSetTrait.
733 
734 template<typename T> struct FoldingSetTrait<T*> {
735   static inline void Profile(T *X, FoldingSetNodeID &ID) {
736     ID.AddPointer(X);
737   }
738 };
739 template <typename T1, typename T2>
740 struct FoldingSetTrait<std::pair<T1, T2>> {
741   static inline void Profile(const std::pair<T1, T2> &P,
742                              llvm::FoldingSetNodeID &ID) {
743     ID.Add(P.first);
744     ID.Add(P.second);
745   }
746 };
747 } // End of namespace llvm.
748 
749 #endif
750