Whitespace.
[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/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   virtual void anchor(); // Out of line virtual method.
111
112 protected:
113   /// Buckets - Array of bucket chains.
114   ///
115   void **Buckets;
116
117   /// NumBuckets - Length of the Buckets array.  Always a power of 2.
118   ///
119   unsigned NumBuckets;
120
121   /// NumNodes - Number of nodes in the folding set. Growth occurs when NumNodes
122   /// is greater than twice the number of buckets.
123   unsigned NumNodes;
124
125   ~FoldingSetImpl();
126
127   explicit FoldingSetImpl(unsigned Log2InitSize = 6);
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:
140     Node() : NextInFoldingSetBucket(nullptr) {}
141
142     // Accessors
143     void *getNextInBucket() const { return NextInFoldingSetBucket; }
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.
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.
178   unsigned size() const { return NumNodes; }
179
180   /// empty - Returns true if there are no nodes in the folding set.
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 {
209   static void Profile(const T &X, FoldingSetNodeID &ID) {
210     X.Profile(ID);
211   }
212   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 {
246   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:
271   FoldingSetNodeIDRef() : Data(nullptr), Size(0) {}
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
286   const unsigned *getData() const { return Data; }
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:
301   FoldingSetNodeID() {}
302
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);
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>
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.
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
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
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
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
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 template <class T> class FoldingSet final : public FoldingSetImpl {
395 private:
396   /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
397   /// way to convert nodes into a unique specifier.
398   void GetNodeProfile(Node *N, FoldingSetNodeID &ID) const override {
399     T *TN = static_cast<T *>(N);
400     FoldingSetTrait<T>::Profile(*TN, ID);
401   }
402   /// NodeEquals - Instantiations may optionally provide a way to compare a
403   /// node with a specified ID.
404   bool NodeEquals(Node *N, const FoldingSetNodeID &ID, unsigned IDHash,
405                   FoldingSetNodeID &TempID) const override {
406     T *TN = static_cast<T *>(N);
407     return FoldingSetTrait<T>::Equals(*TN, ID, IDHash, TempID);
408   }
409   /// ComputeNodeHash - Instantiations may optionally provide a way to compute a
410   /// hash value directly from a node.
411   unsigned ComputeNodeHash(Node *N, FoldingSetNodeID &TempID) const override {
412     T *TN = static_cast<T *>(N);
413     return FoldingSetTrait<T>::ComputeHash(*TN, TempID);
414   }
415
416 public:
417   explicit FoldingSet(unsigned Log2InitSize = 6)
418   : FoldingSetImpl(Log2InitSize)
419   {}
420
421   typedef FoldingSetIterator<T> iterator;
422   iterator begin() { return iterator(Buckets); }
423   iterator end() { return iterator(Buckets+NumBuckets); }
424
425   typedef FoldingSetIterator<const T> const_iterator;
426   const_iterator begin() const { return const_iterator(Buckets); }
427   const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
428
429   typedef FoldingSetBucketIterator<T> bucket_iterator;
430
431   bucket_iterator bucket_begin(unsigned hash) {
432     return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
433   }
434
435   bucket_iterator bucket_end(unsigned hash) {
436     return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
437   }
438
439   /// GetOrInsertNode - If there is an existing simple Node exactly
440   /// equal to the specified node, return it.  Otherwise, insert 'N' and
441   /// return it instead.
442   T *GetOrInsertNode(Node *N) {
443     return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
444   }
445
446   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
447   /// return it.  If not, return the insertion token that will make insertion
448   /// faster.
449   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
450     return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
451   }
452 };
453
454 //===----------------------------------------------------------------------===//
455 /// ContextualFoldingSet - This template class is a further refinement
456 /// of FoldingSet which provides a context argument when calling
457 /// Profile on its nodes.  Currently, that argument is fixed at
458 /// initialization time.
459 ///
460 /// T must be a subclass of FoldingSetNode and implement a Profile
461 /// function with signature
462 ///   void Profile(llvm::FoldingSetNodeID &, Ctx);
463 template <class T, class Ctx>
464 class ContextualFoldingSet final : public FoldingSetImpl {
465   // Unfortunately, this can't derive from FoldingSet<T> because the
466   // construction vtable for FoldingSet<T> requires
467   // FoldingSet<T>::GetNodeProfile to be instantiated, which in turn
468   // requires a single-argument T::Profile().
469
470 private:
471   Ctx Context;
472
473   /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
474   /// way to convert nodes into a unique specifier.
475   void GetNodeProfile(FoldingSetImpl::Node *N,
476                       FoldingSetNodeID &ID) const override {
477     T *TN = static_cast<T *>(N);
478     ContextualFoldingSetTrait<T, Ctx>::Profile(*TN, ID, Context);
479   }
480   bool NodeEquals(FoldingSetImpl::Node *N, const FoldingSetNodeID &ID,
481                   unsigned IDHash, FoldingSetNodeID &TempID) const override {
482     T *TN = static_cast<T *>(N);
483     return ContextualFoldingSetTrait<T, Ctx>::Equals(*TN, ID, IDHash, TempID,
484                                                      Context);
485   }
486   unsigned ComputeNodeHash(FoldingSetImpl::Node *N,
487                            FoldingSetNodeID &TempID) const override {
488     T *TN = static_cast<T *>(N);
489     return ContextualFoldingSetTrait<T, Ctx>::ComputeHash(*TN, TempID, Context);
490   }
491
492 public:
493   explicit ContextualFoldingSet(Ctx Context, unsigned Log2InitSize = 6)
494   : FoldingSetImpl(Log2InitSize), Context(Context)
495   {}
496
497   Ctx getContext() const { return Context; }
498
499   typedef FoldingSetIterator<T> iterator;
500   iterator begin() { return iterator(Buckets); }
501   iterator end() { return iterator(Buckets+NumBuckets); }
502
503   typedef FoldingSetIterator<const T> const_iterator;
504   const_iterator begin() const { return const_iterator(Buckets); }
505   const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
506
507   typedef FoldingSetBucketIterator<T> bucket_iterator;
508
509   bucket_iterator bucket_begin(unsigned hash) {
510     return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
511   }
512
513   bucket_iterator bucket_end(unsigned hash) {
514     return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
515   }
516
517   /// GetOrInsertNode - If there is an existing simple Node exactly
518   /// equal to the specified node, return it.  Otherwise, insert 'N'
519   /// and return it instead.
520   T *GetOrInsertNode(Node *N) {
521     return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
522   }
523
524   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it
525   /// exists, return it.  If not, return the insertion token that will
526   /// make insertion faster.
527   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
528     return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
529   }
530 };
531
532 //===----------------------------------------------------------------------===//
533 /// FoldingSetVector - This template class combines a FoldingSet and a vector
534 /// to provide the interface of FoldingSet but with deterministic iteration
535 /// order based on the insertion order. T must be a subclass of FoldingSetNode
536 /// and implement a Profile function.
537 template <class T, class VectorT = SmallVector<T*, 8> >
538 class FoldingSetVector {
539   FoldingSet<T> Set;
540   VectorT Vector;
541
542 public:
543   explicit FoldingSetVector(unsigned Log2InitSize = 6)
544       : Set(Log2InitSize) {
545   }
546
547   typedef pointee_iterator<typename VectorT::iterator> iterator;
548   iterator begin() { return Vector.begin(); }
549   iterator end()   { return Vector.end(); }
550
551   typedef pointee_iterator<typename VectorT::const_iterator> const_iterator;
552   const_iterator begin() const { return Vector.begin(); }
553   const_iterator end()   const { return Vector.end(); }
554
555   /// clear - Remove all nodes from the folding set.
556   void clear() { Set.clear(); Vector.clear(); }
557
558   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
559   /// return it.  If not, return the insertion token that will make insertion
560   /// faster.
561   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
562     return Set.FindNodeOrInsertPos(ID, InsertPos);
563   }
564
565   /// GetOrInsertNode - If there is an existing simple Node exactly
566   /// equal to the specified node, return it.  Otherwise, insert 'N' and
567   /// return it instead.
568   T *GetOrInsertNode(T *N) {
569     T *Result = Set.GetOrInsertNode(N);
570     if (Result == N) Vector.push_back(N);
571     return Result;
572   }
573
574   /// InsertNode - Insert the specified node into the folding set, knowing that
575   /// it is not already in the folding set.  InsertPos must be obtained from
576   /// FindNodeOrInsertPos.
577   void InsertNode(T *N, void *InsertPos) {
578     Set.InsertNode(N, InsertPos);
579     Vector.push_back(N);
580   }
581
582   /// InsertNode - Insert the specified node into the folding set, knowing that
583   /// it is not already in the folding set.
584   void InsertNode(T *N) {
585     Set.InsertNode(N);
586     Vector.push_back(N);
587   }
588
589   /// size - Returns the number of nodes in the folding set.
590   unsigned size() const { return Set.size(); }
591
592   /// empty - Returns true if there are no nodes in the folding set.
593   bool empty() const { return Set.empty(); }
594 };
595
596 //===----------------------------------------------------------------------===//
597 /// FoldingSetIteratorImpl - This is the common iterator support shared by all
598 /// folding sets, which knows how to walk the folding set hash table.
599 class FoldingSetIteratorImpl {
600 protected:
601   FoldingSetNode *NodePtr;
602   FoldingSetIteratorImpl(void **Bucket);
603   void advance();
604
605 public:
606   bool operator==(const FoldingSetIteratorImpl &RHS) const {
607     return NodePtr == RHS.NodePtr;
608   }
609   bool operator!=(const FoldingSetIteratorImpl &RHS) const {
610     return NodePtr != RHS.NodePtr;
611   }
612 };
613
614 template<class T>
615 class FoldingSetIterator : public FoldingSetIteratorImpl {
616 public:
617   explicit FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
618
619   T &operator*() const {
620     return *static_cast<T*>(NodePtr);
621   }
622
623   T *operator->() const {
624     return static_cast<T*>(NodePtr);
625   }
626
627   inline FoldingSetIterator &operator++() {          // Preincrement
628     advance();
629     return *this;
630   }
631   FoldingSetIterator operator++(int) {        // Postincrement
632     FoldingSetIterator tmp = *this; ++*this; return tmp;
633   }
634 };
635
636 //===----------------------------------------------------------------------===//
637 /// FoldingSetBucketIteratorImpl - This is the common bucket iterator support
638 /// shared by all folding sets, which knows how to walk a particular bucket
639 /// of a folding set hash table.
640
641 class FoldingSetBucketIteratorImpl {
642 protected:
643   void *Ptr;
644
645   explicit FoldingSetBucketIteratorImpl(void **Bucket);
646
647   FoldingSetBucketIteratorImpl(void **Bucket, bool)
648     : Ptr(Bucket) {}
649
650   void advance() {
651     void *Probe = static_cast<FoldingSetNode*>(Ptr)->getNextInBucket();
652     uintptr_t x = reinterpret_cast<uintptr_t>(Probe) & ~0x1;
653     Ptr = reinterpret_cast<void*>(x);
654   }
655
656 public:
657   bool operator==(const FoldingSetBucketIteratorImpl &RHS) const {
658     return Ptr == RHS.Ptr;
659   }
660   bool operator!=(const FoldingSetBucketIteratorImpl &RHS) const {
661     return Ptr != RHS.Ptr;
662   }
663 };
664
665 template<class T>
666 class FoldingSetBucketIterator : public FoldingSetBucketIteratorImpl {
667 public:
668   explicit FoldingSetBucketIterator(void **Bucket) :
669     FoldingSetBucketIteratorImpl(Bucket) {}
670
671   FoldingSetBucketIterator(void **Bucket, bool) :
672     FoldingSetBucketIteratorImpl(Bucket, true) {}
673
674   T &operator*() const { return *static_cast<T*>(Ptr); }
675   T *operator->() const { return static_cast<T*>(Ptr); }
676
677   inline FoldingSetBucketIterator &operator++() { // Preincrement
678     advance();
679     return *this;
680   }
681   FoldingSetBucketIterator operator++(int) {      // Postincrement
682     FoldingSetBucketIterator tmp = *this; ++*this; return tmp;
683   }
684 };
685
686 //===----------------------------------------------------------------------===//
687 /// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
688 /// types in an enclosing object so that they can be inserted into FoldingSets.
689 template <typename T>
690 class FoldingSetNodeWrapper : public FoldingSetNode {
691   T data;
692
693 public:
694   template <typename... Ts>
695   explicit FoldingSetNodeWrapper(Ts &&... Args)
696       : data(std::forward<Ts>(Args)...) {}
697
698   void Profile(FoldingSetNodeID &ID) { FoldingSetTrait<T>::Profile(data, ID); }
699
700   T &getValue() { return data; }
701   const T &getValue() const { return data; }
702
703   operator T&() { return data; }
704   operator const T&() const { return data; }
705 };
706
707 //===----------------------------------------------------------------------===//
708 /// FastFoldingSetNode - This is a subclass of FoldingSetNode which stores
709 /// a FoldingSetNodeID value rather than requiring the node to recompute it
710 /// each time it is needed. This trades space for speed (which can be
711 /// significant if the ID is long), and it also permits nodes to drop
712 /// information that would otherwise only be required for recomputing an ID.
713 class FastFoldingSetNode : public FoldingSetNode {
714   FoldingSetNodeID FastID;
715
716 protected:
717   explicit FastFoldingSetNode(const FoldingSetNodeID &ID) : FastID(ID) {}
718
719 public:
720   void Profile(FoldingSetNodeID &ID) const {
721     ID.AddNodeID(FastID);
722   }
723 };
724
725 //===----------------------------------------------------------------------===//
726 // Partial specializations of FoldingSetTrait.
727
728 template<typename T> struct FoldingSetTrait<T*> {
729   static inline void Profile(T *X, FoldingSetNodeID &ID) {
730     ID.AddPointer(X);
731   }
732 };
733 template <typename T1, typename T2>
734 struct FoldingSetTrait<std::pair<T1, T2>> {
735   static inline void Profile(const std::pair<T1, T2> &P,
736                              llvm::FoldingSetNodeID &ID) {
737     ID.Add(P.first);
738     ID.Add(P.second);
739   }
740 };
741 } // End of namespace llvm.
742
743 #endif