LLVM  mainline
FoldingSet.cpp
Go to the documentation of this file.
00001 //===-- Support/FoldingSet.cpp - Uniquing Hash Set --------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements a hash set that can be used to remove duplication of
00011 // nodes in a graph.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/ADT/FoldingSet.h"
00016 #include "llvm/ADT/Hashing.h"
00017 #include "llvm/Support/Allocator.h"
00018 #include "llvm/Support/ErrorHandling.h"
00019 #include "llvm/Support/Host.h"
00020 #include "llvm/Support/MathExtras.h"
00021 #include <cassert>
00022 #include <cstring>
00023 using namespace llvm;
00024 
00025 //===----------------------------------------------------------------------===//
00026 // FoldingSetNodeIDRef Implementation
00027 
00028 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
00029 /// used to lookup the node in the FoldingSetImpl.
00030 unsigned FoldingSetNodeIDRef::ComputeHash() const {
00031   return static_cast<unsigned>(hash_combine_range(Data, Data+Size));
00032 }
00033 
00034 bool FoldingSetNodeIDRef::operator==(FoldingSetNodeIDRef RHS) const {
00035   if (Size != RHS.Size) return false;
00036   return memcmp(Data, RHS.Data, Size*sizeof(*Data)) == 0;
00037 }
00038 
00039 /// Used to compare the "ordering" of two nodes as defined by the
00040 /// profiled bits and their ordering defined by memcmp().
00041 bool FoldingSetNodeIDRef::operator<(FoldingSetNodeIDRef RHS) const {
00042   if (Size != RHS.Size)
00043     return Size < RHS.Size;
00044   return memcmp(Data, RHS.Data, Size*sizeof(*Data)) < 0;
00045 }
00046 
00047 //===----------------------------------------------------------------------===//
00048 // FoldingSetNodeID Implementation
00049 
00050 /// Add* - Add various data types to Bit data.
00051 ///
00052 void FoldingSetNodeID::AddPointer(const void *Ptr) {
00053   // Note: this adds pointers to the hash using sizes and endianness that
00054   // depend on the host. It doesn't matter, however, because hashing on
00055   // pointer values is inherently unstable. Nothing should depend on the
00056   // ordering of nodes in the folding set.
00057   Bits.append(reinterpret_cast<unsigned *>(&Ptr),
00058               reinterpret_cast<unsigned *>(&Ptr+1));
00059 }
00060 void FoldingSetNodeID::AddInteger(signed I) {
00061   Bits.push_back(I);
00062 }
00063 void FoldingSetNodeID::AddInteger(unsigned I) {
00064   Bits.push_back(I);
00065 }
00066 void FoldingSetNodeID::AddInteger(long I) {
00067   AddInteger((unsigned long)I);
00068 }
00069 void FoldingSetNodeID::AddInteger(unsigned long I) {
00070   if (sizeof(long) == sizeof(int))
00071     AddInteger(unsigned(I));
00072   else if (sizeof(long) == sizeof(long long)) {
00073     AddInteger((unsigned long long)I);
00074   } else {
00075     llvm_unreachable("unexpected sizeof(long)");
00076   }
00077 }
00078 void FoldingSetNodeID::AddInteger(long long I) {
00079   AddInteger((unsigned long long)I);
00080 }
00081 void FoldingSetNodeID::AddInteger(unsigned long long I) {
00082   AddInteger(unsigned(I));
00083   if ((uint64_t)(unsigned)I != I)
00084     Bits.push_back(unsigned(I >> 32));
00085 }
00086 
00087 void FoldingSetNodeID::AddString(StringRef String) {
00088   unsigned Size =  String.size();
00089   Bits.push_back(Size);
00090   if (!Size) return;
00091 
00092   unsigned Units = Size / 4;
00093   unsigned Pos = 0;
00094   const unsigned *Base = (const unsigned*) String.data();
00095   
00096   // If the string is aligned do a bulk transfer.
00097   if (!((intptr_t)Base & 3)) {
00098     Bits.append(Base, Base + Units);
00099     Pos = (Units + 1) * 4;
00100   } else {
00101     // Otherwise do it the hard way.
00102     // To be compatible with above bulk transfer, we need to take endianness
00103     // into account.
00104     static_assert(sys::IsBigEndianHost || sys::IsLittleEndianHost,
00105                   "Unexpected host endianness");
00106     if (sys::IsBigEndianHost) {
00107       for (Pos += 4; Pos <= Size; Pos += 4) {
00108         unsigned V = ((unsigned char)String[Pos - 4] << 24) |
00109                      ((unsigned char)String[Pos - 3] << 16) |
00110                      ((unsigned char)String[Pos - 2] << 8) |
00111                       (unsigned char)String[Pos - 1];
00112         Bits.push_back(V);
00113       }
00114     } else {  // Little-endian host
00115       for (Pos += 4; Pos <= Size; Pos += 4) {
00116         unsigned V = ((unsigned char)String[Pos - 1] << 24) |
00117                      ((unsigned char)String[Pos - 2] << 16) |
00118                      ((unsigned char)String[Pos - 3] << 8) |
00119                       (unsigned char)String[Pos - 4];
00120         Bits.push_back(V);
00121       }
00122     }
00123   }
00124   
00125   // With the leftover bits.
00126   unsigned V = 0;
00127   // Pos will have overshot size by 4 - #bytes left over.
00128   // No need to take endianness into account here - this is always executed.
00129   switch (Pos - Size) {
00130   case 1: V = (V << 8) | (unsigned char)String[Size - 3]; // Fall thru.
00131   case 2: V = (V << 8) | (unsigned char)String[Size - 2]; // Fall thru.
00132   case 3: V = (V << 8) | (unsigned char)String[Size - 1]; break;
00133   default: return; // Nothing left.
00134   }
00135 
00136   Bits.push_back(V);
00137 }
00138 
00139 // AddNodeID - Adds the Bit data of another ID to *this.
00140 void FoldingSetNodeID::AddNodeID(const FoldingSetNodeID &ID) {
00141   Bits.append(ID.Bits.begin(), ID.Bits.end());
00142 }
00143 
00144 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used to 
00145 /// lookup the node in the FoldingSetImpl.
00146 unsigned FoldingSetNodeID::ComputeHash() const {
00147   return FoldingSetNodeIDRef(Bits.data(), Bits.size()).ComputeHash();
00148 }
00149 
00150 /// operator== - Used to compare two nodes to each other.
00151 ///
00152 bool FoldingSetNodeID::operator==(const FoldingSetNodeID &RHS) const {
00153   return *this == FoldingSetNodeIDRef(RHS.Bits.data(), RHS.Bits.size());
00154 }
00155 
00156 /// operator== - Used to compare two nodes to each other.
00157 ///
00158 bool FoldingSetNodeID::operator==(FoldingSetNodeIDRef RHS) const {
00159   return FoldingSetNodeIDRef(Bits.data(), Bits.size()) == RHS;
00160 }
00161 
00162 /// Used to compare the "ordering" of two nodes as defined by the
00163 /// profiled bits and their ordering defined by memcmp().
00164 bool FoldingSetNodeID::operator<(const FoldingSetNodeID &RHS) const {
00165   return *this < FoldingSetNodeIDRef(RHS.Bits.data(), RHS.Bits.size());
00166 }
00167 
00168 bool FoldingSetNodeID::operator<(FoldingSetNodeIDRef RHS) const {
00169   return FoldingSetNodeIDRef(Bits.data(), Bits.size()) < RHS;
00170 }
00171 
00172 /// Intern - Copy this node's data to a memory region allocated from the
00173 /// given allocator and return a FoldingSetNodeIDRef describing the
00174 /// interned data.
00175 FoldingSetNodeIDRef
00176 FoldingSetNodeID::Intern(BumpPtrAllocator &Allocator) const {
00177   unsigned *New = Allocator.Allocate<unsigned>(Bits.size());
00178   std::uninitialized_copy(Bits.begin(), Bits.end(), New);
00179   return FoldingSetNodeIDRef(New, Bits.size());
00180 }
00181 
00182 //===----------------------------------------------------------------------===//
00183 /// Helper functions for FoldingSetImpl.
00184 
00185 /// GetNextPtr - In order to save space, each bucket is a
00186 /// singly-linked-list. In order to make deletion more efficient, we make
00187 /// the list circular, so we can delete a node without computing its hash.
00188 /// The problem with this is that the start of the hash buckets are not
00189 /// Nodes.  If NextInBucketPtr is a bucket pointer, this method returns null:
00190 /// use GetBucketPtr when this happens.
00191 static FoldingSetImpl::Node *GetNextPtr(void *NextInBucketPtr) {
00192   // The low bit is set if this is the pointer back to the bucket.
00193   if (reinterpret_cast<intptr_t>(NextInBucketPtr) & 1)
00194     return nullptr;
00195   
00196   return static_cast<FoldingSetImpl::Node*>(NextInBucketPtr);
00197 }
00198 
00199 
00200 /// testing.
00201 static void **GetBucketPtr(void *NextInBucketPtr) {
00202   intptr_t Ptr = reinterpret_cast<intptr_t>(NextInBucketPtr);
00203   assert((Ptr & 1) && "Not a bucket pointer");
00204   return reinterpret_cast<void**>(Ptr & ~intptr_t(1));
00205 }
00206 
00207 /// GetBucketFor - Hash the specified node ID and return the hash bucket for
00208 /// the specified ID.
00209 static void **GetBucketFor(unsigned Hash, void **Buckets, unsigned NumBuckets) {
00210   // NumBuckets is always a power of 2.
00211   unsigned BucketNum = Hash & (NumBuckets-1);
00212   return Buckets + BucketNum;
00213 }
00214 
00215 /// AllocateBuckets - Allocated initialized bucket memory.
00216 static void **AllocateBuckets(unsigned NumBuckets) {
00217   void **Buckets = static_cast<void**>(calloc(NumBuckets+1, sizeof(void*)));
00218   // Set the very last bucket to be a non-null "pointer".
00219   Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
00220   return Buckets;
00221 }
00222 
00223 //===----------------------------------------------------------------------===//
00224 // FoldingSetImpl Implementation
00225 
00226 void FoldingSetImpl::anchor() {}
00227 
00228 FoldingSetImpl::FoldingSetImpl(unsigned Log2InitSize) {
00229   assert(5 < Log2InitSize && Log2InitSize < 32 &&
00230          "Initial hash table size out of range");
00231   NumBuckets = 1 << Log2InitSize;
00232   Buckets = AllocateBuckets(NumBuckets);
00233   NumNodes = 0;
00234 }
00235 
00236 FoldingSetImpl::FoldingSetImpl(FoldingSetImpl &&Arg)
00237     : Buckets(Arg.Buckets), NumBuckets(Arg.NumBuckets), NumNodes(Arg.NumNodes) {
00238   Arg.Buckets = nullptr;
00239   Arg.NumBuckets = 0;
00240   Arg.NumNodes = 0;
00241 }
00242 
00243 FoldingSetImpl &FoldingSetImpl::operator=(FoldingSetImpl &&RHS) {
00244   free(Buckets); // This may be null if the set is in a moved-from state.
00245   Buckets = RHS.Buckets;
00246   NumBuckets = RHS.NumBuckets;
00247   NumNodes = RHS.NumNodes;
00248   RHS.Buckets = nullptr;
00249   RHS.NumBuckets = 0;
00250   RHS.NumNodes = 0;
00251   return *this;
00252 }
00253 
00254 FoldingSetImpl::~FoldingSetImpl() {
00255   free(Buckets);
00256 }
00257 
00258 void FoldingSetImpl::clear() {
00259   // Set all but the last bucket to null pointers.
00260   memset(Buckets, 0, NumBuckets*sizeof(void*));
00261 
00262   // Set the very last bucket to be a non-null "pointer".
00263   Buckets[NumBuckets] = reinterpret_cast<void*>(-1);
00264 
00265   // Reset the node count to zero.
00266   NumNodes = 0;
00267 }
00268 
00269 /// GrowHashTable - Double the size of the hash table and rehash everything.
00270 ///
00271 void FoldingSetImpl::GrowHashTable() {
00272   void **OldBuckets = Buckets;
00273   unsigned OldNumBuckets = NumBuckets;
00274   NumBuckets <<= 1;
00275   
00276   // Clear out new buckets.
00277   Buckets = AllocateBuckets(NumBuckets);
00278   NumNodes = 0;
00279 
00280   // Walk the old buckets, rehashing nodes into their new place.
00281   FoldingSetNodeID TempID;
00282   for (unsigned i = 0; i != OldNumBuckets; ++i) {
00283     void *Probe = OldBuckets[i];
00284     if (!Probe) continue;
00285     while (Node *NodeInBucket = GetNextPtr(Probe)) {
00286       // Figure out the next link, remove NodeInBucket from the old link.
00287       Probe = NodeInBucket->getNextInBucket();
00288       NodeInBucket->SetNextInBucket(nullptr);
00289 
00290       // Insert the node into the new bucket, after recomputing the hash.
00291       InsertNode(NodeInBucket,
00292                  GetBucketFor(ComputeNodeHash(NodeInBucket, TempID),
00293                               Buckets, NumBuckets));
00294       TempID.clear();
00295     }
00296   }
00297   
00298   free(OldBuckets);
00299 }
00300 
00301 /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
00302 /// return it.  If not, return the insertion token that will make insertion
00303 /// faster.
00304 FoldingSetImpl::Node
00305 *FoldingSetImpl::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
00306                                      void *&InsertPos) {
00307   unsigned IDHash = ID.ComputeHash();
00308   void **Bucket = GetBucketFor(IDHash, Buckets, NumBuckets);
00309   void *Probe = *Bucket;
00310   
00311   InsertPos = nullptr;
00312   
00313   FoldingSetNodeID TempID;
00314   while (Node *NodeInBucket = GetNextPtr(Probe)) {
00315     if (NodeEquals(NodeInBucket, ID, IDHash, TempID))
00316       return NodeInBucket;
00317     TempID.clear();
00318 
00319     Probe = NodeInBucket->getNextInBucket();
00320   }
00321   
00322   // Didn't find the node, return null with the bucket as the InsertPos.
00323   InsertPos = Bucket;
00324   return nullptr;
00325 }
00326 
00327 /// InsertNode - Insert the specified node into the folding set, knowing that it
00328 /// is not already in the map.  InsertPos must be obtained from 
00329 /// FindNodeOrInsertPos.
00330 void FoldingSetImpl::InsertNode(Node *N, void *InsertPos) {
00331   assert(!N->getNextInBucket());
00332   // Do we need to grow the hashtable?
00333   if (NumNodes+1 > NumBuckets*2) {
00334     GrowHashTable();
00335     FoldingSetNodeID TempID;
00336     InsertPos = GetBucketFor(ComputeNodeHash(N, TempID), Buckets, NumBuckets);
00337   }
00338 
00339   ++NumNodes;
00340   
00341   /// The insert position is actually a bucket pointer.
00342   void **Bucket = static_cast<void**>(InsertPos);
00343   
00344   void *Next = *Bucket;
00345   
00346   // If this is the first insertion into this bucket, its next pointer will be
00347   // null.  Pretend as if it pointed to itself, setting the low bit to indicate
00348   // that it is a pointer to the bucket.
00349   if (!Next)
00350     Next = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(Bucket)|1);
00351 
00352   // Set the node's next pointer, and make the bucket point to the node.
00353   N->SetNextInBucket(Next);
00354   *Bucket = N;
00355 }
00356 
00357 /// RemoveNode - Remove a node from the folding set, returning true if one was
00358 /// removed or false if the node was not in the folding set.
00359 bool FoldingSetImpl::RemoveNode(Node *N) {
00360   // Because each bucket is a circular list, we don't need to compute N's hash
00361   // to remove it.
00362   void *Ptr = N->getNextInBucket();
00363   if (!Ptr) return false;  // Not in folding set.
00364 
00365   --NumNodes;
00366   N->SetNextInBucket(nullptr);
00367 
00368   // Remember what N originally pointed to, either a bucket or another node.
00369   void *NodeNextPtr = Ptr;
00370   
00371   // Chase around the list until we find the node (or bucket) which points to N.
00372   while (true) {
00373     if (Node *NodeInBucket = GetNextPtr(Ptr)) {
00374       // Advance pointer.
00375       Ptr = NodeInBucket->getNextInBucket();
00376       
00377       // We found a node that points to N, change it to point to N's next node,
00378       // removing N from the list.
00379       if (Ptr == N) {
00380         NodeInBucket->SetNextInBucket(NodeNextPtr);
00381         return true;
00382       }
00383     } else {
00384       void **Bucket = GetBucketPtr(Ptr);
00385       Ptr = *Bucket;
00386       
00387       // If we found that the bucket points to N, update the bucket to point to
00388       // whatever is next.
00389       if (Ptr == N) {
00390         *Bucket = NodeNextPtr;
00391         return true;
00392       }
00393     }
00394   }
00395 }
00396 
00397 /// GetOrInsertNode - If there is an existing simple Node exactly
00398 /// equal to the specified node, return it.  Otherwise, insert 'N' and it
00399 /// instead.
00400 FoldingSetImpl::Node *FoldingSetImpl::GetOrInsertNode(FoldingSetImpl::Node *N) {
00401   FoldingSetNodeID ID;
00402   GetNodeProfile(N, ID);
00403   void *IP;
00404   if (Node *E = FindNodeOrInsertPos(ID, IP))
00405     return E;
00406   InsertNode(N, IP);
00407   return N;
00408 }
00409 
00410 //===----------------------------------------------------------------------===//
00411 // FoldingSetIteratorImpl Implementation
00412 
00413 FoldingSetIteratorImpl::FoldingSetIteratorImpl(void **Bucket) {
00414   // Skip to the first non-null non-self-cycle bucket.
00415   while (*Bucket != reinterpret_cast<void*>(-1) &&
00416          (!*Bucket || !GetNextPtr(*Bucket)))
00417     ++Bucket;
00418   
00419   NodePtr = static_cast<FoldingSetNode*>(*Bucket);
00420 }
00421 
00422 void FoldingSetIteratorImpl::advance() {
00423   // If there is another link within this bucket, go to it.
00424   void *Probe = NodePtr->getNextInBucket();
00425 
00426   if (FoldingSetNode *NextNodeInBucket = GetNextPtr(Probe))
00427     NodePtr = NextNodeInBucket;
00428   else {
00429     // Otherwise, this is the last link in this bucket.  
00430     void **Bucket = GetBucketPtr(Probe);
00431 
00432     // Skip to the next non-null non-self-cycle bucket.
00433     do {
00434       ++Bucket;
00435     } while (*Bucket != reinterpret_cast<void*>(-1) &&
00436              (!*Bucket || !GetNextPtr(*Bucket)));
00437     
00438     NodePtr = static_cast<FoldingSetNode*>(*Bucket);
00439   }
00440 }
00441 
00442 //===----------------------------------------------------------------------===//
00443 // FoldingSetBucketIteratorImpl Implementation
00444 
00445 FoldingSetBucketIteratorImpl::FoldingSetBucketIteratorImpl(void **Bucket) {
00446   Ptr = (!*Bucket || !GetNextPtr(*Bucket)) ? (void*) Bucket : *Bucket;
00447 }