more on array sets
[libfirm] / include / libfirm / adt / array.h
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     Dynamic and flexible arrays for C.
23  * @author    Markus Armbruster, Michael Beck, Matthias Braun, Sebastian Hack
24  * @version   $Id$
25  */
26 #ifndef FIRM_ADT_ARRAY_H
27 #define FIRM_ADT_ARRAY_H
28
29 #include <assert.h>
30 #include <stddef.h>
31
32 #include "firm_config.h"
33 #include "obst.h"
34 #include "fourcc.h"
35 #include "align.h"
36 #include "xmalloc.h"
37
38 #define ARR_D_MAGIC     FOURCC('A','R','R','D')
39 #define ARR_A_MAGIC     FOURCC('A','R','R','A')
40 #define ARR_F_MAGIC     FOURCC('A','R','R','F')
41
42 /**
43  * Creates a flexible array.
44  *
45  * @param type     The element type of the new array.
46  * @param nelts    a size_t expression evaluating to the number of elements
47  *
48  * This macro creates a flexible array of a given type at runtime.
49  * The size of the array can be changed later.
50  *
51  * @return A pointer to the flexible array (can be used as a pointer to the
52  *         first element of this array).
53  */
54 #define NEW_ARR_F(type, nelts)                                          \
55   ((type *)_new_arr_f ((nelts), sizeof(type) * (nelts)))
56
57 /**
58  * Creates a new flexible array with the same number of elements as a
59  * given one.
60  *
61  * @param type     The element type of the new array.
62  * @param arr      An array from which the number of elements will be taken
63  *
64  * This macro creates a flexible array of a given type at runtime.
65  * The size of the array can be changed later.
66  *
67  * @return A pointer to the flexible array (can be used as a pointer to the
68  *         first element of this array).
69  */
70 #define CLONE_ARR_F(type, arr)                  \
71   NEW_ARR_F (type, ARR_LEN ((arr)))
72
73 /**
74  * Duplicates an array and returns the new flexible one.
75  *
76  * @param type     The element type of the new array.
77  * @param arr      An array from which the elements will be duplicated
78  *
79  * This macro creates a flexible array of a given type at runtime.
80  * The size of the array can be changed later.
81  *
82  * @return A pointer to the flexible array (can be used as a pointer to the
83  *         first element of this array).
84  */
85 #define DUP_ARR_F(type, arr)                                                    \
86   memcpy (CLONE_ARR_F (type, (arr)), (arr), sizeof(type) * ARR_LEN((arr)))
87
88 /**
89  * Delete a flexible array.
90  *
91  * @param arr    The flexible array.
92  */
93 #define DEL_ARR_F(arr) (_del_arr_f ((arr)))
94
95 /**
96  * Creates a dynamic array on an obstack.
97  *
98  * @param type     The element type of the new array.
99  * @param obstack  A struct obstack * were the data will be allocated
100  * @param nelts    A size_t expression evaluating to the number of elements
101  *
102  * This macro creates a dynamic array of a given type at runtime.
103  * The size of the array cannot be changed later.
104  *
105  * @return A pointer to the dynamic array (can be used as a pointer to the
106  *         first element of this array).
107  */
108 #define NEW_ARR_D(type, obstack, nelts)                                 \
109   (  nelts                                                              \
110    ? (type *)_new_arr_d ((obstack), (nelts), sizeof(type) * (nelts))    \
111    : (type *)arr_mt_descr.v.elts)
112
113 /**
114  * Creates a new dynamic array with the same number of elements as a
115  * given one.
116  *
117  * @param type     The element type of the new array.
118  * @param obstack  An struct obstack * were the data will be allocated
119  * @param arr      An array from which the number of elements will be taken
120  *
121  * This macro creates a dynamic array of a given type at runtime.
122  * The size of the array cannot be changed later.
123  *
124  * @return A pointer to the dynamic array (can be used as a pointer to the
125  *         first element of this array).
126  */
127 #define CLONE_ARR_D(type, obstack, arr)         \
128   NEW_ARR_D (type, (obstack), ARR_LEN ((arr)))
129
130 /**
131  * Duplicates an array and returns the new dynamic one.
132  *
133  * @param type     The element type of the new array.
134  * @param obstack  An struct obstack * were the data will be allocated
135  * @param arr      An array from which the elements will be duplicated
136  *
137  * This macro creates a dynamic array of a given type at runtime.
138  * The size of the array cannot be changed later.
139  *
140  * @return A pointer to the dynamic array (can be used as a pointer to the
141  *         first element of this array).
142  */
143 #define DUP_ARR_D(type, obstack, arr)                                                   \
144   memcpy (CLONE_ARR_D (type, (obstack), (arr)), (arr), sizeof(type) * ARR_LEN ((arr)))
145
146 /**
147  * Create an automatic array which will be deleted at return from function.
148  * Beware, the data will be allocated on the function stack!
149  *
150  * @param type     The element type of the new array.
151  * @param var      A lvalue of type (type *) which will hold the new array.
152  * @param n        number of elements in this array.
153  *
154  * This macro creates a dynamic array on the functions stack of a given type at runtime.
155  * The size of the array cannot be changed later.
156  */
157 #define NEW_ARR_A(type, var, n)                                                                 \
158   do {                                                                                          \
159     int _nelts = (n);                                                                           \
160     assert (_nelts >= 0);                                                                       \
161     (var) = (void *)((_arr_descr *)alloca (_ARR_ELTS_OFFS + sizeof(type) * _nelts))->v.elts;    \
162     _ARR_SET_DBGINF (_ARR_DESCR ((var)), ARR_A_MAGIC, sizeof (type));                           \
163     (void)(_ARR_DESCR ((var))->nelts = _nelts);                                                 \
164   } while (0)
165
166 /**
167  * Creates a new automatic array with the same number of elements as a
168  * given one.
169  *
170  * @param type     The element type of the new array.
171  * @param var      A lvalue of type (type *) which will hold the new array.
172  * @param arr      An array from which the elements will be duplicated
173  *
174  * This macro creates a dynamic array of a given type at runtime.
175  * The size of the array cannot be changed later.
176  *
177  * @return A pointer to the dynamic array (can be used as a pointer to the
178  *         first element of this array).
179  */
180 #define CLONE_ARR_A(type, var, arr)             \
181   NEW_ARR_A (type, (var), ARR_LEN ((arr)))
182
183 /**
184  * Duplicates an array and returns a new automatic one.
185  *
186  * @param type     The element type of the new array.
187  * @param var      A lvalue of type (type *) which will hold the new array.
188  * @param arr      An array from with the number of elements will be taken
189  *
190  * This macro creates a dynamic array of a given type at runtime.
191  * The size of the array cannot be changed later.
192  *
193  * @return A pointer to the dynamic array (can be used as a pointer to the
194  *         first element of this array).
195  */
196 #define DUP_ARR_A(type, var, arr)                                       \
197   do { CLONE_ARR_A(type, (var), (arr));                                 \
198        memcpy ((var), (arr), sizeof (type) * ARR_LEN ((arr))); }        \
199   while (0)
200
201 /**
202  * Declare an initialized (zero'ed) array of fixed size.
203  * This macro should be used at file scope only.
204  *
205  * @param type     The element type of the new array.
206  * @param var      A lvalue of type (type *) which will hold the new array.
207  * @param _nelts   Number of elements in this new array.
208  */
209 #define DECL_ARR_S(type, var, _nelts)                                   \
210   ARR_STRUCT(type, (_nelts) ? (_nelts) : 1) _##var;                     \
211   type *var = (_ARR_SET_DBGINF (&_##var, ARR_A_MAGIC, sizeof (type)),   \
212                _##var.nelts = _nelts,                                   \
213                _##var.v.elts)
214
215 /**
216  * Returns the length of an array
217  *
218  * @param arr  a flexible, dynamic, automatic or static array.
219  */
220 #define ARR_LEN(arr) (ARR_VRFY ((arr)), _ARR_DESCR((arr))->nelts)
221
222 /**
223  * Resize a flexible array, allocate more data if needed but do NOT
224  * reduce.
225  *
226  * @param type     The element type of the array.
227  * @param arr      The array, which must be an lvalue.
228  * @param n        The new size of the array.
229  *
230  * @remark  This macro may change arr, so update all references!
231  */
232 #define ARR_RESIZE(type, arr, n)                                        \
233   ((arr) = _arr_resize ((arr), (n), sizeof(type)))
234
235 /**
236  * Resize a flexible array, always reallocate data.
237  *
238  * @param type     The element type of the array.
239  * @param arr      The array, which must be an lvalue.
240  * @param n        The new size of the array.
241  *
242  * @remark  This macro may change arr, so update all references!
243  */
244 #define ARR_SETLEN(type, arr, n)                                        \
245   ((arr) = _arr_setlen ((arr), (n), sizeof(type) * (n)))
246
247 /** Set a length smaller than the current length of the array.  Do not
248  *  resize. len must be <= ARR_LEN(arr). */
249 #define ARR_SHRINKLEN(arr,len)                                          \
250    (ARR_VRFY ((arr)), assert(_ARR_DESCR((arr))->nelts >= len),             \
251     _ARR_DESCR((arr))->nelts = len)
252
253 /**
254  * Resize a flexible array by growing it by delta elements.
255  *
256  * @param type     The element type of the array.
257  * @param arr      The array, which must be an lvalue.
258  * @param delta    The delta number of elements.
259  *
260  * @remark  This macro may change arr, so update all references!
261  */
262 #define ARR_EXTEND(type, arr, delta)                    \
263   ARR_RESIZE (type, (arr), ARR_LEN ((arr)) + (delta))
264
265 /**
266  * Resize a flexible array to hold n elements only if it is currently shorter
267  * than n.
268  *
269  * @param type     The element type of the array.
270  * @param arr      The array, which must be an lvalue.
271  * @param n        The new size of the array.
272  *
273  * @remark  This macro may change arr, so update all references!
274  */
275 #define ARR_EXTO(type, arr, n)                                          \
276   ((n) >= ARR_LEN ((arr)) ? ARR_RESIZE (type, (arr), (n)+1) : (arr))
277
278 /**
279  * Append one element to a flexible array.
280  *
281  * @param type     The element type of the array.
282  * @param arr      The array, which must be an lvalue.
283  * @param elt      The new element, must be of type (type).
284  */
285 #define ARR_APP1(type, arr, elt)                                        \
286   (ARR_EXTEND (type, (arr), 1), (arr)[ARR_LEN ((arr))-1] = (elt))
287
288 #ifdef NDEBUG
289 # define ARR_VRFY(arr) ((void)0)
290 # define ARR_IDX_VRFY(arr, idx) ((void)0)
291 #else
292 # define ARR_VRFY(arr)                                                                  \
293     assert (   (   (_ARR_DESCR((arr))->magic == ARR_D_MAGIC)                            \
294                 || (_ARR_DESCR((arr))->magic == ARR_A_MAGIC)                            \
295                 || (_ARR_DESCR((arr))->magic == ARR_F_MAGIC))                           \
296             && (   (_ARR_DESCR((arr))->magic != ARR_F_MAGIC)                            \
297                 || (_ARR_DESCR((arr))->u.allocated >= _ARR_DESCR((arr))->nelts))        \
298             && (_ARR_DESCR((arr))->nelts >= 0))
299 # define ARR_IDX_VRFY(arr, idx)                         \
300     assert ((0 <= (idx)) && ((idx) < ARR_LEN ((arr))))
301 #endif
302
303
304 /* Private !!!
305    Don't try this at home, kids, we're trained professionals ;->
306    ... or at the IPD, either. */
307 #ifdef NDEBUG
308 # define _ARR_DBGINF_DECL
309 # define _ARR_SET_DBGINF(descr, co, es)
310 #else
311 # define _ARR_DBGINF_DECL int magic; size_t eltsize;
312 # define _ARR_SET_DBGINF(descr, co, es)                                 \
313     ( (descr)->magic = (co), (descr)->eltsize = (es) )
314 #endif
315
316 /**
317  * Construct an array header.
318  */
319 #define ARR_STRUCT(type, _nelts)                                                \
320   struct {                                                                      \
321     _ARR_DBGINF_DECL                                                            \
322     union {                                                                     \
323       struct obstack *obstack;  /* dynamic: allocated on this obstack */        \
324       int allocated;                    /* flexible: #slots allocated */        \
325     } u;                                                                        \
326     int nelts;                                                                  \
327     union {                                                                     \
328       type elts[(_nelts)];                                                      \
329       aligned_type align[1];                                                    \
330     } v;                                                                        \
331   }
332
333 /**
334  * The array descriptor header type.
335  */
336 typedef ARR_STRUCT (aligned_type, 1) _arr_descr;
337
338 extern _arr_descr arr_mt_descr;
339
340 void *_new_arr_f (int, size_t);
341 void _del_arr_f (void *);
342 void *_new_arr_d (struct obstack *obstack, int nelts, size_t elts_size);
343 void *_arr_resize (void *, int, size_t);
344 void *_arr_setlen (void *, int, size_t);
345
346 #define _ARR_ELTS_OFFS offsetof (_arr_descr, v.elts)
347 #define _ARR_DESCR(elts) ((_arr_descr *)(void *)((char *)(elts) - _ARR_ELTS_OFFS))
348
349 /*
350  ____             _           _      _
351 / ___|  ___  _ __| |_ ___  __| |    / \   _ __ _ __ __ _ _   _ ___
352 \___ \ / _ \| '__| __/ _ \/ _` |   / _ \ | '__| '__/ _` | | | / __|
353  ___) | (_) | |  | ||  __/ (_| |  / ___ \| |  | | | (_| | |_| \__ \
354 |____/ \___/|_|   \__\___|\__,_| /_/   \_\_|  |_|  \__,_|\__, |___/
355                                                          |___/
356 */
357
358 typedef int (_arr_cmp_func_t)(const void *a, const void *b);
359
360 /**
361  * Do a binary search in an array.
362  * @param arr      The array.
363  * @param elm_size The size of an array element.
364  * @param cmp      A comparison function for two array elements (see qsort(3) for example).
365  * @param elm      A pointer to the element we are looking for.
366  * @return         This is somewhat tricky. Let <code>res</code> be the return value.
367  *                 If the return value is negative, then <code>elm</code> was not in the array
368  *                 but <code>-res - 1</code> gives the proper location where it should be inserted.
369  *                 If <code>res >= 0</code> then the element is in the array and <code>res</code>
370  *                 represents its index.
371  *                 That allows for testing membership and finding proper insertion indices.
372  * @note           The differences to bsearch(3) which does not give proper insert locations
373  *                 in the case that the element is not conatined in the array.
374  */
375 static INLINE __attribute__((const, unused)) int
376 _arr_bsearch(const void *arr, size_t elm_size, _arr_cmp_func_t *cmp, const void *elm)
377 {
378         int hi = ARR_LEN(arr);
379         int lo = 0;
380
381         while(lo < hi) {
382                 int md     = lo + ((hi - lo) >> 1);
383                 int res    = cmp((char *) arr + md * elm_size, elm);
384                 if(res < 0)
385                         lo = md + 1;
386                 else if(res > 0)
387                         hi = md;
388                 else
389                         return md;
390         }
391
392         return -(lo + 1);
393 }
394
395 #define ARR_SET_INSERT(arr, cmp, elm) \
396 do { \
397         int idx = _arr_bsearch((arr), sizeof((arr)[0]), (cmp), (elm)); \
398         if (idx < 0) { \
399                 idx = -idx - 1; \
400                 memmove(&(arr)[idx+1], &(arr)[idx], sizeof((arr)[0]) * (_ARR_DESCR((arr))->nelts - idx)); \
401                 (arr)[idx] = *(elm); \
402                 ++_ARR_DESCR((arr))->nelts; \
403         } \
404 } while(0)
405
406 #define ARR_SET_INSERT_EXT(type, arr, cmp, elm) \
407 do { \
408         int idx = _arr_bsearch((arr), sizeof((arr)[0]), (cmp), (elm)); \
409         if (idx < 0) { \
410                 int len = ARR_LEN(arr); \
411                 idx = -idx - 1; \
412                 ARR_EXTO(type, arr, len + 1); \
413                 memmove(&(arr)[idx+1], &(arr)[idx], sizeof((arr)[0]) * (len - idx)); \
414                 (arr)[idx] = *(elm); \
415         } \
416 } while(0)
417
418 #define ARR_SET_REMOVE(arr, cmp, elm) \
419 do { \
420         int idx = _arr_bsearch((arr), sizeof((arr)[0]), (cmp), (elm)); \
421         if (idx >= 0) { \
422                 --_ARR_DESCR((arr))->nelts; \
423                 memmove(&(arr)[idx], &(arr)[idx+1], sizeof((arr)[0]) * (_ARR_DESCR((arr))->nelts - idx)); \
424         } \
425 } while(0)
426
427 /**
428  * Return the index of an element in an array set.
429  * To check for containment, use the expression:
430  *     (ARR_SET_GET_IDX(arr, cmp, elm) >= 0)
431  *
432  * @return The index or some value < 0 if the element was not in the set.
433  */
434 #define ARR_SET_GET_IDX(arr, cmp, elm) \
435         (ARR_VRFY((arr)), _arr_bsearch((arr), sizeof((arr)[0]), cmp, (elm)))
436
437 #ifdef __GNUC__
438 #define ARR_SET_GET(arr, cmp, elm) \
439         ({ int idx = ARR_SET_GET_IDX(arr, cmp, elm); idx >= 0 ? &(arr)[idx] : NULL; })
440 #else
441 #define ARR_SET_GET(arr, cmp, elm) \
442         (ARR_SET_GET_IDX(arr, cmp, elm) >= 0 ? &(arr)[ARR_SET_GET_IDX(arr, cmp, elm)] : NULL)
443 #endif
444
445
446 #define ARR_SET_CONTAINS(arr, cmp, elm) \
447         (ARR_SET_GET_IDX((arr), (cmp), (elm)) >= 0)
448
449 /**
450  * Reset the array set.
451  * This just initializes the size to zero but does not wipe out any element.
452  */
453 #define ARR_SET_CLEAR(arr) ARR_SHRINKLEN(arr, 0)
454
455
456 #endif /* FIRM_ADT_ARRAY_H */