Loads do not remove any nodes from the exec after sets. Also fix a 'node leak'.
[libfirm] / ir / adt / hashset.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Generic hashset implementation
23  * @author  Matthias Braun, inspiration from densehash from google sparsehash
24  *          package
25  * @date    17.03.2007
26  * @version $Id$
27  *
28  *
29  * You have to specialize this file by defining:
30  *
31  * <ul>
32  *  <li><b>HashSet</b>         The name of the hashset type</li>
33  *  <li><b>HashSetIterator</b> The name of the hashset iterator type</li>
34  *  <li><b>ValueType</b>       The type of the stored data values</li>
35  *  <li><b>NullValue</b>       A special value representing no values</li>
36  *  <li><b>DeletedValue</b>    A special value representing deleted entries</li>
37  *  <li><b>Hash(hashset,key)</b> calculates the hash value for a given key</li>
38  * </ul>
39  *
40  * Note that by default it is assumed that the data values themselfes are used
41  * as keys. However you can change that with additional defines:
42  *
43  * <ul>
44  *  <li><b>KeyType</b>         The type of the keys identifying data values.
45  *                             Defining this implies, that a data value contains
46  *                             more than just the key.</li>
47  *  <li><b>GetKey(value)</b>   Extracts the key from a data value</li>
48  *  <li><b>KeysEqual(hashset,key1,key2)</b>  Tests wether 2 keys are equal</li>
49  *  <li><b>DO_REHASH</b>       Instead of storing the hash-values, recalculate
50  *                             them on demand from the datavalues. (usefull if
51  *                             calculating the hash-values takes less time than
52  *                             a memory access)</li>
53  * </ul>
54  *
55  * You can further fine tune your hashset by defining the following:
56  *
57  * <ul>
58  *  <li><b>JUMP(num_probes)</b> The probing method</li>
59  *  <li><b>Alloc(count)</b>     Allocates count hashset entries (NOT bytes)</li>
60  *  <li><b>Free(ptr)</b>        Frees a block of memory allocated by Alloc</li>
61  *  <li><b>SetRangeEmpty(ptr,count)</b> Efficiently sets a range of elements to
62  *                                      the Null value</li>
63  *  <li><b>ADDITIONAL_DATA<b>   Additional fields appended to the hashset struct</li>
64  * </ul>
65  */
66 #ifdef HashSet
67
68 #include <stdlib.h>
69 #include <string.h>
70 #include <assert.h>
71
72 #include "bitfiddle.h"
73 #include "util.h"
74
75 /* quadratic probing */
76 #ifndef JUMP
77 #define JUMP(num_probes)      (num_probes)
78 #endif /* JUMP */
79
80 #ifndef Hash
81 #define ID_HASH
82 #define Hash(self,value)      ((unsigned)(value))
83 #endif /* Hash */
84
85 #ifdef DO_REHASH
86 #define HashSetEntry                   ValueType
87 #define EntrySetHash(entry,new_hash)
88 #define EntryGetHash(self,entry)       Hash(self,entry)
89 #define EntryGetValue(entry)           (entry)
90 #else /* ! DO_REHASH */
91 #define EntryGetHash(self,entry)       (entry).hash
92 #define EntrySetHash(entry,new_hash)   (entry).hash = (new_hash)
93 #define EntryGetValue(entry)           (entry).data
94 #endif /* DO_REHASH */
95
96 #ifndef Alloc
97 #include "xmalloc.h"
98 #define Alloc(size)    (HashSetEntry*) xmalloc((size) * sizeof(HashSetEntry))
99 #define Free(ptr)      free(ptr)
100 #endif /* Alloc */
101
102 #ifdef ID_HASH
103 #define InsertReturnValue               int
104 #define GetInsertReturnValue(entry,new) (new)
105 #else /* ! ID_HASH */
106 #define InsertReturnValue               ValueType
107 #define GetInsertReturnValue(entry,new) EntryGetValue(entry)
108 #endif /* ID_HASH */
109
110 #ifndef KeyType
111 #define KeyType                  ValueType
112 #define GetKey(value)            (value)
113 #define InitData(self,value,key) (value) = (key)
114 #endif /* KeyType */
115
116 #ifndef ConstKeyType
117 #define ConstKeyType             const KeyType
118 #endif /* ConstKeyType */
119
120 #ifndef EntrySetEmpty
121 #define EntrySetEmpty(entry)    EntryGetValue(entry) = NullValue
122 #endif /* EntrySetEmpty */
123 #ifndef EntrySetDeleted
124 #define EntrySetDeleted(entry)  EntryGetValue(entry) = DeletedValue
125 #endif /* EntrySetDeleted */
126 #ifndef EntryIsEmpty
127 #define EntryIsEmpty(entry)     (EntryGetValue(entry) == NullValue)
128 #endif /* EntryIsEmpty */
129 #ifndef EntryIsDeleted
130 #define EntryIsDeleted(entry)   (EntryGetValue(entry) == DeletedValue)
131 #endif /* EntryIsDeleted */
132 #ifndef SetRangeEmpty
133 #define SetRangeEmpty(ptr,size)                \
134 {                                              \
135         size_t _i;                                 \
136         size_t _size = (size);                     \
137         HashSetEntry *entries = (ptr);             \
138         for(_i = 0; _i < _size; ++_i) {            \
139                 HashSetEntry *entry = & entries[_i];   \
140                 EntrySetEmpty(*entry);                 \
141         }                                          \
142 }
143 #endif /* SetRangeEmpty */
144
145 #ifndef HT_OCCUPANCY_FLT
146 /** how full before we double size */
147 #define HT_OCCUPANCY_FLT  0.5f
148 #endif /* HT_OCCUPANCY_FLT */
149
150 #ifndef HT_EMPTY_FLT
151 /** how empty before we half size */
152 #define HT_EMPTY_FLT      (0.4f * (HT_OCCUPANCY_FLT))
153 #endif /* HT_EMPTY_FLT */
154
155 #ifndef HT_MIN_BUCKETS
156 /** default smallest bucket size */
157 #define HT_MIN_BUCKETS    32
158 #endif /* HT_MIN_BUCKETS */
159
160 #define ILLEGAL_POS       ((size_t)-1)
161
162 /* check that all needed functions are defined */
163 #ifndef hashset_init
164 #error You have to redefine hashset_init
165 #endif
166 #ifndef hashset_init_size
167 #error You have to redefine hashset_init_size
168 #endif
169 #ifndef hashset_destroy
170 #error You have to redefine hashset_destroy
171 #endif
172 #ifndef hashset_insert
173 #error You have to redefine hashset_insert
174 #endif
175 #ifndef hashset_remove
176 #error You have to redefine hashset_remove
177 #endif
178 #ifndef hashset_find
179 #error You have to redefine hashset_find
180 #endif
181 #ifndef hashset_size
182 #error You have to redefine hashset_size
183 #endif
184 #ifndef hashset_iterator_init
185 #error You have to redefine hashset_iterator_init
186 #endif
187 #ifndef hashset_iterator_next
188 #error You have to redefine hashset_iterator_next
189 #endif
190 #ifndef hashset_remove_iterator
191 #error You have to redefine hashset_remove_iterator
192 #endif
193
194 /**
195  * Returns the number of elements in the hashset
196  */
197 size_t hashset_size(const HashSet *self)
198 {
199         return self->num_elements - self->num_deleted;
200 }
201
202 /**
203  * Inserts an element into a hashset without growing the set (you have to make
204  * sure there's enough room for that.
205  * @note also see comments for hashset_insert()
206  * @internal
207  */
208 static INLINE
209 InsertReturnValue insert_nogrow(HashSet *self, KeyType key)
210 {
211         size_t num_probes = 0;
212         size_t num_buckets = self->num_buckets;
213         size_t hashmask = num_buckets - 1;
214         unsigned hash = Hash(self, key);
215         size_t bucknum = hash & hashmask;
216         size_t insert_pos = ILLEGAL_POS;
217
218         assert((num_buckets & (num_buckets - 1)) == 0);
219
220         while(1) {
221                 HashSetEntry *entry = & self->entries[bucknum];
222
223                 if(EntryIsEmpty(*entry)) {
224                         size_t p;
225                         HashSetEntry *nentry;
226
227                         if(insert_pos != ILLEGAL_POS) {
228                                 p = insert_pos;
229                         } else {
230                                 p = bucknum;
231                         }
232
233                         nentry = &self->entries[p];
234                         InitData(self, EntryGetValue(*nentry), key);
235                         EntrySetHash(*nentry, hash);
236                         self->num_elements++;
237                         return GetInsertReturnValue(*nentry, 1);
238                 }
239                 if(EntryIsDeleted(*entry)) {
240                         if(insert_pos == ILLEGAL_POS)
241                                 insert_pos = bucknum;
242                 } else if(EntryGetHash(self, *entry) == hash) {
243                         if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
244                                 // Value already in the set, return it
245                                 return GetInsertReturnValue(*entry, 0);
246                         }
247                 }
248
249                 ++num_probes;
250                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
251                 assert(num_probes < num_buckets);
252         }
253 }
254
255 /**
256  * Inserts an element into a hashset under the assumption that the hashset
257  * contains no deleted entries and the element doesn't exist in the hashset yet.
258  * @internal
259  */
260 static
261 void insert_new(HashSet *self, unsigned hash, ValueType value)
262 {
263         size_t num_probes = 0;
264         size_t num_buckets = self->num_buckets;
265         size_t hashmask = num_buckets - 1;
266         size_t bucknum = hash & hashmask;
267         size_t insert_pos = ILLEGAL_POS;
268
269         assert(value != NullValue);
270
271         while(1) {
272                 HashSetEntry *entry = & self->entries[bucknum];
273
274                 if(EntryIsEmpty(*entry)) {
275                         size_t p;
276                         HashSetEntry *nentry;
277
278                         if(insert_pos != ILLEGAL_POS) {
279                                 p = insert_pos;
280                         } else {
281                                 p = bucknum;
282                         }
283                         nentry = &self->entries[p];
284
285                         EntryGetValue(*nentry) = value;
286                         EntrySetHash(*nentry, hash);
287                         self->num_elements++;
288                         return;
289                 }
290                 assert(!EntryIsDeleted(*entry));
291
292                 ++num_probes;
293                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
294                 assert(num_probes < num_buckets);
295         }
296 }
297
298 /**
299  * calculate shrink and enlarge limits
300  * @internal
301  */
302 static INLINE
303 void reset_thresholds(HashSet *self)
304 {
305         self->enlarge_threshold = (size_t) (self->num_buckets * HT_OCCUPANCY_FLT);
306         self->shrink_threshold = (size_t) (self->num_buckets * HT_EMPTY_FLT);
307         self->consider_shrink = 0;
308 }
309
310 /**
311  * Resize the hashset
312  * @internal
313  */
314 static INLINE
315 void resize(HashSet *self, size_t new_size)
316 {
317         size_t num_buckets = self->num_buckets;
318         size_t i;
319         HashSetEntry *old_entries = self->entries;
320         HashSetEntry *new_entries;
321
322         /* allocate a new array with double size */
323         new_entries = Alloc(new_size);
324         SetRangeEmpty(new_entries, new_size);
325
326         /* use the new array */
327         self->entries = new_entries;
328         self->num_buckets = new_size;
329         self->num_elements = 0;
330         self->num_deleted = 0;
331 #ifndef NDEBUG
332         self->entries_version++;
333 #endif
334         reset_thresholds(self);
335
336         /* reinsert all elements */
337         for(i = 0; i < num_buckets; ++i) {
338                 HashSetEntry *entry = & old_entries[i];
339                 if(EntryIsEmpty(*entry) || EntryIsDeleted(*entry))
340                         continue;
341
342                 insert_new(self, EntryGetHash(self, *entry), EntryGetValue(*entry));
343         }
344
345         /* now we can free the old array */
346         Free(old_entries);
347 }
348
349 /**
350  * grow the hashset if adding 1 more elements would make it too crowded
351  * @internal
352  */
353 static INLINE
354 void maybe_grow(HashSet *self)
355 {
356         size_t resize_to;
357
358         if(LIKELY(self->num_elements + 1 <= self->enlarge_threshold))
359                 return;
360
361         /* double table size */
362         resize_to = self->num_buckets * 2;
363         resize(self, resize_to);
364 }
365
366 /**
367  * shrink the hashset if it is only sparsely filled
368  * @internal
369  */
370 static INLINE
371 void maybe_shrink(HashSet *self)
372 {
373         size_t size;
374         size_t resize_to;
375
376         if(!self->consider_shrink)
377                 return;
378
379         self->consider_shrink = 0;
380         size = hashset_size(self);
381         if(LIKELY(size > self->shrink_threshold))
382                 return;
383
384         resize_to = ceil_po2(size);
385
386         if(resize_to < 4)
387                 resize_to = 4;
388
389         resize(self, resize_to);
390 }
391
392 /**
393  * Insert an element into the hashset. If no element with key key exists yet,
394  * then a new one is created and initialized with the InitData function.
395  * Otherwise the exisiting element is returned (for hashs where key is equal to
396  * value, nothing is returned.)
397  *
398  * @param self   the hashset
399  * @param key    the key that identifies the data
400  * @returns      the existing or newly created data element (or nothing in case of hashs where keys are the while value)
401  */
402 InsertReturnValue hashset_insert(HashSet *self, KeyType key)
403 {
404 #ifndef NDEBUG
405         self->entries_version++;
406 #endif
407
408         maybe_shrink(self);
409         maybe_grow(self);
410         return insert_nogrow(self, key);
411 }
412
413 /**
414  * Searchs for an element with key @p key.
415  *
416  * @param self      the hashset
417  * @param key       the key to search for
418  * @returns         the found value or NullValue if nothing was found
419  */
420 ValueType hashset_find(const HashSet *self, ConstKeyType key)
421 {
422         size_t num_probes = 0;
423         size_t num_buckets = self->num_buckets;
424         size_t hashmask = num_buckets - 1;
425         unsigned hash = Hash(self, key);
426         size_t bucknum = hash & hashmask;
427
428         while(1) {
429                 HashSetEntry *entry = & self->entries[bucknum];
430
431                 if(EntryIsEmpty(*entry)) {
432                         return NullValue;
433                 }
434                 if(EntryIsDeleted(*entry)) {
435                         // value is deleted
436                 } else if(EntryGetHash(self, *entry) == hash) {
437                         if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
438                                 // found the value
439                                 return EntryGetValue(*entry);
440                         }
441                 }
442
443                 ++num_probes;
444                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
445                 assert(num_probes < num_buckets);
446         }
447 }
448
449 /**
450  * Removes an element from a hashset. Does nothing if the set doesn't contain
451  * the element.
452  *
453  * @param self    the hashset
454  * @param key     key that identifies the data to remove
455  */
456 void hashset_remove(HashSet *self, ConstKeyType key)
457 {
458         size_t num_probes = 0;
459         size_t num_buckets = self->num_buckets;
460         size_t hashmask = num_buckets - 1;
461         unsigned hash = Hash(self, key);
462         size_t bucknum = hash & hashmask;
463
464 #ifndef NDEBUG
465         self->entries_version++;
466 #endif
467
468         while(1) {
469                 HashSetEntry *entry = & self->entries[bucknum];
470
471                 if(EntryIsEmpty(*entry)) {
472                         return;
473                 }
474                 if(EntryIsDeleted(*entry)) {
475                         // entry is deleted
476                 } else if(EntryGetHash(self, *entry) == hash) {
477                         if(KeysEqual(self, GetKey(EntryGetValue(*entry)), key)) {
478                                 EntrySetDeleted(*entry);
479                                 self->num_deleted++;
480                                 self->consider_shrink = 1;
481                                 return;
482                         }
483                 }
484
485                 ++num_probes;
486                 bucknum = (bucknum + JUMP(num_probes)) & hashmask;
487                 assert(num_probes < num_buckets);
488         }
489 }
490
491 /**
492  * Initializes hashset with a specific size
493  * @internal
494  */
495 static INLINE
496 void init_size(HashSet *self, size_t initial_size)
497 {
498         if(initial_size < 4)
499                 initial_size = 4;
500
501         self->entries = Alloc(initial_size);
502         SetRangeEmpty(self->entries, initial_size);
503         self->num_buckets = initial_size;
504         self->consider_shrink = 0;
505         self->num_elements = 0;
506         self->num_deleted = 0;
507 #ifndef NDEBUG
508         self->entries_version = 0;
509 #endif
510
511         reset_thresholds(self);
512 }
513
514 /**
515  * Initialializes a hashset with the default size. The memory for the set has to
516  * already allocated.
517  */
518 void hashset_init(HashSet *self)
519 {
520         init_size(self, HT_MIN_BUCKETS);
521 }
522
523 /**
524  * Destroys a hashset, freeing all used memory (except the memory for the
525  * HashSet struct itself).
526  */
527 void hashset_destroy(HashSet *self)
528 {
529         Free(self->entries);
530 #ifndef NDEBUG
531         self->entries = NULL;
532 #endif
533 }
534
535 /**
536  * Initializes a hashset expecting expected_element size
537  */
538 void hashset_init_size(HashSet *self, size_t expected_elements)
539 {
540         size_t needed_size;
541         size_t po2size;
542
543         if(expected_elements >= UINT_MAX/2) {
544                 abort();
545         }
546
547         needed_size = expected_elements * (int)(1.0 / HT_OCCUPANCY_FLT);
548         po2size = ceil_po2(needed_size);
549         init_size(self, po2size);
550 }
551
552 /**
553  * Initializes a hashset iterator. The memory for the allocator has to be
554  * already allocated.
555  * @note it is not allowed to remove or insert elements while iterating
556  */
557 void hashset_iterator_init(HashSetIterator *self, const HashSet *hashset)
558 {
559         self->current_bucket = hashset->entries - 1;
560         self->end = hashset->entries + hashset->num_buckets;
561 #ifndef NDEBUG
562         self->set = hashset;
563         self->entries_version = hashset->entries_version;
564 #endif
565 }
566
567 /**
568  * Returns the next value in the iterator or NULL if no value is left
569  * in the hashset.
570  * @note it is not allowed to remove or insert elements while iterating
571  */
572 ValueType hashset_iterator_next(HashSetIterator *self)
573 {
574         HashSetEntry *current_bucket = self->current_bucket;
575         HashSetEntry *end = self->end;
576
577         if(current_bucket >= end)
578                 return NullValue;
579
580         /* using hashset_insert or hashset_remove is not allowed while iterating */
581         assert(self->entries_version == self->set->entries_version);
582
583         do {
584                 current_bucket++;
585         } while(current_bucket < end &&
586                         (EntryIsEmpty(*current_bucket) || EntryIsDeleted(*current_bucket)));
587
588         if(current_bucket >= end)
589                 return NullValue;
590
591         self->current_bucket = current_bucket;
592         return EntryGetValue(*current_bucket);
593 }
594
595 /**
596  * Removes the element the iterator points to. Removing an element a second time
597  * has no result.
598  */
599 void hashset_remove_iterator(HashSet *self, const HashSetIterator *iter)
600 {
601         HashSetEntry *entry = iter->current_bucket;
602
603         /* iterator_next needs to have been called at least once */
604         assert(entry >= self->entries);
605         /* needs to be on a valid element */
606         assert(entry < self->entries + self->num_buckets);
607
608         if(EntryIsDeleted(*entry))
609                 return;
610
611         EntrySetDeleted(*entry);
612         self->num_deleted++;
613         self->consider_shrink = 1;
614 }
615
616 #endif