[sgen] Generational mono g hashtable
[mono.git] / mono / metadata / mono-hash.c
1 /*
2  * ghashtable.c: Hashtable implementation
3  *
4  * Author:
5  *   Miguel de Icaza (miguel@novell.com)
6  *
7  * (C) 2006 Novell, Inc.
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining
10  * a copy of this software and associated documentation files (the
11  * "Software"), to deal in the Software without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27  */
28 #include <config.h>
29 #include <stdio.h>
30 #include <math.h>
31 #include <glib.h>
32 #include "mono-hash.h"
33 #include "metadata/gc-internals.h"
34 #include <mono/utils/checked-build.h>
35 #include <mono/utils/mono-threads-coop.h>
36
37 #ifdef HAVE_BOEHM_GC
38 #define mg_new0(type,n)  ((type *) GC_MALLOC(sizeof(type) * (n)))
39 #define mg_new(type,n)   ((type *) GC_MALLOC(sizeof(type) * (n)))
40 #define mg_free(x)       do { } while (0)
41 #else
42 #define mg_new0(x,n)     g_new0(x,n)
43 #define mg_new(type,n)   g_new(type,n)
44 #define mg_free(x)       g_free(x)
45 #endif
46
47 struct _MonoGHashTable {
48         GHashFunc      hash_func;
49         GEqualFunc     key_equal_func;
50
51         MonoObject **keys;
52         MonoObject **values;
53         int   table_size;
54         int   in_use;
55         GDestroyNotify value_destroy_func, key_destroy_func;
56         MonoGHashGCType gc_type;
57         MonoGCRootSource source;
58         const char *msg;
59 };
60
61 #if UNUSED
62 static gboolean
63 test_prime (int x)
64 {
65         if ((x & 1) != 0) {
66                 int n;
67                 for (n = 3; n< (int)sqrt (x); n += 2) {
68                         if ((x % n) == 0)
69                                 return FALSE;
70                 }
71                 return TRUE;
72         }
73         // There is only one even prime - 2.
74         return (x == 2);
75 }
76
77 static int
78 calc_prime (int x)
79 {
80         int i;
81
82         for (i = (x & (~1))-1; i< G_MAXINT32; i += 2) {
83                 if (test_prime (i))
84                         return i;
85         }
86         return x;
87 }
88 #endif
89
90 #define HASH_TABLE_MAX_LOAD_FACTOR 0.7f
91 /* We didn't really do compaction before, keep it lenient for now */
92 #define HASH_TABLE_MIN_LOAD_FACTOR 0.05f
93 /* We triple the table size at rehash time, similar with previous implementation */
94 #define HASH_TABLE_RESIZE_RATIO 3
95
96 static inline void mono_g_hash_table_key_store (MonoGHashTable *hash, int slot, MonoObject* key)
97 {
98         MonoObject **key_addr = &hash->keys [slot];
99         if (hash->gc_type & MONO_HASH_KEY_GC)
100                 mono_gc_wbarrier_generic_store (key_addr, key);
101         else
102                 *key_addr = key;
103 }
104
105 static inline void mono_g_hash_table_value_store (MonoGHashTable *hash, int slot, MonoObject* value)
106 {
107         MonoObject **value_addr = &hash->values [slot];
108         if (hash->gc_type & MONO_HASH_VALUE_GC)
109                 mono_gc_wbarrier_generic_store (value_addr, value);
110         else
111                 *value_addr = value;
112 }
113
114 /* Returns position of key or of an empty slot for it */
115 static inline int mono_g_hash_table_find_slot (MonoGHashTable *hash, const MonoObject *key)
116 {
117         guint i = ((*hash->hash_func) (key)) % hash->table_size;
118         GEqualFunc equal = hash->key_equal_func;
119
120         while (hash->keys [i] && !(*equal) (hash->keys [i], key)) {
121                 i++;
122                 if (i == hash->table_size)
123                         i = 0;
124         }
125         return i;
126 }
127
128
129 MonoGHashTable *
130 mono_g_hash_table_new_type (GHashFunc hash_func, GEqualFunc key_equal_func, MonoGHashGCType type, MonoGCRootSource source, const char *msg)
131 {
132         MonoGHashTable *hash;
133
134         if (!hash_func)
135                 hash_func = g_direct_hash;
136         if (!key_equal_func)
137                 key_equal_func = g_direct_equal;
138
139 #ifdef HAVE_SGEN_GC
140         hash = mg_new0 (MonoGHashTable, 1);
141 #else
142         hash = mono_gc_alloc_fixed (sizeof (MonoGHashTable), MONO_GC_ROOT_DESCR_FOR_FIXED (sizeof (MonoGHashTable)), source, msg);
143 #endif
144
145         hash->hash_func = hash_func;
146         hash->key_equal_func = key_equal_func;
147
148         hash->table_size = g_spaced_primes_closest (1);
149         hash->keys = mg_new0 (MonoObject*, hash->table_size);
150         hash->values = mg_new0 (MonoObject*, hash->table_size);
151
152         hash->gc_type = type;
153         hash->source = source;
154         hash->msg = msg;
155
156         if (type > MONO_HASH_KEY_VALUE_GC)
157                 g_error ("wrong type for gc hashtable");
158
159 #ifdef HAVE_SGEN_GC
160         if (hash->gc_type & MONO_HASH_KEY_GC)
161                 mono_gc_register_root_wbarrier ((char*)hash->keys, sizeof (MonoObject*) * hash->table_size, mono_gc_make_vector_descr (), hash->source, hash->msg);
162         if (hash->gc_type & MONO_HASH_VALUE_GC)
163                 mono_gc_register_root_wbarrier ((char*)hash->values, sizeof (MonoObject*) * hash->table_size, mono_gc_make_vector_descr (), hash->source, hash->msg);
164 #endif
165
166         return hash;
167 }
168
169 typedef struct {
170         MonoGHashTable *hash;
171         int new_size;
172         MonoObject **keys;
173         MonoObject **values;
174 } RehashData;
175
176 static void*
177 do_rehash (void *_data)
178 {
179         RehashData *data = (RehashData *)_data;
180         MonoGHashTable *hash = data->hash;
181         int current_size, i;
182         MonoObject **old_keys;
183         MonoObject **old_values;
184
185         current_size = hash->table_size;
186         hash->table_size = data->new_size;
187         old_keys = hash->keys;
188         old_values = hash->values;
189         hash->keys = data->keys;
190         hash->values = data->values;
191
192         for (i = 0; i < current_size; i++) {
193                 if (old_keys [i]) {
194                         int slot = mono_g_hash_table_find_slot (hash, old_keys [i]);
195                         mono_g_hash_table_key_store (hash, slot, old_keys [i]);
196                         mono_g_hash_table_value_store (hash, slot, old_values [i]);
197                 }
198         }
199         return NULL;
200 }
201
202 static void
203 rehash (MonoGHashTable *hash)
204 {
205         MONO_REQ_GC_UNSAFE_MODE; //we must run in unsafe mode to make rehash safe
206
207         RehashData data;
208         void *old_keys G_GNUC_UNUSED = hash->keys; /* unused on Boehm */
209         void *old_values G_GNUC_UNUSED = hash->values; /* unused on Boehm */
210
211         data.hash = hash;
212         /*
213          * Rehash to a size that can fit the current elements. Rehash relative to in_use
214          * to allow also for compaction.
215          */
216         data.new_size = g_spaced_primes_closest (hash->in_use / HASH_TABLE_MAX_LOAD_FACTOR * HASH_TABLE_RESIZE_RATIO);
217         data.keys = mg_new0 (MonoObject*, data.new_size);
218         data.values = mg_new0 (MonoObject*, data.new_size);
219
220 #ifdef HAVE_SGEN_GC
221         if (hash->gc_type & MONO_HASH_KEY_GC)
222                 mono_gc_register_root_wbarrier ((char*)data.keys, sizeof (MonoObject*) * data.new_size, mono_gc_make_vector_descr (), hash->source, hash->msg);
223         if (hash->gc_type & MONO_HASH_VALUE_GC)
224                 mono_gc_register_root_wbarrier ((char*)data.values, sizeof (MonoObject*) * data.new_size, mono_gc_make_vector_descr (), hash->source, hash->msg);
225 #endif
226
227         if (!mono_threads_is_coop_enabled ()) {
228                 mono_gc_invoke_with_gc_lock (do_rehash, &data);
229         } else {
230                 /* We cannot be preempted */
231                 do_rehash (&data);
232         }
233
234 #ifdef HAVE_SGEN_GC
235         if (hash->gc_type & MONO_HASH_KEY_GC)
236                 mono_gc_deregister_root ((char*)old_keys);
237         if (hash->gc_type & MONO_HASH_VALUE_GC)
238                 mono_gc_deregister_root ((char*)old_values);
239 #endif
240         mg_free (old_keys);
241         mg_free (old_values);
242 }
243
244 guint
245 mono_g_hash_table_size (MonoGHashTable *hash)
246 {
247         g_return_val_if_fail (hash != NULL, 0);
248
249         return hash->in_use;
250 }
251
252 gpointer
253 mono_g_hash_table_lookup (MonoGHashTable *hash, gconstpointer key)
254 {
255         gpointer orig_key, value;
256
257         if (mono_g_hash_table_lookup_extended (hash, key, &orig_key, &value))
258                 return value;
259         else
260                 return NULL;
261 }
262
263 gboolean
264 mono_g_hash_table_lookup_extended (MonoGHashTable *hash, gconstpointer key, gpointer *orig_key, gpointer *value)
265 {
266         int slot;
267
268         g_return_val_if_fail (hash != NULL, FALSE);
269
270         slot = mono_g_hash_table_find_slot (hash, key);
271
272         if (hash->keys [slot]) {
273                 *orig_key = hash->keys [slot];
274                 *value = hash->values [slot];
275                 return TRUE;
276         }
277
278         return FALSE;
279 }
280
281 void
282 mono_g_hash_table_foreach (MonoGHashTable *hash, GHFunc func, gpointer user_data)
283 {
284         int i;
285
286         g_return_if_fail (hash != NULL);
287         g_return_if_fail (func != NULL);
288
289         for (i = 0; i < hash->table_size; i++) {
290                 if (hash->keys [i])
291                         (*func)(hash->keys [i], hash->values [i], user_data);
292         }
293 }
294
295 gpointer
296 mono_g_hash_table_find (MonoGHashTable *hash, GHRFunc predicate, gpointer user_data)
297 {
298         int i;
299
300         g_return_val_if_fail (hash != NULL, NULL);
301         g_return_val_if_fail (predicate != NULL, NULL);
302
303         for (i = 0; i < hash->table_size; i++) {
304                 if (hash->keys [i] && (*predicate)(hash->keys [i], hash->values [i], user_data))
305                         return hash->values [i];
306         }
307         return NULL;
308 }
309
310 gboolean
311 mono_g_hash_table_remove (MonoGHashTable *hash, gconstpointer key)
312 {
313         int slot, last_clear_slot;
314
315         g_return_val_if_fail (hash != NULL, FALSE);
316         slot = mono_g_hash_table_find_slot (hash, key);
317
318         if (!hash->keys [slot])
319                 return FALSE;
320
321         if (hash->key_destroy_func)
322                 (*hash->key_destroy_func)(hash->keys [slot]);
323         hash->keys [slot] = NULL;
324         if (hash->value_destroy_func)
325                 (*hash->value_destroy_func)(hash->values [slot]);
326         hash->values [slot] = NULL;
327         hash->in_use--;
328
329         /*
330          * When we insert in the hashtable, if the required position is occupied we
331          * consecutively try out following positions. In order to be able to find
332          * if a key exists or not in the array (without traversing the entire hash)
333          * we maintain the constraint that there can be no free slots between two
334          * entries that are hashed to the same position. This means that, at search
335          * time, when we encounter a free slot we can stop looking for collissions.
336          * Similarly, at remove time, we need to shift all following slots to their
337          * normal slot, until we reach an empty slot.
338          */
339         last_clear_slot = slot;
340         slot = (slot + 1) % hash->table_size;
341         while (hash->keys [slot]) {
342                 guint hashcode = ((*hash->hash_func)(hash->keys [slot])) % hash->table_size;
343                 /*
344                  * We try to move the current element to last_clear_slot, but only if
345                  * it brings it closer to its normal position (hashcode)
346                  */
347                 if ((last_clear_slot < slot && (hashcode > slot || hashcode <= last_clear_slot)) ||
348                                 (last_clear_slot > slot && (hashcode > slot && hashcode <= last_clear_slot))) {
349                         mono_g_hash_table_key_store (hash, last_clear_slot, hash->keys [slot]);
350                         mono_g_hash_table_value_store (hash, last_clear_slot, hash->values [slot]);
351                         hash->keys [slot] = NULL;
352                         hash->values [slot] = NULL;
353                         last_clear_slot = slot;
354                 }
355                 slot++;
356                 if (slot == hash->table_size)
357                         slot = 0;
358         }
359         return TRUE;
360 }
361
362 guint
363 mono_g_hash_table_foreach_remove (MonoGHashTable *hash, GHRFunc func, gpointer user_data)
364 {
365         int i;
366         int count = 0;
367
368         g_return_val_if_fail (hash != NULL, 0);
369         g_return_val_if_fail (func != NULL, 0);
370
371         for (i = 0; i < hash->table_size; i++) {
372                 if (hash->keys [i] && (*func)(hash->keys [i], hash->values [i], user_data)) {
373                         mono_g_hash_table_remove (hash, hash->keys [i]);
374                         count++;
375                         /* Retry current slot in case the removal shifted elements */
376                         i--;
377                 }
378         }
379         if (hash->in_use < hash->table_size * HASH_TABLE_MIN_LOAD_FACTOR)
380                 rehash (hash);
381         return count;
382 }
383
384 void
385 mono_g_hash_table_destroy (MonoGHashTable *hash)
386 {
387         int i;
388
389         g_return_if_fail (hash != NULL);
390
391 #ifdef HAVE_SGEN_GC
392         if (hash->gc_type & MONO_HASH_KEY_GC)
393                 mono_gc_deregister_root ((char*)hash->keys);
394         if (hash->gc_type & MONO_HASH_VALUE_GC)
395                 mono_gc_deregister_root ((char*)hash->values);
396 #endif
397
398         for (i = 0; i < hash->table_size; i++) {
399                 if (hash->keys [i]) {
400                         if (hash->key_destroy_func)
401                                 (*hash->key_destroy_func)(hash->keys [i]);
402                         if (hash->value_destroy_func)
403                                 (*hash->value_destroy_func)(hash->values [i]);
404                 }
405         }
406         mg_free (hash->keys);
407         mg_free (hash->values);
408 #ifdef HAVE_SGEN_GC
409         mg_free (hash);
410 #else
411         mono_gc_free_fixed (hash);
412 #endif
413 }
414
415 static void
416 mono_g_hash_table_insert_replace (MonoGHashTable *hash, gpointer key, gpointer value, gboolean replace)
417 {
418         int slot;
419         g_return_if_fail (hash != NULL);
420
421         if (hash->in_use > (hash->table_size * HASH_TABLE_MAX_LOAD_FACTOR))
422                 rehash (hash);
423
424         slot = mono_g_hash_table_find_slot (hash, key);
425
426         if (hash->keys [slot]) {
427                 if (replace) {
428                         if (hash->key_destroy_func)
429                                 (*hash->key_destroy_func)(hash->keys [slot]);
430                         mono_g_hash_table_key_store (hash, slot, (MonoObject*)key);
431                 }
432                 if (hash->value_destroy_func)
433                         (*hash->value_destroy_func) (hash->values [slot]);
434                 mono_g_hash_table_value_store (hash, slot, (MonoObject*)value);
435         } else {
436                 mono_g_hash_table_key_store (hash, slot, (MonoObject*)key);
437                 mono_g_hash_table_value_store (hash, slot, (MonoObject*)value);
438                 hash->in_use++;
439         }
440 }
441
442 void
443 mono_g_hash_table_insert (MonoGHashTable *h, gpointer k, gpointer v)
444 {
445         mono_g_hash_table_insert_replace (h, k, v, FALSE);
446 }
447
448 void
449 mono_g_hash_table_replace(MonoGHashTable *h, gpointer k, gpointer v)
450 {
451         mono_g_hash_table_insert_replace (h, k, v, TRUE);
452 }
453
454 void
455 mono_g_hash_table_print_stats (MonoGHashTable *hash)
456 {
457         int i = 0, chain_size = 0, max_chain_size = 0;
458         gboolean wrapped_around = FALSE;
459
460         while (TRUE) {
461                 if (hash->keys [i]) {
462                         chain_size++;
463                 } else {
464                         max_chain_size = MAX(max_chain_size, chain_size);
465                         chain_size = 0;
466                         if (wrapped_around)
467                                 break;
468                 }
469
470                 if (i == (hash->table_size - 1)) {
471                         wrapped_around = TRUE;
472                         i = 0;
473                 } else {
474                         i++;
475                 }
476         }
477         /* Rehash to a size that can fit the current elements */
478         printf ("Size: %d Table Size: %d Max Chain Length: %d\n", hash->in_use, hash->table_size, max_chain_size);
479 }