a069e6619b0d2147feb2c7e08ffb35cd18b308eb
[cparser] / ast2firm.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <string.h>
5 #include <stdbool.h>
6
7 #include <libfirm/firm.h>
8 #include <libfirm/adt/obst.h>
9
10 #include "ast2firm.h"
11
12 #include "adt/error.h"
13 #include "adt/array.h"
14 #include "token_t.h"
15 #include "type_t.h"
16 #include "ast_t.h"
17 #include "parser.h"
18 #include "diagnostic.h"
19 #include "lang_features.h"
20 #include "types.h"
21 #include "driver/firm_opt.h"
22 #include "driver/firm_cmdline.h"
23
24 #define MAGIC_DEFAULT_PN_NUMBER     (long) -314159265
25
26 static ir_type *ir_type_const_char;
27 static ir_type *ir_type_wchar_t;
28 static ir_type *ir_type_void;
29 static ir_type *ir_type_int;
30
31 static type_t *type_const_char;
32
33 static int       next_value_number_function;
34 static ir_node  *continue_label;
35 static ir_node  *break_label;
36 static ir_node  *current_switch_cond;
37 static bool      saw_default_label;
38 static ir_node **imature_blocks;
39
40 static const declaration_t *current_function_decl;
41 static ir_node             *current_function_name;
42
43 static struct obstack asm_obst;
44
45 typedef enum declaration_kind_t {
46         DECLARATION_KIND_UNKNOWN,
47         DECLARATION_KIND_FUNCTION,
48         DECLARATION_KIND_GLOBAL_VARIABLE,
49         DECLARATION_KIND_LOCAL_VARIABLE,
50         DECLARATION_KIND_LOCAL_VARIABLE_ENTITY,
51         DECLARATION_KIND_COMPOUND_MEMBER,
52         DECLARATION_KIND_LABEL_BLOCK,
53         DECLARATION_KIND_ENUM_ENTRY
54 } declaration_kind_t;
55
56 static ir_type *get_ir_type(type_t *type);
57 static int count_decls_in_stmts(const statement_t *stmt);
58
59 ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos)
60 {
61         const declaration_t *declaration = get_irg_loc_description(irg, pos);
62
63         warningf(declaration->source_position,
64                  "variable '%#T' might be used uninitialized",
65                  declaration->type, declaration->symbol);
66         return new_r_Unknown(irg, mode);
67 }
68
69 unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg)
70 {
71         const source_position_t *pos = (const source_position_t*) dbg;
72         if(pos == NULL)
73                 return 0;
74         return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name,
75                                    pos->linenr);
76 }
77
78 const char *dbg_retrieve(const dbg_info *dbg, unsigned *line)
79 {
80         const source_position_t *pos = (const source_position_t*) dbg;
81         if(pos == NULL)
82                 return NULL;
83         if(line != NULL)
84                 *line = pos->linenr;
85         return pos->input_name;
86 }
87
88 static dbg_info *get_dbg_info(const source_position_t *pos)
89 {
90         return (dbg_info*) pos;
91 }
92
93 static unsigned unique_id = 0;
94
95 static ident *unique_ident(const char *tag)
96 {
97         char buf[256];
98
99         snprintf(buf, sizeof(buf), "%s.%u", tag, unique_id);
100         unique_id++;
101         return new_id_from_str(buf);
102 }
103
104 /**
105  * Return the signed integer mode of size bytes.
106  *
107  * @param size   the size
108  */
109 static ir_mode *get_smode(unsigned size)
110 {
111         static ir_mode *s_modes[16 + 1] = {0, };
112         ir_mode *res;
113
114         if (size <= 0 || size > 16)
115                 return NULL;
116
117         res = s_modes[size];
118         if (res == NULL) {
119                 unsigned bits;
120         char name[32];
121
122         bits = size * 8;
123         snprintf(name, sizeof(name), "i%u", bits);
124         res = new_ir_mode(name, irms_int_number, bits, 1, irma_twos_complement,
125                                         bits <= machine_size ? machine_size : bits );
126
127                 s_modes[size] = res;
128         }
129         return res;
130 }
131
132 /**
133  * Return the unsigned integer mode of size bytes.
134  *
135  * @param size  the size
136  */
137 static ir_mode *get_umode(unsigned size)
138 {
139         static ir_mode *u_modes[16 + 1] = {0, };
140         ir_mode *res;
141
142         if (size <= 0 || size > 16)
143                 return NULL;
144
145         res = u_modes[size];
146         if (res == NULL) {
147                 unsigned bits;
148                 char name[32];
149
150                 bits = size * 8;
151                 snprintf(name, sizeof(name), "u%u", bits);
152                 res = new_ir_mode(name, irms_int_number, bits, 0, irma_twos_complement,
153                                                 bits <= machine_size ? machine_size : bits );
154
155                 u_modes[size] = res;
156         }
157         return res;
158 }
159
160 /**
161  * Return the pointer mode of size bytes.
162  *
163  * @param size  the size
164  */
165 static ir_mode *get_ptrmode(unsigned size, char *name)
166 {
167         static ir_mode *p_modes[16 + 1] = {0, };
168         ir_mode *res;
169
170         if (size <= 0 || size > 16)
171                 return NULL;
172
173         res = p_modes[size];
174         if (res == NULL) {
175                 unsigned bits;
176                 char buf[32];
177
178                 bits = size * 8;
179                 if (name == NULL) {
180                         snprintf(buf, sizeof(buf), "p%u", bits);
181                         name = buf;
182                 }
183                 res = new_ir_mode(name, irms_reference, bits, 0, irma_twos_complement,
184                                                 bits <= machine_size ? machine_size : bits);
185
186                 p_modes[size] = res;
187
188                 set_reference_mode_signed_eq(res, get_smode(size));
189                 set_reference_mode_unsigned_eq(res, get_umode(size));
190         }
191         return res;
192 }
193
194 static ir_mode *_atomic_modes[ATOMIC_TYPE_LAST];
195
196 static ir_mode *mode_int, *mode_uint;
197
198 /**
199  * Initialises the atomic modes depending on the machine size.
200  */
201 static void init_atomic_modes(void) {
202         unsigned int_size   = machine_size < 32 ? 2 : 4;
203         unsigned long_size  = machine_size < 64 ? 4 : 8;
204         unsigned llong_size = machine_size < 32 ? 4 : 8;
205
206         /* firm has no real void... */
207         _atomic_modes[ATOMIC_TYPE_VOID]        = mode_T;
208         _atomic_modes[ATOMIC_TYPE_CHAR]        = char_is_signed ? get_smode(1) : get_umode(1);
209         _atomic_modes[ATOMIC_TYPE_SCHAR]       = get_smode(1);
210         _atomic_modes[ATOMIC_TYPE_UCHAR]       = get_umode(1);
211         _atomic_modes[ATOMIC_TYPE_SHORT]       = get_smode(2);
212         _atomic_modes[ATOMIC_TYPE_USHORT]      = get_umode(2);
213         _atomic_modes[ATOMIC_TYPE_INT]         = get_smode(int_size);
214         _atomic_modes[ATOMIC_TYPE_UINT]        = get_umode(int_size);
215         _atomic_modes[ATOMIC_TYPE_LONG]        = get_smode(long_size);
216         _atomic_modes[ATOMIC_TYPE_ULONG]       = get_umode(long_size);
217         _atomic_modes[ATOMIC_TYPE_LONGLONG]    = get_smode(llong_size);
218         _atomic_modes[ATOMIC_TYPE_ULONGLONG]   = get_umode(llong_size);
219         _atomic_modes[ATOMIC_TYPE_FLOAT]       = mode_F;
220         _atomic_modes[ATOMIC_TYPE_DOUBLE]      = mode_D;
221         _atomic_modes[ATOMIC_TYPE_LONG_DOUBLE] = mode_E;
222         _atomic_modes[ATOMIC_TYPE_BOOL]        = get_umode(int_size);
223
224 #ifdef PROVIDE_COMPLEX
225         _atomic_modes[ATOMIC_TYPE_BOOL]                  = _atomic_modes[ATOMIC_TYPE_INT];
226         _atomic_modes[ATOMIC_TYPE_FLOAT_IMAGINARY]       = _atomic_modes[ATOMIC_TYPE_FLOAT];
227         _atomic_modes[ATOMIC_TYPE_DOUBLE_IMAGINARY]      = _atomic_modes[ATOMIC_TYPE_DOUBLE];
228         _atomic_modes[ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY] = _atomic_modes[ATOMIC_TYPE_LONG_DOUBLE];
229 #endif
230
231         /* Hmm, pointers should be machine size */
232         set_modeP_data(get_ptrmode(machine_size >> 3, NULL));
233         set_modeP_code(get_ptrmode(machine_size >> 3, NULL));
234
235         mode_int  = _atomic_modes[ATOMIC_TYPE_INT];
236         mode_uint = _atomic_modes[ATOMIC_TYPE_UINT];
237 }
238
239 static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type)
240 {
241         ir_mode *res = NULL;
242         if ((unsigned)atomic_type->akind < (unsigned)ATOMIC_TYPE_LAST)
243                 res = _atomic_modes[(unsigned)atomic_type->akind];
244         if (res == NULL)
245                 panic("Encountered unknown atomic type");
246         return res;
247 }
248
249 static unsigned get_type_size(type_t *type);
250
251 static unsigned get_atomic_type_size(const atomic_type_t *type)
252 {
253         switch(type->akind) {
254         case ATOMIC_TYPE_CHAR:
255         case ATOMIC_TYPE_SCHAR:
256         case ATOMIC_TYPE_UCHAR:
257                 return 1;
258
259         case ATOMIC_TYPE_SHORT:
260         case ATOMIC_TYPE_USHORT:
261                 return 2;
262
263         case ATOMIC_TYPE_BOOL:
264         case ATOMIC_TYPE_INT:
265         case ATOMIC_TYPE_UINT:
266                 return machine_size >> 3;
267
268         case ATOMIC_TYPE_LONG:
269         case ATOMIC_TYPE_ULONG:
270                 return machine_size > 16 ? machine_size >> 3 : 4;
271
272         case ATOMIC_TYPE_LONGLONG:
273         case ATOMIC_TYPE_ULONGLONG:
274                 return machine_size > 16 ? 8 : 4;
275
276         case ATOMIC_TYPE_FLOAT:
277                 return 4;
278
279         case ATOMIC_TYPE_DOUBLE:
280                 return 8;
281
282         case ATOMIC_TYPE_LONG_DOUBLE:
283                 return 12;
284
285         case ATOMIC_TYPE_VOID:
286                 return 1;
287
288         case ATOMIC_TYPE_INVALID:
289         case ATOMIC_TYPE_LAST:
290                 break;
291         }
292         panic("Trying to determine size of invalid atomic type");
293 }
294
295 static unsigned get_compound_type_size(compound_type_t *type)
296 {
297         ir_type *irtype = get_ir_type((type_t*) type);
298         return get_type_size_bytes(irtype);
299 }
300
301 static unsigned get_array_type_size(array_type_t *type)
302 {
303         ir_type *irtype = get_ir_type((type_t*) type);
304         return get_type_size_bytes(irtype);
305 }
306
307
308 static unsigned get_type_size(type_t *type)
309 {
310         type = skip_typeref(type);
311
312         switch(type->kind) {
313         case TYPE_ERROR:
314                 panic("error type occured");
315         case TYPE_ATOMIC:
316                 return get_atomic_type_size(&type->atomic);
317         case TYPE_ENUM:
318                 return get_mode_size_bytes(mode_int);
319         case TYPE_COMPOUND_UNION:
320         case TYPE_COMPOUND_STRUCT:
321                 return get_compound_type_size(&type->compound);
322         case TYPE_FUNCTION:
323                 /* just a pointer to the function */
324                 return get_mode_size_bytes(mode_P_code);
325         case TYPE_POINTER:
326                 return get_mode_size_bytes(mode_P_data);
327         case TYPE_ARRAY:
328                 return get_array_type_size(&type->array);
329         case TYPE_BUILTIN:
330                 return get_type_size(type->builtin.real_type);
331         case TYPE_BITFIELD:
332                 panic("type size of bitfield request");
333         case TYPE_TYPEDEF:
334         case TYPE_TYPEOF:
335         case TYPE_INVALID:
336                 break;
337         }
338         panic("Trying to determine size of invalid type");
339 }
340
341 static unsigned count_parameters(const function_type_t *function_type)
342 {
343         unsigned count = 0;
344
345         function_parameter_t *parameter = function_type->parameters;
346         for ( ; parameter != NULL; parameter = parameter->next) {
347                 ++count;
348         }
349
350         return count;
351 }
352
353
354 static ir_type *create_atomic_type(const atomic_type_t *type)
355 {
356         dbg_info *dbgi  = get_dbg_info(&type->type.source_position);
357         ir_mode *mode   = get_atomic_mode(type);
358         ident   *id     = get_mode_ident(mode);
359         ir_type *irtype = new_d_type_primitive(id, mode, dbgi);
360
361         if(type->akind == ATOMIC_TYPE_LONG_DOUBLE
362                         || type->akind == ATOMIC_TYPE_DOUBLE) {
363                 set_type_alignment_bytes(irtype, 4);
364         }
365
366         return irtype;
367 }
368
369 static ir_type *create_method_type(const function_type_t *function_type)
370 {
371         type_t  *return_type  = function_type->return_type;
372
373         ident   *id           = unique_ident("functiontype");
374         int      n_parameters = count_parameters(function_type);
375         int      n_results    = return_type == type_void ? 0 : 1;
376         dbg_info *dbgi        = get_dbg_info(&function_type->type.source_position);
377         ir_type *irtype       = new_d_type_method(id, n_parameters, n_results, dbgi);
378
379         if(return_type != type_void) {
380                 ir_type *restype = get_ir_type(return_type);
381                 set_method_res_type(irtype, 0, restype);
382         }
383
384         function_parameter_t *parameter = function_type->parameters;
385         int                   n         = 0;
386         for( ; parameter != NULL; parameter = parameter->next) {
387                 ir_type *p_irtype = get_ir_type(parameter->type);
388                 set_method_param_type(irtype, n, p_irtype);
389                 ++n;
390         }
391
392         if(function_type->variadic || function_type->unspecified_parameters) {
393                 set_method_variadicity(irtype, variadicity_variadic);
394         }
395
396         return irtype;
397 }
398
399 static ir_type *create_pointer_type(pointer_type_t *type)
400 {
401         type_t  *points_to = type->points_to;
402         ir_type *ir_points_to;
403         /* Avoid endless recursion if the points_to type contains this poiner type
404          * again (might be a struct). We therefore first create a void* pointer
405          * and then set the real points_to type
406          */
407         dbg_info *dbgi   = get_dbg_info(&type->type.source_position);
408         ir_type *ir_type = new_d_type_pointer(unique_ident("pointer"),
409                                             ir_type_void, mode_P_data, dbgi);
410         type->type.firm_type  = ir_type;
411
412         ir_points_to = get_ir_type(points_to);
413         set_pointer_points_to_type(ir_type, ir_points_to);
414
415         return ir_type;
416 }
417
418 static ir_type *create_array_type(array_type_t *type)
419 {
420         type_t  *element_type    = type->element_type;
421         ir_type *ir_element_type = get_ir_type(element_type);
422
423         ident    *id      = unique_ident("array");
424         dbg_info *dbgi    = get_dbg_info(&type->type.source_position);
425         ir_type  *ir_type = new_d_type_array(id, 1, ir_element_type, dbgi);
426
427         const int align = get_type_alignment_bytes(ir_element_type);
428         set_type_alignment_bytes(ir_type, align);
429
430         if(type->size_constant) {
431                 int n_elements = type->size;
432
433                 set_array_bounds_int(ir_type, 0, 0, n_elements);
434
435                 size_t elemsize = get_type_size_bytes(ir_element_type);
436                 if(elemsize % align > 0) {
437                         elemsize += align - (elemsize % align);
438                 }
439                 set_type_size_bytes(ir_type, n_elements * elemsize);
440         } else {
441                 set_array_lower_bound_int(ir_type, 0, 0);
442         }
443         set_type_state(ir_type, layout_fixed);
444
445         return ir_type;
446 }
447
448 /**
449  * Return the signed integer type of size bits.
450  *
451  * @param size   the size
452  */
453 static ir_type *get_signed_int_type_for_bit_size(ir_type *base_tp,
454                                                  unsigned size)
455 {
456         static ir_mode *s_modes[64 + 1] = {NULL, };
457         ir_type *res;
458         ir_mode *mode;
459
460         if (size <= 0 || size > 64)
461                 return NULL;
462
463         mode = s_modes[size];
464         if (mode == NULL) {
465                 char name[32];
466
467                 snprintf(name, sizeof(name), "bf_I%u", size);
468                 mode = new_ir_mode(name, irms_int_number, size, 1, irma_twos_complement,
469                                    size <= 32 ? 32 : size );
470                 s_modes[size] = mode;
471         }
472
473         char name[32];
474         snprintf(name, sizeof(name), "I%u", size);
475         ident *id = new_id_from_str(name);
476         dbg_info *dbgi = get_dbg_info(&builtin_source_position);
477         res = new_d_type_primitive(mangle_u(get_type_ident(base_tp), id), mode, dbgi);
478         set_primitive_base_type(res, base_tp);
479
480         return res;
481 }
482
483 /**
484  * Return the unsigned integer type of size bits.
485  *
486  * @param size   the size
487  */
488 static ir_type *get_unsigned_int_type_for_bit_size(ir_type *base_tp,
489                                                    unsigned size)
490 {
491         static ir_mode *u_modes[64 + 1] = {NULL, };
492         ir_type *res;
493         ir_mode *mode;
494
495         if (size <= 0 || size > 64)
496                 return NULL;
497
498         mode = u_modes[size];
499         if (mode == NULL) {
500                 char name[32];
501
502                 snprintf(name, sizeof(name), "bf_U%u", size);
503                 mode = new_ir_mode(name, irms_int_number, size, 0, irma_twos_complement,
504                                    size <= 32 ? 32 : size );
505                 u_modes[size] = mode;
506         }
507
508         char name[32];
509
510         snprintf(name, sizeof(name), "U%u", size);
511         ident *id = new_id_from_str(name);
512         dbg_info *dbgi = get_dbg_info(&builtin_source_position);
513         res = new_d_type_primitive(mangle_u(get_type_ident(base_tp), id), mode, dbgi);
514         set_primitive_base_type(res, base_tp);
515
516         return res;
517 }
518
519 static ir_type *create_bitfield_type(bitfield_type_t *const type)
520 {
521         type_t *base = skip_typeref(type->base);
522         assert(base->kind == TYPE_ATOMIC);
523         ir_type *irbase = get_ir_type(base);
524
525         unsigned size = fold_constant(type->size);
526
527         assert(!is_type_float(base));
528         if(is_type_signed(base)) {
529                 return get_signed_int_type_for_bit_size(irbase, size);
530         } else {
531                 return get_unsigned_int_type_for_bit_size(irbase, size);
532         }
533 }
534
535 #define INVALID_TYPE ((ir_type_ptr)-1)
536
537 static ir_type *create_union_type(compound_type_t *type, ir_type *irtype,
538                                   size_t *outer_offset, size_t *outer_align);
539
540 static ir_type *create_struct_type(compound_type_t *type, ir_type *irtype,
541                                    size_t *outer_offset, size_t *outer_align)
542 {
543         declaration_t *declaration = type->declaration;
544         if(declaration->v.irtype != NULL) {
545                 return declaration->v.irtype;
546         }
547
548         size_t align_all  = 1;
549         size_t offset     = 0;
550         size_t bit_offset = 0;
551         if(irtype == NULL) {
552                 symbol_t *symbol = declaration->symbol;
553                 ident    *id;
554                 if(symbol != NULL) {
555                         id = unique_ident(symbol->string);
556                 } else {
557                         id = unique_ident("__anonymous_struct");
558                 }
559                 dbg_info *dbgi  = get_dbg_info(&type->type.source_position);
560
561                 irtype = new_d_type_struct(id, dbgi);
562
563                 declaration->v.irtype = irtype;
564                 type->type.firm_type  = irtype;
565         } else {
566                 offset    = *outer_offset;
567                 align_all = *outer_align;
568         }
569
570         declaration_t *entry = declaration->scope.declarations;
571         for( ; entry != NULL; entry = entry->next) {
572                 if(entry->namespc != NAMESPACE_NORMAL)
573                         continue;
574
575                 symbol_t *symbol     = entry->symbol;
576                 type_t   *entry_type = skip_typeref(entry->type);
577                 dbg_info *dbgi       = get_dbg_info(&entry->source_position);
578                 ident    *ident;
579                 if(symbol != NULL) {
580                         ident = new_id_from_str(symbol->string);
581                 } else {
582                         if(entry_type->kind == TYPE_COMPOUND_STRUCT) {
583                                 create_struct_type(&entry_type->compound, irtype, &offset,
584                                                    &align_all);
585                                 continue;
586                         } else if(entry_type->kind == TYPE_COMPOUND_UNION) {
587                                 create_union_type(&entry_type->compound, irtype, &offset,
588                                                   &align_all);
589                                 continue;
590                         } else {
591                                 assert(entry_type->kind == TYPE_BITFIELD);
592                         }
593                         ident = unique_ident("anon");
594                 }
595
596                 ir_type *base_irtype;
597                 if(entry_type->kind == TYPE_BITFIELD) {
598                         base_irtype = get_ir_type(entry_type->bitfield.base);
599                 } else {
600                         base_irtype = get_ir_type(entry_type);
601                 }
602
603                 size_t entry_alignment = get_type_alignment_bytes(base_irtype);
604                 size_t misalign        = offset % entry_alignment;
605
606                 ir_type   *entry_irtype = get_ir_type(entry_type);
607                 ir_entity *entity = new_d_entity(irtype, ident, entry_irtype, dbgi);
608
609                 size_t base;
610                 size_t bits_remainder;
611                 if(entry_type->kind == TYPE_BITFIELD) {
612                         size_t size_bits      = fold_constant(entry_type->bitfield.size);
613                         size_t rest_size_bits = (entry_alignment - misalign)*8 - bit_offset;
614
615                         if(size_bits > rest_size_bits) {
616                                 /* start a new bucket */
617                                 offset     += entry_alignment - misalign;
618                                 bit_offset  = 0;
619
620                                 base           = offset;
621                                 bits_remainder = 0;
622                         } else {
623                                 /* put into current bucket */
624                                 base           = offset - misalign;
625                                 bits_remainder = misalign * 8 + bit_offset;
626                         }
627
628                         offset     += size_bits / 8;
629                         bit_offset  = bit_offset + (size_bits % 8);
630                 } else {
631                         size_t entry_size = get_type_size_bytes(base_irtype);
632                         if(misalign > 0 || bit_offset > 0)
633                                 offset += entry_alignment - misalign;
634
635                         base           = offset;
636                         bits_remainder = 0;
637                         offset        += entry_size;
638                         bit_offset     = 0;
639                 }
640
641                 if(entry_alignment > align_all) {
642                         if(entry_alignment % align_all != 0) {
643                                 panic("uneven alignments not supported yet");
644                         }
645                         align_all = entry_alignment;
646                 }
647
648                 set_entity_offset(entity, base);
649                 set_entity_offset_bits_remainder(entity,
650                                                  (unsigned char) bits_remainder);
651                 //add_struct_member(irtype, entity);
652                 entry->declaration_kind = DECLARATION_KIND_COMPOUND_MEMBER;
653                 assert(entry->v.entity == NULL);
654                 entry->v.entity         = entity;
655         }
656
657         size_t misalign = offset % align_all;
658         if(misalign > 0 || bit_offset > 0) {
659                 offset += align_all - misalign;
660         }
661
662         if(outer_offset != NULL) {
663                 *outer_offset = offset;
664                 *outer_align  = align_all;
665         } else {
666                 set_type_alignment_bytes(irtype, align_all);
667                 set_type_size_bytes(irtype, offset);
668                 set_type_state(irtype, layout_fixed);
669         }
670
671         return irtype;
672 }
673
674 static ir_type *create_union_type(compound_type_t *type, ir_type *irtype,
675                                   size_t *outer_offset, size_t *outer_align)
676 {
677         declaration_t *declaration = type->declaration;
678         if(declaration->v.irtype != NULL) {
679                 return declaration->v.irtype;
680         }
681
682         size_t align_all = 1;
683         size_t offset    = 0;
684         size_t size      = 0;
685
686         if(irtype == NULL) {
687                 symbol_t      *symbol      = declaration->symbol;
688                 ident         *id;
689                 if(symbol != NULL) {
690                         id = unique_ident(symbol->string);
691                 } else {
692                         id = unique_ident("__anonymous_union");
693                 }
694                 dbg_info *dbgi = get_dbg_info(&type->type.source_position);
695
696                 irtype = new_d_type_union(id, dbgi);
697
698                 declaration->v.irtype = irtype;
699                 type->type.firm_type  = irtype;
700         } else {
701                 offset    = *outer_offset;
702                 align_all = *outer_align;
703         }
704
705         type->type.firm_type = irtype;
706
707         declaration_t *entry = declaration->scope.declarations;
708         for( ; entry != NULL; entry = entry->next) {
709                 if(entry->namespc != NAMESPACE_NORMAL)
710                         continue;
711
712                 symbol_t *symbol        = entry->symbol;
713                 type_t   *entry_type    = skip_typeref(entry->type);
714                 ir_type  *entry_ir_type = get_ir_type(entry_type);
715
716                 ident *ident;
717                 if(symbol != NULL) {
718                         ident = new_id_from_str(entry->symbol->string);
719                 } else {
720                         size_t offs = offset;
721                         if(entry_type->kind == TYPE_COMPOUND_STRUCT) {
722                                 create_struct_type(&entry_type->compound, irtype, &offs,
723                                                    &align_all);
724                                 continue;
725                         } else if(entry_type->kind == TYPE_COMPOUND_UNION) {
726                                 create_union_type(&entry_type->compound, irtype, &offs,
727                                                   &align_all);
728                                 continue;
729                         } else {
730                                 panic("anonymous union member must be struct or union");
731                         }
732                         size_t entry_size = offs - offset;
733                         if(entry_size > size) {
734                                 size = entry_size;
735                         }
736                         ident = unique_ident("anon");
737                 }
738
739                 size_t entry_size      = get_type_size_bytes(entry_ir_type);
740                 size_t entry_alignment = get_type_alignment_bytes(entry_ir_type);
741
742                 dbg_info  *const dbgi   = get_dbg_info(&entry->source_position);
743                 ir_entity *const entity = new_d_entity(irtype, ident, entry_ir_type,
744                                                        dbgi);
745                 //add_union_member(irtype, entity);
746                 set_entity_offset(entity, 0);
747                 entry->declaration_kind = DECLARATION_KIND_COMPOUND_MEMBER;
748                 assert(entry->v.entity == NULL);
749                 entry->v.entity         = entity;
750
751                 if(entry_size > size) {
752                         size = entry_size;
753                 }
754                 if(entry_alignment > align_all) {
755                         if(entry_alignment % align_all != 0) {
756                                 panic("Uneven alignments not supported yet");
757                         }
758                         align_all = entry_alignment;
759                 }
760         }
761
762         if(outer_offset != NULL) {
763                 assert(*outer_offset == offset);
764
765                 size_t misalign = offset % align_all;
766                 if (misalign != 0)
767                         size += align_all - misalign;
768                 *outer_offset += size;
769
770                 if(align_all > *outer_align) {
771                         if(align_all % *outer_align != 0) {
772                                 panic("uneven alignments not supported yet");
773                         }
774                         *outer_align = align_all;
775                 }
776         } else {
777                 set_type_alignment_bytes(irtype, align_all);
778                 set_type_size_bytes(irtype, size);
779                 set_type_state(irtype, layout_fixed);
780                 declaration->v.irtype = irtype;
781         }
782
783         return irtype;
784 }
785
786 static ir_node *expression_to_firm(const expression_t *expression);
787 static inline ir_mode *get_ir_mode(type_t *type);
788
789 static ir_type *create_enum_type(enum_type_t *const type)
790 {
791         type->type.firm_type = ir_type_int;
792
793         ir_mode *const mode    = mode_int;
794         tarval  *const one     = get_mode_one(mode);
795         tarval  *      tv_next = get_tarval_null(mode);
796
797         declaration_t *declaration = type->declaration->next;
798         for (; declaration != NULL; declaration = declaration->next) {
799                 if (declaration->storage_class != STORAGE_CLASS_ENUM_ENTRY)
800                         break;
801
802                 declaration->declaration_kind = DECLARATION_KIND_ENUM_ENTRY;
803
804                 expression_t *const init = declaration->init.enum_value;
805                 if (init != NULL) {
806                         ir_node *const cnst = expression_to_firm(init);
807                         if (!is_Const(cnst)) {
808                                 panic("couldn't fold constant");
809                         }
810                         tv_next = get_Const_tarval(cnst);
811                 }
812                 declaration->v.enum_val = tv_next;
813                 tv_next = tarval_add(tv_next, one);
814         }
815
816         return ir_type_int;
817 }
818
819 static ir_type *get_ir_type(type_t *type)
820 {
821         assert(type != NULL);
822
823         type = skip_typeref(type);
824
825         if(type->base.firm_type != NULL) {
826                 assert(type->base.firm_type != INVALID_TYPE);
827                 return type->base.firm_type;
828         }
829
830         ir_type *firm_type = NULL;
831         switch(type->kind) {
832         case TYPE_ERROR:
833                 panic("error type occured");
834         case TYPE_ATOMIC:
835                 firm_type = create_atomic_type(&type->atomic);
836                 break;
837         case TYPE_FUNCTION:
838                 firm_type = create_method_type(&type->function);
839                 break;
840         case TYPE_POINTER:
841                 firm_type = create_pointer_type(&type->pointer);
842                 break;
843         case TYPE_ARRAY:
844                 firm_type = create_array_type(&type->array);
845                 break;
846         case TYPE_COMPOUND_STRUCT:
847                 firm_type = create_struct_type(&type->compound, NULL, NULL, NULL);
848                 break;
849         case TYPE_COMPOUND_UNION:
850                 firm_type = create_union_type(&type->compound, NULL, NULL, NULL);
851                 break;
852         case TYPE_ENUM:
853                 firm_type = create_enum_type(&type->enumt);
854                 break;
855         case TYPE_BUILTIN:
856                 firm_type = get_ir_type(type->builtin.real_type);
857                 break;
858         case TYPE_BITFIELD:
859                 firm_type = create_bitfield_type(&type->bitfield);
860                 break;
861
862         case TYPE_TYPEOF:
863         case TYPE_TYPEDEF:
864         case TYPE_INVALID:
865                 break;
866         }
867         if(firm_type == NULL)
868                 panic("unknown type found");
869
870         type->base.firm_type = firm_type;
871         return firm_type;
872 }
873
874 static inline ir_mode *get_ir_mode(type_t *type)
875 {
876         ir_type *irtype = get_ir_type(type);
877
878         /* firm doesn't report a mode for arrays somehow... */
879         if(is_Array_type(irtype)) {
880                 return mode_P_data;
881         }
882
883         ir_mode *mode = get_type_mode(irtype);
884         assert(mode != NULL);
885         return mode;
886 }
887
888 static ident *predef_idents[rts_max];
889
890 /** Names of the runtime functions. */
891 static const struct {
892         int        id;           /**< the rts id */
893         int        n_res;        /**< number of return values */
894         const char *name;        /**< the name of the rts function */
895         int        n_params;     /**< number of parameters */
896         unsigned   flags;        /**< language flags */
897 } rts_data[] = {
898         { rts_debugbreak, 0, "__debugbreak", 0, _MS },
899         { rts_abort,      0, "abort",        0, _C89 },
900         { rts_abs,        1, "abs",          1, _C89 },
901         { rts_labs,       1, "labs",         1, _C89 },
902         { rts_llabs,      1, "llabs",        1, _C99 },
903         { rts_imaxabs,    1, "imaxabs",      1, _C99 },
904
905         { rts_fabs,       1, "fabs",         1, _C89 },
906         { rts_sqrt,       1, "sqrt",         1, _C89 },
907         { rts_cbrt,       1, "cbrt",         1, _C99 },
908         { rts_exp,        1, "exp",          1, _C89 },
909         { rts_exp2,       1, "exp2",         1, _C89 },
910         { rts_exp10,      1, "exp10",        1, _GNUC },
911         { rts_log,        1, "log",          1, _C89 },
912         { rts_log2,       1, "log2",         1, _C89 },
913         { rts_log10,      1, "log10",        1, _C89 },
914         { rts_pow,        1, "pow",          2, _C89 },
915         { rts_sin,        1, "sin",          1, _C89 },
916         { rts_cos,        1, "cos",          1, _C89 },
917         { rts_tan,        1, "tan",          1, _C89 },
918         { rts_asin,       1, "asin",         1, _C89 },
919         { rts_acos,       1, "acos",         1, _C89 },
920         { rts_atan,       1, "atan",         1, _C89 },
921         { rts_sinh,       1, "sinh",         1, _C89 },
922         { rts_cosh,       1, "cosh",         1, _C89 },
923         { rts_tanh,       1, "tanh",         1, _C89 },
924
925         { rts_fabsf,      1, "fabsf",        1, _C99 },
926         { rts_sqrtf,      1, "sqrtf",        1, _C99 },
927         { rts_cbrtf,      1, "cbrtf",        1, _C99 },
928         { rts_expf,       1, "expf",         1, _C99 },
929         { rts_exp2f,      1, "exp2f",        1, _C99 },
930         { rts_exp10f,     1, "exp10f",       1, _GNUC },
931         { rts_logf,       1, "logf",         1, _C99 },
932         { rts_log2f,      1, "log2f",        1, _C99 },
933         { rts_log10f,     1, "log10f",       1, _C99 },
934         { rts_powf,       1, "powf",         2, _C99 },
935         { rts_sinf,       1, "sinf",         1, _C99 },
936         { rts_cosf,       1, "cosf",         1, _C99 },
937         { rts_tanf,       1, "tanf",         1, _C99 },
938         { rts_asinf,      1, "asinf",        1, _C99 },
939         { rts_acosf,      1, "acosf",        1, _C99 },
940         { rts_atanf,      1, "atanf",        1, _C99 },
941         { rts_sinhf,      1, "sinhf",        1, _C99 },
942         { rts_coshf,      1, "coshf",        1, _C99 },
943         { rts_tanhf,      1, "tanhf",        1, _C99 },
944
945         { rts_fabsl,      1, "fabsl",        1, _C99 },
946         { rts_sqrtl,      1, "sqrtl",        1, _C99 },
947         { rts_cbrtl,      1, "cbrtl",        1, _C99 },
948         { rts_expl,       1, "expl",         1, _C99 },
949         { rts_exp2l,      1, "exp2l",        1, _C99 },
950         { rts_exp10l,     1, "exp10l",       1, _GNUC },
951         { rts_logl,       1, "logl",         1, _C99 },
952         { rts_log2l,      1, "log2l",        1, _C99 },
953         { rts_log10l,     1, "log10l",       1, _C99 },
954         { rts_powl,       1, "powl",         2, _C99 },
955         { rts_sinl,       1, "sinl",         1, _C99 },
956         { rts_cosl,       1, "cosl",         1, _C99 },
957         { rts_tanl,       1, "tanl",         1, _C99 },
958         { rts_asinl,      1, "asinl",        1, _C99 },
959         { rts_acosl,      1, "acosl",        1, _C99 },
960         { rts_atanl,      1, "atanl",        1, _C99 },
961         { rts_sinhl,      1, "sinhl",        1, _C99 },
962         { rts_coshl,      1, "coshl",        1, _C99 },
963         { rts_tanhl,      1, "tanhl",        1, _C99 },
964
965         { rts_memcpy,     1, "memcpy",       3, _C89 },  /* HMM, man say its C99 */
966         { rts_memset,     1, "memset",       3, _C89 },  /* HMM, man say its C99 */
967         { rts_strcmp,     1, "strcmp",       2, _C89 },
968         { rts_strncmp,    1, "strncmp",      3, _C89 }
969 };
970
971 static ir_entity* get_function_entity(declaration_t *declaration)
972 {
973         if(declaration->declaration_kind == DECLARATION_KIND_FUNCTION)
974                 return declaration->v.entity;
975         assert(declaration->declaration_kind == DECLARATION_KIND_UNKNOWN);
976
977         symbol_t *symbol = declaration->symbol;
978         ident    *id     = new_id_from_str(symbol->string);
979
980         ir_type  *global_type    = get_glob_type();
981         ir_type  *ir_type_method = get_ir_type(declaration->type);
982         assert(is_Method_type(ir_type_method));
983
984         dbg_info  *const dbgi   = get_dbg_info(&declaration->source_position);
985         ir_entity *const entity = new_d_entity(global_type, id, ir_type_method, dbgi);
986         set_entity_ld_ident(entity, id);
987         if(declaration->storage_class == STORAGE_CLASS_STATIC
988                         || declaration->is_inline) {
989                 set_entity_visibility(entity, visibility_local);
990         } else if(declaration->init.statement != NULL) {
991                 set_entity_visibility(entity, visibility_external_visible);
992         } else {
993                 set_entity_visibility(entity, visibility_external_allocated);
994
995                 /* We should check for file scope here, but as long as we compile C only
996                    this is not needed. */
997                 int    n_params = get_method_n_params(ir_type_method);
998                 int    n_res    = get_method_n_ress(ir_type_method);
999                 int    i;
1000
1001                 if (n_params == 0 && n_res == 0 && id == predef_idents[rts_abort]) {
1002                         /* found abort(), store for later */
1003                         //abort_ent = ent;
1004                         //abort_tp  = ftype;
1005                 } else {
1006                         if (! firm_opt.freestanding) {
1007                                 /* check for a known runtime function */
1008                                 for (i = 0; i < rts_max; ++i) {
1009                                         /* ignore those rts functions not necessary needed for current mode */
1010                                         if ((c_mode & rts_data[i].flags) == 0)
1011                                                 continue;
1012                                         if (n_params == rts_data[i].n_params && n_res == rts_data[i].n_res &&
1013                                                 id == predef_idents[rts_data[i].id])
1014                                                 rts_entities[rts_data[i].id] = entity;
1015                                 }
1016                         }
1017                 }
1018         }
1019         set_entity_allocation(entity, allocation_static);
1020
1021         declaration->declaration_kind = DECLARATION_KIND_FUNCTION;
1022         declaration->v.entity         = entity;
1023
1024         return entity;
1025 }
1026
1027 static ir_node *const_to_firm(const const_expression_t *cnst)
1028 {
1029         dbg_info *dbgi = get_dbg_info(&cnst->base.source_position);
1030         ir_mode  *mode = get_ir_mode(cnst->base.type);
1031
1032         char    buf[128];
1033         tarval *tv;
1034         size_t  len;
1035         if(mode_is_float(mode)) {
1036                 tv = new_tarval_from_double(cnst->v.float_value, mode);
1037         } else {
1038                 if(mode_is_signed(mode)) {
1039                         len = snprintf(buf, sizeof(buf), "%lld", cnst->v.int_value);
1040                 } else {
1041                         len = snprintf(buf, sizeof(buf), "%llu",
1042                                        (unsigned long long) cnst->v.int_value);
1043                 }
1044                 tv = new_tarval_from_str(buf, len, mode);
1045         }
1046
1047         return new_d_Const(dbgi, mode, tv);
1048 }
1049
1050 static ir_node *char_const_to_firm(const const_expression_t *cnst)
1051 {
1052         dbg_info *dbgi = get_dbg_info(&cnst->base.source_position);
1053         ir_mode  *mode = get_ir_mode(cnst->base.type);
1054
1055         long long int v = 0;
1056         for (size_t i = 0; i < cnst->v.chars.size; ++i) {
1057                 v = (v << 8) | ((unsigned char)cnst->v.chars.begin[i]);
1058         }
1059         char    buf[128];
1060         size_t  len = snprintf(buf, sizeof(buf), "%lld", v);
1061         tarval *tv = new_tarval_from_str(buf, len, mode);
1062
1063         return new_d_Const(dbgi, mode, tv);
1064 }
1065
1066 static ir_node *create_symconst(dbg_info *dbgi, ir_mode *mode,
1067                                 ir_entity *entity)
1068 {
1069         assert(entity != NULL);
1070         union symconst_symbol sym;
1071         sym.entity_p = entity;
1072         return new_d_SymConst(dbgi, mode, sym, symconst_addr_ent);
1073 }
1074
1075 static ir_node *string_to_firm(const source_position_t *const src_pos,
1076                                const char *const id_prefix,
1077                                const string_t *const value)
1078 {
1079         ir_type  *const global_type = get_glob_type();
1080         dbg_info *const dbgi        = get_dbg_info(src_pos);
1081         ir_type  *const type        = new_d_type_array(unique_ident("strtype"), 1,
1082                                                        ir_type_const_char, dbgi);
1083
1084         ident     *const id     = unique_ident(id_prefix);
1085         ir_entity *const entity = new_d_entity(global_type, id, type, dbgi);
1086         set_entity_ld_ident(entity, id);
1087         set_entity_variability(entity, variability_constant);
1088         set_entity_allocation(entity, allocation_static);
1089
1090         ir_type *const elem_type = ir_type_const_char;
1091         ir_mode *const mode      = get_type_mode(elem_type);
1092
1093         const char* const string = value->begin;
1094         const size_t      slen   = value->size;
1095
1096         set_array_lower_bound_int(type, 0, 0);
1097         set_array_upper_bound_int(type, 0, slen);
1098         set_type_size_bytes(type, slen);
1099         set_type_state(type, layout_fixed);
1100
1101         tarval **const tvs = xmalloc(slen * sizeof(tvs[0]));
1102         for(size_t i = 0; i < slen; ++i) {
1103                 tvs[i] = new_tarval_from_long(string[i], mode);
1104         }
1105
1106         set_array_entity_values(entity, tvs, slen);
1107         free(tvs);
1108
1109         return create_symconst(dbgi, mode_P_data, entity);
1110 }
1111
1112 static ir_node *string_literal_to_firm(
1113                 const string_literal_expression_t* literal)
1114 {
1115         return string_to_firm(&literal->base.source_position, "Lstr",
1116                               &literal->value);
1117 }
1118
1119 static ir_node *wide_string_literal_to_firm(
1120         const wide_string_literal_expression_t* const literal)
1121 {
1122         ir_type *const global_type = get_glob_type();
1123         ir_type *const elem_type   = ir_type_wchar_t;
1124         dbg_info *const dbgi       = get_dbg_info(&literal->base.source_position);
1125         ir_type *const type        = new_d_type_array(unique_ident("strtype"), 1,
1126                                                     elem_type, dbgi);
1127
1128         ident     *const id     = unique_ident("Lstr");
1129         ir_entity *const entity = new_d_entity(global_type, id, type, dbgi);
1130         set_entity_ld_ident(entity, id);
1131         set_entity_variability(entity, variability_constant);
1132         set_entity_allocation(entity, allocation_static);
1133
1134         ir_mode *const mode      = get_type_mode(elem_type);
1135
1136         const wchar_rep_t *const string = literal->value.begin;
1137         const size_t             slen   = literal->value.size;
1138
1139         set_array_lower_bound_int(type, 0, 0);
1140         set_array_upper_bound_int(type, 0, slen);
1141         set_type_size_bytes(type, slen);
1142         set_type_state(type, layout_fixed);
1143
1144         tarval **const tvs = xmalloc(slen * sizeof(tvs[0]));
1145         for(size_t i = 0; i < slen; ++i) {
1146                 tvs[i] = new_tarval_from_long(string[i], mode);
1147         }
1148
1149         set_array_entity_values(entity, tvs, slen);
1150         free(tvs);
1151
1152         return create_symconst(dbgi, mode_P_data, entity);
1153 }
1154
1155 static ir_node *deref_address(ir_type *const irtype, ir_node *const addr,
1156                               dbg_info *const dbgi)
1157 {
1158         if (is_compound_type(irtype) ||
1159                         is_Method_type(irtype)   ||
1160                         is_Array_type(irtype)) {
1161                 return addr;
1162         }
1163
1164         ir_mode *const mode     = get_type_mode(irtype);
1165         ir_node *const memory   = get_store();
1166         ir_node *const load     = new_d_Load(dbgi, memory, addr, mode);
1167         ir_node *const load_mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M);
1168         ir_node *const load_res = new_d_Proj(dbgi, load, mode,   pn_Load_res);
1169         set_store(load_mem);
1170         return load_res;
1171 }
1172
1173 static ir_node *do_strict_conv(dbg_info *dbgi, ir_node *node)
1174 {
1175         ir_mode *mode = get_irn_mode(node);
1176
1177         if(!(get_irg_fp_model(current_ir_graph) & fp_explicit_rounding))
1178                 return node;
1179         if(!mode_is_float(mode))
1180                 return node;
1181
1182         /* check if there is already a Conv */
1183         if (get_irn_op(node) == op_Conv) {
1184                 /* convert it into a strict Conv */
1185                 set_Conv_strict(node, 1);
1186                 return node;
1187         }
1188
1189         /* otherwise create a new one */
1190         return new_d_strictConv(dbgi, node, mode);
1191 }
1192
1193 static ir_node *get_global_var_address(dbg_info *const dbgi,
1194                                        const declaration_t *const decl)
1195 {
1196         assert(decl->declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
1197
1198         ir_entity *const entity = decl->v.entity;
1199         switch ((storage_class_tag_t)decl->storage_class) {
1200                 case STORAGE_CLASS_THREAD:
1201                 case STORAGE_CLASS_THREAD_EXTERN:
1202                 case STORAGE_CLASS_THREAD_STATIC: {
1203                         ir_node *const no_mem = new_NoMem();
1204                         ir_node *const tls    = get_irg_tls(current_ir_graph);
1205                         return new_d_simpleSel(dbgi, no_mem, tls, entity);
1206                 }
1207
1208                 default:
1209                         return create_symconst(dbgi, mode_P_data, entity);
1210         }
1211 }
1212
1213 /* Returns the correct base address depending on whether it is a parameter or a
1214  * normal local variable */
1215 static ir_node *get_local_frame(ir_entity *const ent)
1216 {
1217         ir_graph      *const irg   = current_ir_graph;
1218         const ir_type *const owner = get_entity_owner(ent);
1219         if (owner == get_irg_frame_type(irg)) {
1220                 return get_irg_frame(irg);
1221         } else {
1222                 assert(owner == get_method_value_param_type(get_entity_type(get_irg_entity(irg))));
1223                 return get_irg_value_param_base(irg);
1224         }
1225 }
1226
1227 static ir_node *reference_expression_to_firm(const reference_expression_t *ref)
1228 {
1229         dbg_info      *dbgi        = get_dbg_info(&ref->base.source_position);
1230         declaration_t *declaration = ref->declaration;
1231         type_t        *type        = skip_typeref(declaration->type);
1232
1233         switch((declaration_kind_t) declaration->declaration_kind) {
1234         case DECLARATION_KIND_UNKNOWN:
1235                 if (declaration->storage_class != STORAGE_CLASS_ENUM_ENTRY) {
1236                         break;
1237                 }
1238                 get_ir_type(type);
1239                 /* FALLTHROUGH */
1240
1241         case DECLARATION_KIND_ENUM_ENTRY: {
1242                 ir_mode *const mode = get_ir_mode(type);
1243                 return new_Const(mode, declaration->v.enum_val);
1244         }
1245
1246         case DECLARATION_KIND_LOCAL_VARIABLE: {
1247                 ir_mode *const mode = get_ir_mode(type);
1248                 return get_value(declaration->v.value_number, mode);
1249         }
1250         case DECLARATION_KIND_FUNCTION: {
1251                 ir_mode *const mode = get_ir_mode(type);
1252                 return create_symconst(dbgi, mode, declaration->v.entity);
1253         }
1254         case DECLARATION_KIND_GLOBAL_VARIABLE: {
1255                 ir_node *const addr   = get_global_var_address(dbgi, declaration);
1256                 ir_type *const irtype = get_entity_type(declaration->v.entity);
1257                 return deref_address(irtype, addr, dbgi);
1258         }
1259
1260         case DECLARATION_KIND_LOCAL_VARIABLE_ENTITY: {
1261                 ir_entity *entity = declaration->v.entity;
1262                 ir_node   *frame  = get_local_frame(entity);
1263                 ir_node   *sel    = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
1264                 ir_type   *irtype = get_entity_type(entity);
1265                 return deref_address(irtype, sel, dbgi);
1266         }
1267
1268         case DECLARATION_KIND_COMPOUND_MEMBER:
1269         case DECLARATION_KIND_LABEL_BLOCK:
1270                 panic("not implemented reference type");
1271         }
1272
1273         panic("reference to declaration with unknown type found");
1274 }
1275
1276 static ir_node *reference_addr(const reference_expression_t *ref)
1277 {
1278         dbg_info      *dbgi        = get_dbg_info(&ref->base.source_position);
1279         declaration_t *declaration = ref->declaration;
1280
1281         switch((declaration_kind_t) declaration->declaration_kind) {
1282         case DECLARATION_KIND_UNKNOWN:
1283                 break;
1284         case DECLARATION_KIND_LOCAL_VARIABLE:
1285                 panic("local variable without entity has no address");
1286         case DECLARATION_KIND_FUNCTION: {
1287                 type_t *const  type = skip_typeref(ref->base.type);
1288                 ir_mode *const mode = get_ir_mode(type);
1289                 return create_symconst(dbgi, mode, declaration->v.entity);
1290         }
1291         case DECLARATION_KIND_GLOBAL_VARIABLE: {
1292                 ir_node *const addr = get_global_var_address(dbgi, declaration);
1293                 return addr;
1294         }
1295         case DECLARATION_KIND_LOCAL_VARIABLE_ENTITY: {
1296                 ir_entity *entity = declaration->v.entity;
1297                 ir_node   *frame  = get_local_frame(entity);
1298                 ir_node   *sel    = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
1299
1300                 return sel;
1301         }
1302
1303         case DECLARATION_KIND_ENUM_ENTRY:
1304                 panic("trying to reference enum entry");
1305
1306         case DECLARATION_KIND_COMPOUND_MEMBER:
1307         case DECLARATION_KIND_LABEL_BLOCK:
1308                 panic("not implemented reference type");
1309         }
1310
1311         panic("reference to declaration with unknown type found");
1312 }
1313
1314 static ir_node *process_builtin_call(const call_expression_t *call)
1315 {
1316         dbg_info *dbgi = get_dbg_info(&call->base.source_position);
1317
1318         assert(call->function->kind == EXPR_BUILTIN_SYMBOL);
1319         builtin_symbol_expression_t *builtin = &call->function->builtin_symbol;
1320
1321         type_t *type = skip_typeref(builtin->base.type);
1322         assert(is_type_pointer(type));
1323
1324         type_t   *function_type = skip_typeref(type->pointer.points_to);
1325         symbol_t *symbol        = builtin->symbol;
1326
1327         switch(symbol->ID) {
1328         case T___builtin_alloca: {
1329                 if(call->arguments == NULL || call->arguments->next != NULL) {
1330                         panic("invalid number of parameters on __builtin_alloca");
1331                 }
1332                 expression_t *argument = call->arguments->expression;
1333                 ir_node      *size     = expression_to_firm(argument);
1334
1335                 ir_node *store  = get_store();
1336                 ir_node *alloca = new_d_Alloc(dbgi, store, size, firm_unknown_type,
1337                                               stack_alloc);
1338                 ir_node *proj_m = new_Proj(alloca, mode_M, pn_Alloc_M);
1339                 set_store(proj_m);
1340                 ir_node *res    = new_Proj(alloca, mode_P_data, pn_Alloc_res);
1341
1342                 return res;
1343         }
1344         case T___builtin_nan:
1345         case T___builtin_nanf:
1346         case T___builtin_nand: {
1347                 /* Ignore string for now... */
1348                 assert(is_type_function(function_type));
1349                 ir_mode *mode = get_ir_mode(function_type->function.return_type);
1350                 tarval  *tv   = get_mode_NAN(mode);
1351                 ir_node *res  = new_d_Const(dbgi, mode, tv);
1352                 return res;
1353         }
1354         case T___builtin_va_end:
1355                 return NULL;
1356         default:
1357                 panic("Unsupported builtin found\n");
1358         }
1359 }
1360
1361 static ir_node *call_expression_to_firm(const call_expression_t *call)
1362 {
1363         assert(get_cur_block() != NULL);
1364
1365         expression_t *function = call->function;
1366         if(function->kind == EXPR_BUILTIN_SYMBOL) {
1367                 return process_builtin_call(call);
1368         }
1369         ir_node *callee = expression_to_firm(function);
1370
1371         type_t *type = skip_typeref(function->base.type);
1372         assert(is_type_pointer(type));
1373         pointer_type_t *pointer_type = &type->pointer;
1374         type_t         *points_to    = skip_typeref(pointer_type->points_to);
1375         assert(is_type_function(points_to));
1376         function_type_t *function_type = &points_to->function;
1377
1378         int              n_parameters = 0;
1379         call_argument_t *argument     = call->arguments;
1380         for( ; argument != NULL; argument = argument->next) {
1381                 ++n_parameters;
1382         }
1383
1384         dbg_info *dbgi  = get_dbg_info(&call->base.source_position);
1385
1386         ir_type *ir_method_type  = get_ir_type((type_t*) function_type);
1387         ir_type *new_method_type = NULL;
1388         if(function_type->variadic || function_type->unspecified_parameters) {
1389                 /* we need to construct a new method type matching the call
1390                  * arguments... */
1391                 int n_res       = get_method_n_ress(ir_method_type);
1392                 dbg_info *dbgi  = get_dbg_info(&call->base.source_position);
1393                 new_method_type = new_d_type_method(unique_ident("calltype"),
1394                                                   n_parameters, n_res, dbgi);
1395                 set_method_calling_convention(new_method_type,
1396                                get_method_calling_convention(ir_method_type));
1397                 set_method_additional_properties(new_method_type,
1398                                get_method_additional_properties(ir_method_type));
1399
1400                 for(int i = 0; i < n_res; ++i) {
1401                         set_method_res_type(new_method_type, i,
1402                                             get_method_res_type(ir_method_type, i));
1403                 }
1404         }
1405         ir_node *in[n_parameters];
1406
1407         argument = call->arguments;
1408         int n = 0;
1409         for( ; argument != NULL; argument = argument->next) {
1410                 expression_t *expression = argument->expression;
1411                 ir_node      *arg_node   = expression_to_firm(expression);
1412
1413                 arg_node = do_strict_conv(dbgi, arg_node);
1414
1415                 in[n] = arg_node;
1416                 if(new_method_type != NULL) {
1417                         ir_type *irtype = get_ir_type(expression->base.type);
1418                         set_method_param_type(new_method_type, n, irtype);
1419                 }
1420
1421                 n++;
1422         }
1423         assert(n == n_parameters);
1424
1425         if(new_method_type != NULL)
1426                 ir_method_type = new_method_type;
1427
1428         ir_node  *store = get_store();
1429         ir_node  *node  = new_d_Call(dbgi, store, callee, n_parameters, in,
1430                                      ir_method_type);
1431         ir_node  *mem   = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular);
1432         set_store(mem);
1433
1434         type_t  *return_type = skip_typeref(function_type->return_type);
1435         ir_node *result      = NULL;
1436
1437         if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
1438                 ir_mode *mode;
1439                 if(is_type_scalar(return_type)) {
1440                         mode = get_ir_mode(return_type);
1441                 } else {
1442                         mode = mode_P_data;
1443                 }
1444                 ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result);
1445                 result           = new_d_Proj(dbgi, resproj, mode, 0);
1446         }
1447
1448         return result;
1449 }
1450
1451 static void statement_to_firm(statement_t *statement);
1452 static ir_node *compound_statement_to_firm(compound_statement_t *compound);
1453
1454 static ir_node *expression_to_addr(const expression_t *expression);
1455 static void create_condition_evaluation(const expression_t *expression,
1456                                         ir_node *true_block,
1457                                         ir_node *false_block);
1458
1459 static void assign_value(dbg_info *dbgi, ir_node *addr, type_t *type,
1460                          ir_node *value)
1461 {
1462         value = do_strict_conv(dbgi, value);
1463
1464         ir_node *memory = get_store();
1465
1466         if(is_type_scalar(type)) {
1467                 ir_node  *store     = new_d_Store(dbgi, memory, addr, value);
1468                 ir_node  *store_mem = new_d_Proj(dbgi, store, mode_M, pn_Store_M);
1469                 set_store(store_mem);
1470         } else {
1471                 ir_type *irtype    = get_ir_type(type);
1472                 ir_node *copyb     = new_d_CopyB(dbgi, memory, addr, value, irtype);
1473                 ir_node *copyb_mem = new_Proj(copyb, mode_M, pn_CopyB_M_regular);
1474                 set_store(copyb_mem);
1475         }
1476 }
1477
1478 static tarval *create_bitfield_mask(ir_mode *mode, int offset, int size)
1479 {
1480         tarval *all_one   = get_mode_all_one(mode);
1481         int     mode_size = get_mode_size_bits(mode);
1482
1483         assert(offset >= 0 && size >= 0);
1484         assert(offset + size <= mode_size);
1485         if(size == mode_size) {
1486                 return all_one;
1487         }
1488
1489         long    shiftr    = get_mode_size_bits(mode) - size;
1490         long    shiftl    = offset;
1491         tarval *tv_shiftr = new_tarval_from_long(shiftr, mode_uint);
1492         tarval *tv_shiftl = new_tarval_from_long(shiftl, mode_uint);
1493         tarval *mask0     = tarval_shr(all_one, tv_shiftr);
1494         tarval *mask1     = tarval_shl(mask0, tv_shiftl);
1495
1496         return mask1;
1497 }
1498
1499 static void bitfield_store_to_firm(const unary_expression_t *expression,
1500                                    ir_node *value)
1501 {
1502         expression_t *select = expression->value;
1503         assert(select->kind == EXPR_SELECT);
1504         type_t       *type   = select->base.type;
1505         assert(type->kind == TYPE_BITFIELD);
1506         ir_mode      *mode   = get_ir_mode(type->bitfield.base);
1507         ir_node      *addr   = expression_to_addr(select);
1508
1509         assert(get_irn_mode(value) == mode);
1510
1511         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
1512
1513         /* kill upper bits of value and shift to right position */
1514         ir_entity *entity       = select->select.compound_entry->v.entity;
1515         int        bitoffset    = get_entity_offset_bits_remainder(entity);
1516         ir_type   *entity_type  = get_entity_type(entity);
1517         int        bitsize      = get_mode_size_bits(get_type_mode(entity_type));
1518
1519         tarval  *mask            = create_bitfield_mask(mode, 0, bitsize);
1520         ir_node *mask_node       = new_d_Const(dbgi, mode, mask);
1521         ir_node *value_masked    = new_d_And(dbgi, value, mask_node, mode);
1522         tarval  *shiftl          = new_tarval_from_long(bitoffset, mode_uint);
1523         ir_node *shiftcount      = new_d_Const(dbgi, mode_uint, shiftl);
1524         ir_node *value_maskshift = new_d_Shl(dbgi, value_masked, shiftcount, mode);
1525
1526         /* load current value */
1527         ir_node  *mem             = get_store();
1528         ir_node  *load            = new_d_Load(dbgi, mem, addr, mode);
1529         ir_node  *load_mem        = new_d_Proj(dbgi, load, mode_M, pn_Load_M);
1530         ir_node  *load_res        = new_d_Proj(dbgi, load, mode, pn_Load_res);
1531         tarval   *shift_mask      = create_bitfield_mask(mode, bitoffset, bitsize);
1532         tarval   *inv_mask        = tarval_not(shift_mask);
1533         ir_node  *inv_mask_node   = new_d_Const(dbgi, mode, inv_mask);
1534         ir_node  *load_res_masked = new_d_And(dbgi, load_res, inv_mask_node, mode);
1535
1536         /* construct new value and store */
1537         ir_node *new_val   = new_d_Or(dbgi, load_res_masked, value_maskshift, mode);
1538         ir_node *store     = new_d_Store(dbgi, load_mem, addr, new_val);
1539         ir_node *store_mem = new_d_Proj(dbgi, store, mode_M, pn_Store_M);
1540         set_store(store_mem);
1541 }
1542
1543 static void set_value_for_expression(const expression_t *expression,
1544                                      ir_node *value)
1545 {
1546         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
1547         value          = do_strict_conv(dbgi, value);
1548
1549         if(expression->kind == EXPR_REFERENCE) {
1550                 const reference_expression_t *ref = &expression->reference;
1551
1552                 declaration_t *declaration = ref->declaration;
1553                 assert(declaration->declaration_kind != DECLARATION_KIND_UNKNOWN);
1554                 if(declaration->declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE) {
1555                         set_value(declaration->v.value_number, value);
1556                         return;
1557                 }
1558         }
1559
1560         if(expression->kind == EXPR_UNARY_BITFIELD_EXTRACT) {
1561                 bitfield_store_to_firm(&expression->unary, value);
1562                 return;
1563         }
1564
1565         ir_node *addr = expression_to_addr(expression);
1566         type_t  *type = skip_typeref(expression->base.type);
1567         assign_value(dbgi, addr, type, value);
1568 }
1569
1570 static ir_node *create_conv(dbg_info *dbgi, ir_node *value, ir_mode *dest_mode)
1571 {
1572         ir_mode *value_mode = get_irn_mode(value);
1573
1574         if (value_mode == dest_mode || is_Bad(value))
1575                 return value;
1576
1577         if(dest_mode == mode_b) {
1578                 ir_node *zero = new_Const(value_mode, get_mode_null(value_mode));
1579                 ir_node *cmp  = new_d_Cmp(dbgi, value, zero);
1580                 ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, pn_Cmp_Lg);
1581                 return proj;
1582         }
1583
1584         return new_d_Conv(dbgi, value, dest_mode);
1585 }
1586
1587 static ir_node *create_incdec(const unary_expression_t *expression)
1588 {
1589         dbg_info     *dbgi  = get_dbg_info(&expression->base.source_position);
1590         type_t       *type  = skip_typeref(expression->base.type);
1591         ir_mode      *mode  = get_ir_mode(type);
1592         expression_t *value = expression->value;
1593
1594         ir_node *value_node = expression_to_firm(value);
1595
1596         ir_node *offset;
1597         if(is_type_pointer(type)) {
1598                 pointer_type_t *pointer_type = &type->pointer;
1599                 unsigned        elem_size    = get_type_size(pointer_type->points_to);
1600                 offset = new_Const_long(mode_int, elem_size);
1601         } else {
1602                 assert(is_type_arithmetic(type));
1603                 offset = new_Const(mode, get_mode_one(mode));
1604         }
1605
1606         switch(expression->base.kind) {
1607         case EXPR_UNARY_POSTFIX_INCREMENT: {
1608                 ir_node *new_value = new_d_Add(dbgi, value_node, offset, mode);
1609                 set_value_for_expression(value, new_value);
1610                 return value_node;
1611         }
1612         case EXPR_UNARY_POSTFIX_DECREMENT: {
1613                 ir_node *new_value = new_d_Sub(dbgi, value_node, offset, mode);
1614                 set_value_for_expression(value, new_value);
1615                 return value_node;
1616         }
1617         case EXPR_UNARY_PREFIX_INCREMENT: {
1618                 ir_node *new_value = new_d_Add(dbgi, value_node, offset, mode);
1619                 set_value_for_expression(value, new_value);
1620                 return new_value;
1621         }
1622         case EXPR_UNARY_PREFIX_DECREMENT: {
1623                 ir_node *new_value = new_d_Sub(dbgi, value_node, offset, mode);
1624                 set_value_for_expression(value, new_value);
1625                 return new_value;
1626         }
1627         default:
1628                 panic("no incdec expr in create_incdec");
1629                 return NULL;
1630         }
1631 }
1632
1633 static bool is_local_variable(expression_t *expression)
1634 {
1635         if (expression->kind != EXPR_REFERENCE)
1636                 return false;
1637         reference_expression_t *ref_expr    = &expression->reference;
1638         declaration_t          *declaration = ref_expr->declaration;
1639         return declaration->declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE;
1640 }
1641
1642 static pn_Cmp get_pnc(const expression_kind_t kind, type_t *const type)
1643 {
1644         switch(kind) {
1645         case EXPR_BINARY_EQUAL:         return pn_Cmp_Eq;
1646         case EXPR_BINARY_ISLESSGREATER: return pn_Cmp_Lg;
1647         case EXPR_BINARY_NOTEQUAL:
1648                 return is_type_float(skip_typeref(type)) ? pn_Cmp_Ne : pn_Cmp_Lg;
1649         case EXPR_BINARY_ISLESS:
1650         case EXPR_BINARY_LESS:          return pn_Cmp_Lt;
1651         case EXPR_BINARY_ISLESSEQUAL:
1652         case EXPR_BINARY_LESSEQUAL:     return pn_Cmp_Le;
1653         case EXPR_BINARY_ISGREATER:
1654         case EXPR_BINARY_GREATER:       return pn_Cmp_Gt;
1655         case EXPR_BINARY_ISGREATEREQUAL:
1656         case EXPR_BINARY_GREATEREQUAL:  return pn_Cmp_Ge;
1657         case EXPR_BINARY_ISUNORDERED:   return pn_Cmp_Uo;
1658
1659         default:
1660                 break;
1661         }
1662         panic("trying to get pn_Cmp from non-comparison binexpr type");
1663 }
1664
1665 /**
1666  * Handle the assume optimizer hint: check if a Confirm
1667  * node can be created.
1668  *
1669  * @param dbi    debug info
1670  * @param expr   the IL assume expression
1671  *
1672  * we support here only some simple cases:
1673  *  - var rel const
1674  *  - const rel val
1675  *  - var rel var
1676  */
1677 static ir_node *handle_assume_compare(dbg_info *dbi,
1678                                       const binary_expression_t *expression)
1679 {
1680         expression_t  *op1 = expression->left;
1681         expression_t  *op2 = expression->right;
1682         declaration_t *var2, *var = NULL;
1683         ir_node       *res = NULL;
1684         pn_Cmp         cmp_val;
1685
1686         cmp_val = get_pnc(expression->base.kind, op1->base.type);
1687
1688         if (is_local_variable(op1) && is_local_variable(op2)) {
1689         var  = op1->reference.declaration;
1690             var2 = op2->reference.declaration;
1691
1692                 type_t  *const type = skip_typeref(var->type);
1693                 ir_mode *const mode = get_ir_mode(type);
1694
1695                 ir_node *const irn1 = get_value(var->v.value_number, mode);
1696                 ir_node *const irn2 = get_value(var2->v.value_number, mode);
1697
1698                 res = new_d_Confirm(dbi, irn2, irn1, get_inversed_pnc(cmp_val));
1699                 set_value(var2->v.value_number, res);
1700
1701                 res = new_d_Confirm(dbi, irn1, irn2, cmp_val);
1702                 set_value(var->v.value_number, res);
1703
1704                 return res;
1705         }
1706
1707         expression_t *con;
1708         if (is_local_variable(op1) && is_constant_expression(op2)) {
1709                 var = op1->reference.declaration;
1710                 con = op2;
1711         } else if (is_constant_expression(op1) && is_local_variable(op2)) {
1712                 cmp_val = get_inversed_pnc(cmp_val);
1713                 var = op2->reference.declaration;
1714                 con = op1;
1715         }
1716
1717         if (var != NULL) {
1718                 type_t  *const type = skip_typeref(var->type);
1719                 ir_mode *const mode = get_ir_mode(type);
1720
1721                 res = get_value(var->v.value_number, mode);
1722                 res = new_d_Confirm(dbi, res, expression_to_firm(con), cmp_val);
1723                 set_value(var->v.value_number, res);
1724         }
1725         return res;
1726 }
1727
1728 /**
1729  * Handle the assume optimizer hint.
1730  *
1731  * @param dbi    debug info
1732  * @param expr   the IL assume expression
1733  */
1734 static ir_node *handle_assume(dbg_info *dbi, const expression_t *expression) {
1735         switch(expression->kind) {
1736         case EXPR_BINARY_EQUAL:
1737         case EXPR_BINARY_NOTEQUAL:
1738         case EXPR_BINARY_LESS:
1739         case EXPR_BINARY_LESSEQUAL:
1740         case EXPR_BINARY_GREATER:
1741         case EXPR_BINARY_GREATEREQUAL:
1742                 return handle_assume_compare(dbi, &expression->binary);
1743         default:
1744                 return NULL;
1745         }
1746 }
1747
1748 static ir_node *bitfield_extract_to_firm(const unary_expression_t *expression)
1749 {
1750         expression_t *select = expression->value;
1751         assert(select->kind == EXPR_SELECT);
1752
1753         type_t   *type     = select->base.type;
1754         assert(type->kind == TYPE_BITFIELD);
1755         ir_mode  *mode     = get_ir_mode(type->bitfield.base);
1756         dbg_info *dbgi     = get_dbg_info(&expression->base.source_position);
1757         ir_node  *addr     = expression_to_addr(select);
1758         ir_node  *mem      = get_store();
1759         ir_node  *load     = new_d_Load(dbgi, mem, addr, mode);
1760         ir_node  *load_mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M);
1761         ir_node  *load_res = new_d_Proj(dbgi, load, mode, pn_Load_res);
1762
1763         load_res           = create_conv(dbgi, load_res, mode_int);
1764
1765         set_store(load_mem);
1766
1767         /* kill upper bits */
1768         ir_entity *entity       = select->select.compound_entry->v.entity;
1769         int        bitoffset    = get_entity_offset_bits_remainder(entity);
1770         ir_type   *entity_type  = get_entity_type(entity);
1771         int        bitsize      = get_mode_size_bits(get_type_mode(entity_type));
1772         long       shift_bitsl  = machine_size - bitoffset - bitsize;
1773         assert(shift_bitsl >= 0);
1774         tarval    *tvl          = new_tarval_from_long(shift_bitsl, mode_uint);
1775         ir_node   *countl       = new_d_Const(dbgi, mode_uint, tvl);
1776         ir_node   *shiftl       = new_d_Shl(dbgi, load_res, countl, mode_int);
1777
1778         long       shift_bitsr  = bitoffset + shift_bitsl;
1779         assert(shift_bitsr <= (long) machine_size);
1780         tarval    *tvr          = new_tarval_from_long(shift_bitsr, mode_uint);
1781         ir_node   *countr       = new_d_Const(dbgi, mode_uint, tvr);
1782         ir_node   *shiftr;
1783         if(mode_is_signed(mode)) {
1784                 shiftr = new_d_Shrs(dbgi, shiftl, countr, mode_int);
1785         } else {
1786                 shiftr = new_d_Shr(dbgi, shiftl, countr, mode_int);
1787         }
1788
1789         return create_conv(dbgi, shiftr, mode);
1790 }
1791
1792 static ir_node *unary_expression_to_firm(const unary_expression_t *expression)
1793 {
1794         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
1795         type_t   *type = skip_typeref(expression->base.type);
1796
1797         if(expression->base.kind == EXPR_UNARY_TAKE_ADDRESS)
1798                 return expression_to_addr(expression->value);
1799
1800         const expression_t *value = expression->value;
1801
1802         switch(expression->base.kind) {
1803         case EXPR_UNARY_NEGATE: {
1804                 ir_node *value_node = expression_to_firm(value);
1805                 ir_mode *mode = get_ir_mode(type);
1806                 return new_d_Minus(dbgi, value_node, mode);
1807         }
1808         case EXPR_UNARY_PLUS:
1809                 return expression_to_firm(value);
1810         case EXPR_UNARY_BITWISE_NEGATE: {
1811                 ir_node *value_node = expression_to_firm(value);
1812                 ir_mode *mode = get_ir_mode(type);
1813                 return new_d_Not(dbgi, value_node, mode);
1814         }
1815         case EXPR_UNARY_NOT: {
1816                 ir_node *value_node = expression_to_firm(value);
1817                 ir_mode *mode = get_ir_mode(type);
1818                 if(get_irn_mode(value_node) != mode_b) {
1819                         value_node = create_conv(dbgi, value_node, mode_b);
1820                 }
1821                 value_node = new_d_Not(dbgi, value_node, mode_b);
1822                 if(mode != mode_b) {
1823                         value_node = create_conv(dbgi, value_node, mode);
1824                 }
1825                 return value_node;
1826         }
1827         case EXPR_UNARY_DEREFERENCE: {
1828                 ir_node *value_node = expression_to_firm(value);
1829                 type_t  *value_type = skip_typeref(value->base.type);
1830                 ir_type *irtype     = get_ir_type(value_type);
1831                 assert(is_Pointer_type(irtype));
1832                 ir_type *points_to  = get_pointer_points_to_type(irtype);
1833                 return deref_address(points_to, value_node, dbgi);
1834         }
1835         case EXPR_UNARY_POSTFIX_INCREMENT:
1836         case EXPR_UNARY_POSTFIX_DECREMENT:
1837         case EXPR_UNARY_PREFIX_INCREMENT:
1838         case EXPR_UNARY_PREFIX_DECREMENT:
1839                 return create_incdec(expression);
1840         case EXPR_UNARY_CAST: {
1841                 ir_node *value_node = expression_to_firm(value);
1842                 if(is_type_scalar(type)) {
1843                         ir_mode *mode = get_ir_mode(type);
1844                         ir_node *node = create_conv(dbgi, value_node, mode);
1845                         node = do_strict_conv(dbgi, node);
1846                         return node;
1847                 } else {
1848                         return value_node;
1849                 }
1850         }
1851         case EXPR_UNARY_CAST_IMPLICIT: {
1852                 ir_node *value_node = expression_to_firm(value);
1853                 if(is_type_scalar(type)) {
1854                         ir_mode *mode = get_ir_mode(type);
1855                         return create_conv(dbgi, value_node, mode);
1856                 } else {
1857                         return value_node;
1858                 }
1859         }
1860         case EXPR_UNARY_ASSUME:
1861                 if(firm_opt.confirm)
1862                         return handle_assume(dbgi, value);
1863                 else
1864                         return NULL;
1865         case EXPR_UNARY_BITFIELD_EXTRACT:
1866                 return bitfield_extract_to_firm(expression);
1867
1868         default:
1869                 break;
1870         }
1871         panic("invalid UNEXPR type found");
1872 }
1873
1874 static ir_node *produce_condition_result(const expression_t *expression,
1875                                          dbg_info *dbgi)
1876 {
1877         ir_mode *mode      = get_ir_mode(expression->base.type);
1878         ir_node *cur_block = get_cur_block();
1879
1880         ir_node *one_block = new_immBlock();
1881         ir_node *one       = new_Const(mode, get_mode_one(mode));
1882         ir_node *jmp_one   = new_d_Jmp(dbgi);
1883
1884         ir_node *zero_block = new_immBlock();
1885         ir_node *zero       = new_Const(mode, get_mode_null(mode));
1886         ir_node *jmp_zero   = new_d_Jmp(dbgi);
1887
1888         set_cur_block(cur_block);
1889         create_condition_evaluation(expression, one_block, zero_block);
1890         mature_immBlock(one_block);
1891         mature_immBlock(zero_block);
1892
1893         ir_node *common_block = new_immBlock();
1894         add_immBlock_pred(common_block, jmp_one);
1895         add_immBlock_pred(common_block, jmp_zero);
1896         mature_immBlock(common_block);
1897
1898         ir_node *in[2] = { one, zero };
1899         ir_node *val   = new_d_Phi(dbgi, 2, in, mode);
1900
1901         return val;
1902 }
1903
1904 static ir_node *create_lazy_op(const binary_expression_t *expression)
1905 {
1906         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
1907         type_t   *type = expression->base.type;
1908         ir_mode  *mode = get_ir_mode(type);
1909
1910         if(is_constant_expression(expression->left)) {
1911                 long val = fold_constant(expression->left);
1912                 expression_kind_t ekind = expression->base.kind;
1913                 if((ekind == EXPR_BINARY_LOGICAL_AND && val != 0)
1914                                 || (ekind == EXPR_BINARY_LOGICAL_OR && val == 0)) {
1915                         return expression_to_firm(expression->right);
1916                 } else {
1917                         assert((ekind == EXPR_BINARY_LOGICAL_AND && val == 0)
1918                                         || (ekind == EXPR_BINARY_LOGICAL_OR && val != 0));
1919                         return new_Const(mode, get_mode_one(mode));
1920                 }
1921         }
1922
1923         return produce_condition_result((const expression_t*) expression, dbgi);
1924 }
1925
1926 typedef ir_node * (*create_arithmetic_func)(dbg_info *dbgi, ir_node *left,
1927                                             ir_node *right, ir_mode *mode);
1928
1929 static ir_node *create_arithmetic_binop(const binary_expression_t *expression,
1930                                         create_arithmetic_func func)
1931 {
1932         dbg_info *dbgi  = get_dbg_info(&expression->base.source_position);
1933         ir_node  *left  = expression_to_firm(expression->left);
1934         ir_node  *right = expression_to_firm(expression->right);
1935         type_t   *type  = expression->right->base.type;
1936         /* be careful with the modes, because in arithmetic assign nodes only
1937          * the right operand has the mode of the arithmetic already */
1938         ir_mode  *mode  = get_ir_mode(type);
1939         left            = create_conv(dbgi, left, mode);
1940         ir_node  *res   = func(dbgi, left, right, mode);
1941
1942         return res;
1943 }
1944
1945 static ir_node *pointer_arithmetic(ir_node  *const pointer,
1946                                    ir_node  *      integer,
1947                                    type_t   *const type,
1948                                    dbg_info *const dbgi,
1949                                    const create_arithmetic_func func)
1950 {
1951         pointer_type_t *const pointer_type = &type->pointer;
1952         type_t         *const points_to    = pointer_type->points_to;
1953         const unsigned        elem_size    = get_type_size(points_to);
1954
1955         assert(elem_size >= 1);
1956         if (elem_size > 1) {
1957                 integer             = create_conv(dbgi, integer, mode_int);
1958                 ir_node *const cnst = new_Const_long(mode_int, (long)elem_size);
1959                 ir_node *const mul  = new_d_Mul(dbgi, integer, cnst, mode_int);
1960                 integer = mul;
1961         }
1962
1963         ir_mode *const mode = get_ir_mode(type);
1964         return func(dbgi, pointer, integer, mode);
1965 }
1966
1967 static ir_node *create_arithmetic_assign_binop(
1968                 const binary_expression_t *expression, create_arithmetic_func func)
1969 {
1970         dbg_info *const dbgi = get_dbg_info(&expression->base.source_position);
1971         type_t   *const type = skip_typeref(expression->base.type);
1972         ir_node  *value;
1973
1974         if (is_type_pointer(type)) {
1975                 ir_node *const pointer = expression_to_firm(expression->left);
1976                 ir_node *      integer = expression_to_firm(expression->right);
1977                 value = pointer_arithmetic(pointer, integer, type, dbgi, func);
1978         } else {
1979                 value = create_arithmetic_binop(expression, func);
1980         }
1981
1982         ir_mode *const mode = get_ir_mode(type);
1983         value = create_conv(dbgi, value, mode);
1984         set_value_for_expression(expression->left, value);
1985
1986         return value;
1987 }
1988
1989 static ir_node *create_add(const binary_expression_t *expression)
1990 {
1991         dbg_info *dbgi  = get_dbg_info(&expression->base.source_position);
1992         ir_node  *left  = expression_to_firm(expression->left);
1993         ir_node  *right = expression_to_firm(expression->right);
1994         type_t   *type  = expression->base.type;
1995
1996         expression_t *expr_left  = expression->left;
1997         expression_t *expr_right = expression->right;
1998         type_t       *type_left  = skip_typeref(expr_left->base.type);
1999         type_t       *type_right = skip_typeref(expr_right->base.type);
2000
2001         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
2002                 ir_mode *const mode = get_ir_mode(type);
2003                 return new_d_Add(dbgi, left, right, mode);
2004         }
2005
2006         if (is_type_pointer(type_left)) {
2007                 return pointer_arithmetic(left, right, type, dbgi, new_d_Add);
2008         } else {
2009                 assert(is_type_pointer(type_right));
2010                 return pointer_arithmetic(right, left, type, dbgi, new_d_Add);
2011         }
2012 }
2013
2014 static ir_node *create_sub(const binary_expression_t *expression)
2015 {
2016         dbg_info *const dbgi  = get_dbg_info(&expression->base.source_position);
2017         expression_t *const expr_left  = expression->left;
2018         expression_t *const expr_right = expression->right;
2019         ir_node      *const left       = expression_to_firm(expr_left);
2020         ir_node      *const right      = expression_to_firm(expr_right);
2021         type_t       *const type       = expression->base.type;
2022         type_t       *const type_left  = skip_typeref(expr_left->base.type);
2023         type_t       *const type_right = skip_typeref(expr_right->base.type);
2024
2025         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
2026                 ir_mode *const mode = get_ir_mode(type);
2027                 return new_d_Sub(dbgi, left, right, mode);
2028         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
2029                 const pointer_type_t *const ptr_type = &type_left->pointer;
2030                 const unsigned elem_size             = get_type_size(ptr_type->points_to);
2031                 ir_mode *const mode   = get_ir_mode(type);
2032                 ir_node *const sub    = new_d_Sub(dbgi, left, right, mode);
2033                 ir_node *const cnst   = new_Const_long(mode_int, (long)elem_size);
2034                 ir_node *const no_mem = new_NoMem();
2035                 ir_node *const div    = new_d_Div(dbgi, no_mem, sub, cnst, mode,
2036                                                   op_pin_state_floats);
2037                 return new_d_Proj(dbgi, div, mode, pn_Div_res);
2038         }
2039
2040         assert(is_type_pointer(type_left));
2041         return pointer_arithmetic(left, right, type_left, dbgi, new_d_Sub);
2042 }
2043
2044 static ir_node *create_shift(const binary_expression_t *expression)
2045 {
2046         dbg_info *dbgi  = get_dbg_info(&expression->base.source_position);
2047         ir_node  *left  = expression_to_firm(expression->left);
2048         ir_node  *right = expression_to_firm(expression->right);
2049         type_t   *type  = expression->base.type;
2050         ir_mode  *mode  = get_ir_mode(type);
2051
2052         /* firm always wants the shift count to be unsigned */
2053         right = create_conv(dbgi, right, mode_uint);
2054
2055         ir_node *res;
2056
2057         switch(expression->base.kind) {
2058         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2059         case EXPR_BINARY_SHIFTLEFT:
2060                 res = new_d_Shl(dbgi, left, right, mode);
2061                 break;
2062         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2063         case EXPR_BINARY_SHIFTRIGHT: {
2064                  expression_t *expr_left = expression->left;
2065                  type_t       *type_left = skip_typeref(expr_left->base.type);
2066
2067                  if(is_type_signed(type_left)) {
2068                         res = new_d_Shrs(dbgi, left, right, mode);
2069                  } else {
2070                          res = new_d_Shr(dbgi, left, right, mode);
2071                  }
2072                  break;
2073         }
2074         default:
2075                 panic("create shift op called for non-shift op");
2076         }
2077
2078         return res;
2079 }
2080
2081
2082 static ir_node *create_divmod(const binary_expression_t *expression)
2083 {
2084         dbg_info *dbgi  = get_dbg_info(&expression->base.source_position);
2085         ir_node  *left  = expression_to_firm(expression->left);
2086         ir_node  *right = expression_to_firm(expression->right);
2087         ir_node  *pin   = new_Pin(new_NoMem());
2088         /* be careful with the modes, because in arithmetic assign nodes only
2089          * the right operand has the mode of the arithmetic already */
2090         type_t   *type  = expression->right->base.type;
2091         ir_mode  *mode  = get_ir_mode(type);
2092         left            = create_conv(dbgi, left, mode);
2093         ir_node  *op;
2094         ir_node  *res;
2095
2096         switch (expression->base.kind) {
2097         case EXPR_BINARY_DIV:
2098         case EXPR_BINARY_DIV_ASSIGN:
2099                 if(mode_is_float(mode)) {
2100                         op  = new_d_Quot(dbgi, pin, left, right, mode, op_pin_state_floats);
2101                         res = new_d_Proj(dbgi, op, mode, pn_Quot_res);
2102                 } else {
2103                         op  = new_d_Div(dbgi, pin, left, right, mode, op_pin_state_floats);
2104                         res = new_d_Proj(dbgi, op, mode, pn_Div_res);
2105                 }
2106                 break;
2107
2108         case EXPR_BINARY_MOD:
2109         case EXPR_BINARY_MOD_ASSIGN:
2110                 assert(!mode_is_float(mode));
2111                 op  = new_d_Mod(dbgi, pin, left, right, mode, op_pin_state_floats);
2112                 res = new_d_Proj(dbgi, op, mode, pn_Mod_res);
2113                 break;
2114
2115         default: panic("unexpected binary expression type in create_divmod()");
2116         }
2117
2118         return res;
2119 }
2120
2121 static ir_node *create_arithmetic_assign_divmod(
2122                 const binary_expression_t *expression)
2123 {
2124         ir_node  *      value = create_divmod(expression);
2125         dbg_info *const dbgi  = get_dbg_info(&expression->base.source_position);
2126         type_t   *const type  = expression->base.type;
2127         ir_mode  *const mode  = get_ir_mode(type);
2128
2129         assert(type->kind != TYPE_POINTER);
2130
2131         value = create_conv(dbgi, value, mode);
2132         set_value_for_expression(expression->left, value);
2133
2134         return value;
2135 }
2136
2137 static ir_node *create_arithmetic_assign_shift(
2138                 const binary_expression_t *expression)
2139 {
2140         ir_node  *      value = create_shift(expression);
2141         dbg_info *const dbgi  = get_dbg_info(&expression->base.source_position);
2142         type_t   *const type  = expression->base.type;
2143         ir_mode  *const mode  = get_ir_mode(type);
2144
2145         value = create_conv(dbgi, value, mode);
2146         set_value_for_expression(expression->left, value);
2147
2148         return value;
2149 }
2150
2151 static ir_node *binary_expression_to_firm(const binary_expression_t *expression)
2152 {
2153         expression_kind_t kind = expression->base.kind;
2154
2155         switch(kind) {
2156         case EXPR_BINARY_EQUAL:
2157         case EXPR_BINARY_NOTEQUAL:
2158         case EXPR_BINARY_LESS:
2159         case EXPR_BINARY_LESSEQUAL:
2160         case EXPR_BINARY_GREATER:
2161         case EXPR_BINARY_GREATEREQUAL:
2162         case EXPR_BINARY_ISGREATER:
2163         case EXPR_BINARY_ISGREATEREQUAL:
2164         case EXPR_BINARY_ISLESS:
2165         case EXPR_BINARY_ISLESSEQUAL:
2166         case EXPR_BINARY_ISLESSGREATER:
2167         case EXPR_BINARY_ISUNORDERED: {
2168                 dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
2169                 ir_node *left  = expression_to_firm(expression->left);
2170                 ir_node *right = expression_to_firm(expression->right);
2171                 ir_node *cmp   = new_d_Cmp(dbgi, left, right);
2172                 long     pnc   = get_pnc(kind, expression->left->base.type);
2173                 ir_node *proj  = new_d_Proj(dbgi, cmp, mode_b, pnc);
2174                 return proj;
2175         }
2176         case EXPR_BINARY_ASSIGN: {
2177                 ir_node *right = expression_to_firm(expression->right);
2178                 set_value_for_expression(expression->left, right);
2179
2180                 return right;
2181         }
2182         case EXPR_BINARY_ADD:
2183                 return create_add(expression);
2184         case EXPR_BINARY_SUB:
2185                 return create_sub(expression);
2186         case EXPR_BINARY_MUL:
2187                 return create_arithmetic_binop(expression, new_d_Mul);
2188         case EXPR_BINARY_BITWISE_AND:
2189                 return create_arithmetic_binop(expression, new_d_And);
2190         case EXPR_BINARY_BITWISE_OR:
2191                 return create_arithmetic_binop(expression, new_d_Or);
2192         case EXPR_BINARY_BITWISE_XOR:
2193                 return create_arithmetic_binop(expression, new_d_Eor);
2194         case EXPR_BINARY_SHIFTLEFT:
2195         case EXPR_BINARY_SHIFTRIGHT:
2196                 return create_shift(expression);
2197         case EXPR_BINARY_DIV:
2198         case EXPR_BINARY_MOD:
2199                 return create_divmod(expression);
2200         case EXPR_BINARY_LOGICAL_AND:
2201         case EXPR_BINARY_LOGICAL_OR:
2202                 return create_lazy_op(expression);
2203         case EXPR_BINARY_COMMA:
2204                 expression_to_firm(expression->left);
2205                 return expression_to_firm(expression->right);
2206         case EXPR_BINARY_ADD_ASSIGN:
2207                 return create_arithmetic_assign_binop(expression, new_d_Add);
2208         case EXPR_BINARY_SUB_ASSIGN:
2209                 return create_arithmetic_assign_binop(expression, new_d_Sub);
2210         case EXPR_BINARY_MUL_ASSIGN:
2211                 return create_arithmetic_assign_binop(expression, new_d_Mul);
2212         case EXPR_BINARY_MOD_ASSIGN:
2213         case EXPR_BINARY_DIV_ASSIGN:
2214                 return create_arithmetic_assign_divmod(expression);
2215         case EXPR_BINARY_BITWISE_AND_ASSIGN:
2216                 return create_arithmetic_assign_binop(expression, new_d_And);
2217         case EXPR_BINARY_BITWISE_OR_ASSIGN:
2218                 return create_arithmetic_assign_binop(expression, new_d_Or);
2219         case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2220                 return create_arithmetic_assign_binop(expression, new_d_Eor);
2221         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2222         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2223                 return create_arithmetic_assign_shift(expression);
2224         case EXPR_BINARY_BUILTIN_EXPECT:
2225                 return expression_to_firm(expression->left);
2226         default:
2227                 panic("TODO binexpr type");
2228         }
2229 }
2230
2231 static ir_node *array_access_addr(const array_access_expression_t *expression)
2232 {
2233         dbg_info *dbgi      = get_dbg_info(&expression->base.source_position);
2234         ir_node  *base_addr = expression_to_firm(expression->array_ref);
2235         ir_node  *offset    = expression_to_firm(expression->index);
2236         offset              = create_conv(dbgi, offset, mode_uint);
2237
2238         type_t *ref_type = skip_typeref(expression->array_ref->base.type);
2239         assert(is_type_pointer(ref_type));
2240         pointer_type_t *pointer_type = &ref_type->pointer;
2241
2242         unsigned elem_size       = get_type_size(pointer_type->points_to);
2243         ir_node *elem_size_const = new_Const_long(mode_uint, elem_size);
2244         ir_node *real_offset     = new_d_Mul(dbgi, offset, elem_size_const,
2245                                              mode_uint);
2246         ir_node *result          = new_d_Add(dbgi, base_addr, real_offset, mode_P_data);
2247
2248         return result;
2249 }
2250
2251 static ir_node *array_access_to_firm(
2252                 const array_access_expression_t *expression)
2253 {
2254         dbg_info *dbgi   = get_dbg_info(&expression->base.source_position);
2255         ir_node  *addr   = array_access_addr(expression);
2256         type_t   *type   = revert_automatic_type_conversion(
2257                         (const expression_t*) expression);
2258         type             = skip_typeref(type);
2259         ir_type  *irtype = get_ir_type(type);
2260
2261         return deref_address(irtype, addr, dbgi);
2262 }
2263
2264 static long get_offsetof_offset(const offsetof_expression_t *expression)
2265 {
2266         type_t *orig_type = expression->type;
2267         long    offset    = 0;
2268
2269         designator_t *designator = expression->designator;
2270         for( ; designator != NULL; designator = designator->next) {
2271                 type_t *type = skip_typeref(orig_type);
2272                 /* be sure the type is constructed */
2273                 (void) get_ir_type(type);
2274
2275                 if(designator->symbol != NULL) {
2276                         assert(is_type_compound(type));
2277                         symbol_t *symbol = designator->symbol;
2278
2279                         declaration_t *declaration = type->compound.declaration;
2280                         declaration_t *iter        = declaration->scope.declarations;
2281                         for( ; iter != NULL; iter = iter->next) {
2282                                 if(iter->symbol == symbol) {
2283                                         break;
2284                                 }
2285                         }
2286                         assert(iter != NULL);
2287
2288                         assert(iter->declaration_kind == DECLARATION_KIND_COMPOUND_MEMBER);
2289                         offset += get_entity_offset(iter->v.entity);
2290
2291                         orig_type = iter->type;
2292                 } else {
2293                         expression_t *array_index = designator->array_index;
2294                         assert(designator->array_index != NULL);
2295                         assert(is_type_array(type));
2296                         assert(is_type_valid(array_index->base.type));
2297
2298                         long index         = fold_constant(array_index);
2299                         ir_type *arr_type  = get_ir_type(type);
2300                         ir_type *elem_type = get_array_element_type(arr_type);
2301                         long     elem_size = get_type_size_bytes(elem_type);
2302
2303                         offset += index * elem_size;
2304
2305                         orig_type = type->array.element_type;
2306                 }
2307         }
2308
2309         return offset;
2310 }
2311
2312 static ir_node *offsetof_to_firm(const offsetof_expression_t *expression)
2313 {
2314         ir_mode  *mode   = get_ir_mode(expression->base.type);
2315         long      offset = get_offsetof_offset(expression);
2316         tarval   *tv     = new_tarval_from_long(offset, mode);
2317         dbg_info *dbgi   = get_dbg_info(&expression->base.source_position);
2318
2319         return new_d_Const(dbgi, mode, tv);
2320 }
2321
2322 static void create_local_initializer(initializer_t *initializer, dbg_info *dbgi,
2323                                      ir_entity *entity, type_t *type);
2324
2325 static ir_node *compound_literal_to_firm(
2326                 const compound_literal_expression_t *expression)
2327 {
2328         type_t *type = expression->type;
2329
2330         /* create an entity on the stack */
2331         ir_type *frame_type = get_irg_frame_type(current_ir_graph);
2332
2333         ident     *const id     = unique_ident("CompLit");
2334         ir_type   *const irtype = get_ir_type(type);
2335         dbg_info  *const dbgi   = get_dbg_info(&expression->base.source_position);
2336         ir_entity *const entity = new_d_entity(frame_type, id, irtype, dbgi);
2337         set_entity_ld_ident(entity, id);
2338
2339         set_entity_variability(entity, variability_uninitialized);
2340
2341         /* create initialisation code */
2342         initializer_t *initializer = expression->initializer;
2343         create_local_initializer(initializer, dbgi, entity, type);
2344
2345         /* create a sel for the compound literal address */
2346         ir_node *frame = get_local_frame(entity);
2347         ir_node *sel   = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
2348         return sel;
2349 }
2350
2351 /**
2352  * Transform a sizeof expression into Firm code.
2353  */
2354 static ir_node *sizeof_to_firm(const typeprop_expression_t *expression)
2355 {
2356         type_t *type = expression->type;
2357         if(type == NULL) {
2358                 type = expression->tp_expression->base.type;
2359                 assert(type != NULL);
2360         }
2361
2362         ir_mode *const mode = get_ir_mode(expression->base.type);
2363         symconst_symbol sym;
2364         sym.type_p = get_ir_type(type);
2365         return new_SymConst(mode, sym, symconst_type_size);
2366 }
2367
2368 /**
2369  * Transform an alignof expression into Firm code.
2370  */
2371 static ir_node *alignof_to_firm(const typeprop_expression_t *expression)
2372 {
2373         type_t *type = expression->type;
2374         if(type == NULL) {
2375                 /* beware: if expression is a variable reference, return the
2376                    alignment of the variable. */
2377                 const expression_t *tp_expression = expression->tp_expression;
2378                 const declaration_t *declaration = expr_is_variable(tp_expression);
2379                 if (declaration != NULL) {
2380                         /* TODO: get the alignment of this variable. */
2381                 }
2382                 type = tp_expression->base.type;
2383                 assert(type != NULL);
2384         }
2385
2386         ir_mode *const mode = get_ir_mode(expression->base.type);
2387         symconst_symbol sym;
2388         sym.type_p = get_ir_type(type);
2389         return new_SymConst(mode, sym, symconst_type_align);
2390 }
2391
2392 static void init_ir_types(void);
2393 long fold_constant(const expression_t *expression)
2394 {
2395         init_ir_types();
2396
2397         assert(is_constant_expression(expression));
2398
2399         ir_graph *old_current_ir_graph = current_ir_graph;
2400         if(current_ir_graph == NULL) {
2401                 current_ir_graph = get_const_code_irg();
2402         }
2403
2404         ir_node *cnst = expression_to_firm(expression);
2405         current_ir_graph = old_current_ir_graph;
2406
2407         if(!is_Const(cnst)) {
2408                 panic("couldn't fold constant\n");
2409         }
2410
2411         tarval *tv = get_Const_tarval(cnst);
2412         if(!tarval_is_long(tv)) {
2413                 panic("result of constant folding is not integer\n");
2414         }
2415
2416         return get_tarval_long(tv);
2417 }
2418
2419 static ir_node *conditional_to_firm(const conditional_expression_t *expression)
2420 {
2421         dbg_info *const dbgi = get_dbg_info(&expression->base.source_position);
2422
2423         /* first try to fold a constant condition */
2424         if(is_constant_expression(expression->condition)) {
2425                 long val = fold_constant(expression->condition);
2426                 if(val) {
2427                         return expression_to_firm(expression->true_expression);
2428                 } else {
2429                         return expression_to_firm(expression->false_expression);
2430                 }
2431         }
2432
2433         ir_node *cur_block   = get_cur_block();
2434
2435         /* create the true block */
2436         ir_node *true_block  = new_immBlock();
2437
2438         ir_node *true_val = expression_to_firm(expression->true_expression);
2439         ir_node *true_jmp = new_Jmp();
2440
2441         /* create the false block */
2442         ir_node *false_block = new_immBlock();
2443
2444         ir_node *false_val = expression_to_firm(expression->false_expression);
2445         ir_node *false_jmp = new_Jmp();
2446
2447         /* create the condition evaluation */
2448         set_cur_block(cur_block);
2449         create_condition_evaluation(expression->condition, true_block, false_block);
2450         mature_immBlock(true_block);
2451         mature_immBlock(false_block);
2452
2453         /* create the common block */
2454         ir_node *common_block = new_immBlock();
2455         add_immBlock_pred(common_block, true_jmp);
2456         add_immBlock_pred(common_block, false_jmp);
2457         mature_immBlock(common_block);
2458
2459         /* TODO improve static semantics, so either both or no values are NULL */
2460         if (true_val == NULL || false_val == NULL)
2461                 return NULL;
2462
2463         ir_node *in[2] = { true_val, false_val };
2464         ir_mode *mode  = get_irn_mode(true_val);
2465         assert(get_irn_mode(false_val) == mode);
2466         ir_node *val   = new_d_Phi(dbgi, 2, in, mode);
2467
2468         return val;
2469 }
2470
2471 static ir_node *select_addr(const select_expression_t *expression)
2472 {
2473         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
2474
2475         ir_node *compound_addr = expression_to_firm(expression->compound);
2476
2477         declaration_t *entry = expression->compound_entry;
2478         assert(entry->declaration_kind == DECLARATION_KIND_COMPOUND_MEMBER);
2479         ir_entity     *entity = entry->v.entity;
2480
2481         assert(entity != NULL);
2482
2483         ir_node *sel = new_d_simpleSel(dbgi, new_NoMem(), compound_addr, entity);
2484
2485         return sel;
2486 }
2487
2488 static ir_node *select_to_firm(const select_expression_t *expression)
2489 {
2490         dbg_info *dbgi   = get_dbg_info(&expression->base.source_position);
2491         ir_node  *addr   = select_addr(expression);
2492         type_t   *type   = revert_automatic_type_conversion(
2493                         (const expression_t*) expression);
2494         type             = skip_typeref(type);
2495         ir_type  *irtype = get_ir_type(type);
2496
2497         return deref_address(irtype, addr, dbgi);
2498 }
2499
2500 /* Values returned by __builtin_classify_type. */
2501 typedef enum gcc_type_class
2502 {
2503         no_type_class = -1,
2504         void_type_class,
2505         integer_type_class,
2506         char_type_class,
2507         enumeral_type_class,
2508         boolean_type_class,
2509         pointer_type_class,
2510         reference_type_class,
2511         offset_type_class,
2512         real_type_class,
2513         complex_type_class,
2514         function_type_class,
2515         method_type_class,
2516         record_type_class,
2517         union_type_class,
2518         array_type_class,
2519         string_type_class,
2520         set_type_class,
2521         file_type_class,
2522         lang_type_class
2523 } gcc_type_class;
2524
2525 static ir_node *classify_type_to_firm(const classify_type_expression_t *const expr)
2526 {
2527         const type_t *const type = expr->type_expression->base.type;
2528
2529         gcc_type_class tc;
2530         switch (type->kind)
2531         {
2532                 case TYPE_ATOMIC: {
2533                         const atomic_type_t *const atomic_type = &type->atomic;
2534                         switch (atomic_type->akind) {
2535                                 /* should not be reached */
2536                                 case ATOMIC_TYPE_INVALID:
2537                                         tc = no_type_class;
2538                                         break;
2539
2540                                 /* gcc cannot do that */
2541                                 case ATOMIC_TYPE_VOID:
2542                                         tc = void_type_class;
2543                                         break;
2544
2545                                 case ATOMIC_TYPE_CHAR:      /* gcc handles this as integer */
2546                                 case ATOMIC_TYPE_SCHAR:     /* gcc handles this as integer */
2547                                 case ATOMIC_TYPE_UCHAR:     /* gcc handles this as integer */
2548                                 case ATOMIC_TYPE_SHORT:
2549                                 case ATOMIC_TYPE_USHORT:
2550                                 case ATOMIC_TYPE_INT:
2551                                 case ATOMIC_TYPE_UINT:
2552                                 case ATOMIC_TYPE_LONG:
2553                                 case ATOMIC_TYPE_ULONG:
2554                                 case ATOMIC_TYPE_LONGLONG:
2555                                 case ATOMIC_TYPE_ULONGLONG:
2556                                 case ATOMIC_TYPE_BOOL:      /* gcc handles this as integer */
2557                                         tc = integer_type_class;
2558                                         break;
2559
2560                                 case ATOMIC_TYPE_FLOAT:
2561                                 case ATOMIC_TYPE_DOUBLE:
2562                                 case ATOMIC_TYPE_LONG_DOUBLE:
2563                                         tc = real_type_class;
2564                                         break;
2565
2566 #ifdef PROVIDE_COMPLEX
2567                                 case ATOMIC_TYPE_FLOAT_COMPLEX:
2568                                 case ATOMIC_TYPE_DOUBLE_COMPLEX:
2569                                 case ATOMIC_TYPE_LONG_DOUBLE_COMPLEX:
2570                                         tc = complex_type_class;
2571                                         break;
2572                                 case ATOMIC_TYPE_FLOAT_IMAGINARY:
2573                                 case ATOMIC_TYPE_DOUBLE_IMAGINARY:
2574                                 case ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY:
2575                                         tc = complex_type_class;
2576                                         break;
2577 #endif
2578
2579                                 default:
2580                                         panic("Unimplemented case in classify_type_to_firm().");
2581                         }
2582                         break;
2583                 }
2584
2585                 case TYPE_ARRAY:           /* gcc handles this as pointer */
2586                 case TYPE_FUNCTION:        /* gcc handles this as pointer */
2587                 case TYPE_POINTER:         tc = pointer_type_class; break;
2588                 case TYPE_COMPOUND_STRUCT: tc = record_type_class;  break;
2589                 case TYPE_COMPOUND_UNION:  tc = union_type_class;   break;
2590
2591                 /* gcc handles this as integer */
2592                 case TYPE_ENUM:            tc = integer_type_class; break;
2593
2594                 default:
2595                         panic("Unimplemented case in classify_type_to_firm().");
2596         }
2597
2598         dbg_info *const dbgi = get_dbg_info(&expr->base.source_position);
2599         ir_mode  *const mode = mode_int;
2600         tarval   *const tv   = new_tarval_from_long(tc, mode);
2601         return new_d_Const(dbgi, mode, tv);
2602 }
2603
2604 static ir_node *function_name_to_firm(
2605                 const string_literal_expression_t *const expr)
2606 {
2607         if (current_function_name == NULL) {
2608                 const source_position_t *const src_pos = &expr->base.source_position;
2609                 const char *const name = current_function_decl->symbol->string;
2610                 const string_t string = { name, strlen(name) + 1 };
2611                 current_function_name = string_to_firm(src_pos, "__func__", &string);
2612         }
2613
2614         return current_function_name;
2615 }
2616
2617 static ir_node *statement_expression_to_firm(const statement_expression_t *expr)
2618 {
2619         statement_t *statement = expr->statement;
2620
2621         assert(statement->kind == STATEMENT_COMPOUND);
2622         return compound_statement_to_firm(&statement->compound);
2623 }
2624
2625 static ir_node *va_start_expression_to_firm(
2626         const va_start_expression_t *const expr)
2627 {
2628         ir_type   *const method_type = get_ir_type(current_function_decl->type);
2629         int        const n           = get_method_n_params(method_type) - 1;
2630         ir_entity *const parm_ent    = get_method_value_param_ent(method_type, n);
2631         ir_node   *const arg_base    = get_irg_value_param_base(current_ir_graph);
2632         dbg_info  *const dbgi        = get_dbg_info(&expr->base.source_position);
2633         ir_node   *const no_mem      = new_NoMem();
2634         ir_node   *const arg_sel     =
2635                 new_d_simpleSel(dbgi, no_mem, arg_base, parm_ent);
2636
2637         size_t     const parm_size   = get_type_size(expr->parameter->type);
2638         ir_node   *const cnst        = new_Const_long(mode_uint, parm_size);
2639         ir_node   *const add         = new_d_Add(dbgi, arg_sel, cnst, mode_P_data);
2640         set_value_for_expression(expr->ap, add);
2641
2642         return NULL;
2643 }
2644
2645 static ir_node *va_arg_expression_to_firm(const va_arg_expression_t *const expr)
2646 {
2647         ir_type  *const irtype = get_ir_type(expr->base.type);
2648         ir_node  *const ap     = expression_to_firm(expr->ap);
2649         dbg_info *const dbgi   = get_dbg_info(&expr->base.source_position);
2650         ir_node  *const res    = deref_address(irtype, ap, dbgi);
2651
2652         size_t    const parm_size = get_type_size(expr->base.type);
2653         ir_node  *const cnst      = new_Const_long(mode_uint, parm_size);
2654         ir_node  *const add       = new_d_Add(dbgi, ap, cnst, mode_P_data);
2655         set_value_for_expression(expr->ap, add);
2656
2657         return res;
2658 }
2659
2660 static ir_node *dereference_addr(const unary_expression_t *const expression)
2661 {
2662         assert(expression->base.kind == EXPR_UNARY_DEREFERENCE);
2663         return expression_to_firm(expression->value);
2664 }
2665
2666 static ir_node *expression_to_addr(const expression_t *expression)
2667 {
2668         switch(expression->kind) {
2669         case EXPR_REFERENCE:
2670                 return reference_addr(&expression->reference);
2671         case EXPR_ARRAY_ACCESS:
2672                 return array_access_addr(&expression->array_access);
2673         case EXPR_SELECT:
2674                 return select_addr(&expression->select);
2675         case EXPR_CALL:
2676                 return call_expression_to_firm(&expression->call);
2677         case EXPR_UNARY_DEREFERENCE: {
2678                 return dereference_addr(&expression->unary);
2679         }
2680         default:
2681                 break;
2682         }
2683         panic("trying to get address of non-lvalue");
2684 }
2685
2686 static ir_node *builtin_constant_to_firm(
2687                 const builtin_constant_expression_t *expression)
2688 {
2689         ir_mode *mode = get_ir_mode(expression->base.type);
2690         long     v;
2691
2692         if (is_constant_expression(expression->value)) {
2693                 v = 1;
2694         } else {
2695                 v = 0;
2696         }
2697         return new_Const_long(mode, v);
2698 }
2699
2700 static ir_node *builtin_prefetch_to_firm(
2701                 const builtin_prefetch_expression_t *expression)
2702 {
2703         ir_node *adr = expression_to_firm(expression->adr);
2704         /* no Firm support for prefetch yet */
2705         (void) adr;
2706         return NULL;
2707 }
2708
2709 static ir_node *_expression_to_firm(const expression_t *expression)
2710 {
2711         switch(expression->kind) {
2712         case EXPR_CHAR_CONST:
2713                 return char_const_to_firm(&expression->conste);
2714         case EXPR_CONST:
2715                 return const_to_firm(&expression->conste);
2716         case EXPR_STRING_LITERAL:
2717                 return string_literal_to_firm(&expression->string);
2718         case EXPR_WIDE_STRING_LITERAL:
2719                 return wide_string_literal_to_firm(&expression->wide_string);
2720         case EXPR_REFERENCE:
2721                 return reference_expression_to_firm(&expression->reference);
2722         case EXPR_CALL:
2723                 return call_expression_to_firm(&expression->call);
2724         EXPR_UNARY_CASES
2725                 return unary_expression_to_firm(&expression->unary);
2726         EXPR_BINARY_CASES
2727                 return binary_expression_to_firm(&expression->binary);
2728         case EXPR_ARRAY_ACCESS:
2729                 return array_access_to_firm(&expression->array_access);
2730         case EXPR_SIZEOF:
2731                 return sizeof_to_firm(&expression->typeprop);
2732         case EXPR_ALIGNOF:
2733                 return alignof_to_firm(&expression->typeprop);
2734         case EXPR_CONDITIONAL:
2735                 return conditional_to_firm(&expression->conditional);
2736         case EXPR_SELECT:
2737                 return select_to_firm(&expression->select);
2738         case EXPR_CLASSIFY_TYPE:
2739                 return classify_type_to_firm(&expression->classify_type);
2740         case EXPR_FUNCTION:
2741         case EXPR_PRETTY_FUNCTION:
2742                 return function_name_to_firm(&expression->string);
2743         case EXPR_STATEMENT:
2744                 return statement_expression_to_firm(&expression->statement);
2745         case EXPR_VA_START:
2746                 return va_start_expression_to_firm(&expression->va_starte);
2747         case EXPR_VA_ARG:
2748                 return va_arg_expression_to_firm(&expression->va_arge);
2749         case EXPR_BUILTIN_SYMBOL:
2750                 panic("unimplemented expression found");
2751         case EXPR_BUILTIN_CONSTANT_P:
2752                 return builtin_constant_to_firm(&expression->builtin_constant);
2753         case EXPR_BUILTIN_PREFETCH:
2754                 return builtin_prefetch_to_firm(&expression->builtin_prefetch);
2755         case EXPR_OFFSETOF:
2756                 return offsetof_to_firm(&expression->offsetofe);
2757         case EXPR_COMPOUND_LITERAL:
2758                 return compound_literal_to_firm(&expression->compound_literal);
2759
2760         case EXPR_UNKNOWN:
2761         case EXPR_INVALID:
2762                 break;
2763         }
2764         panic("invalid expression found");
2765 }
2766
2767 static ir_node *expression_to_firm(const expression_t *expression)
2768 {
2769         ir_node *res = _expression_to_firm(expression);
2770
2771         if(res != NULL && get_irn_mode(res) == mode_b) {
2772                 ir_mode *mode = get_ir_mode(expression->base.type);
2773                 if(is_Const(res)) {
2774                         if(is_Const_null(res)) {
2775                                 return new_Const_long(mode, 0);
2776                         } else {
2777                                 assert(is_Const_one(res));
2778                                 return new_Const_long(mode, 1);
2779                         }
2780                 }
2781
2782                 dbg_info *dbgi        = get_dbg_info(&expression->base.source_position);
2783                 return produce_condition_result(expression, dbgi);
2784         }
2785
2786         return res;
2787 }
2788
2789 static ir_node *expression_to_modeb(const expression_t *expression)
2790 {
2791         ir_node *res = _expression_to_firm(expression);
2792         res          = create_conv(NULL, res, mode_b);
2793
2794         return res;
2795 }
2796
2797 /**
2798  * create a short-circuit expression evaluation that tries to construct
2799  * efficient control flow structures for &&, || and ! expressions
2800  */
2801 static void create_condition_evaluation(const expression_t *expression,
2802                                         ir_node *true_block,
2803                                         ir_node *false_block)
2804 {
2805         switch(expression->kind) {
2806         case EXPR_UNARY_NOT: {
2807                 const unary_expression_t *unary_expression = &expression->unary;
2808                 create_condition_evaluation(unary_expression->value, false_block,
2809                                             true_block);
2810                 return;
2811         }
2812         case EXPR_BINARY_LOGICAL_AND: {
2813                 const binary_expression_t *binary_expression = &expression->binary;
2814
2815                 ir_node *cur_block   = get_cur_block();
2816                 ir_node *extra_block = new_immBlock();
2817                 set_cur_block(cur_block);
2818                 create_condition_evaluation(binary_expression->left, extra_block,
2819                                             false_block);
2820                 mature_immBlock(extra_block);
2821                 set_cur_block(extra_block);
2822                 create_condition_evaluation(binary_expression->right, true_block,
2823                                             false_block);
2824                 return;
2825         }
2826         case EXPR_BINARY_LOGICAL_OR: {
2827                 const binary_expression_t *binary_expression = &expression->binary;
2828
2829                 ir_node *cur_block   = get_cur_block();
2830                 ir_node *extra_block = new_immBlock();
2831                 set_cur_block(cur_block);
2832                 create_condition_evaluation(binary_expression->left, true_block,
2833                                             extra_block);
2834                 mature_immBlock(extra_block);
2835                 set_cur_block(extra_block);
2836                 create_condition_evaluation(binary_expression->right, true_block,
2837                                             false_block);
2838                 return;
2839         }
2840         default:
2841                 break;
2842         }
2843
2844         dbg_info *dbgi       = get_dbg_info(&expression->base.source_position);
2845         ir_node  *condition  = expression_to_modeb(expression);
2846         ir_node  *cond       = new_d_Cond(dbgi, condition);
2847         ir_node  *true_proj  = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true);
2848         ir_node  *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false);
2849
2850         /* set branch prediction info based on __builtin_expect */
2851         if(expression->kind == EXPR_BINARY_BUILTIN_EXPECT) {
2852                 long               cnst = fold_constant(expression->binary.right);
2853                 cond_jmp_predicate pred;
2854
2855                 if(cnst == 0) {
2856                         pred = COND_JMP_PRED_FALSE;
2857                 } else {
2858                         pred = COND_JMP_PRED_TRUE;
2859                 }
2860                 set_Cond_jmp_pred(cond, pred);
2861         }
2862
2863         add_immBlock_pred(true_block, true_proj);
2864         add_immBlock_pred(false_block, false_proj);
2865
2866         set_cur_block(NULL);
2867 }
2868
2869
2870
2871 static void create_declaration_entity(declaration_t *declaration,
2872                                       declaration_kind_t declaration_kind,
2873                                       ir_type *parent_type)
2874 {
2875         ident     *const id     = new_id_from_str(declaration->symbol->string);
2876         ir_type   *const irtype = get_ir_type(declaration->type);
2877         dbg_info  *const dbgi   = get_dbg_info(&declaration->source_position);
2878         ir_entity *const entity = new_d_entity(parent_type, id, irtype, dbgi);
2879         set_entity_ld_ident(entity, id);
2880
2881         declaration->declaration_kind = (unsigned char) declaration_kind;
2882         declaration->v.entity         = entity;
2883         set_entity_variability(entity, variability_uninitialized);
2884         if(parent_type == get_tls_type())
2885                 set_entity_allocation(entity, allocation_automatic);
2886         else if(declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE)
2887                 set_entity_allocation(entity, allocation_static);
2888         /* TODO: visibility? */
2889 }
2890
2891
2892 typedef struct type_path_entry_t type_path_entry_t;
2893 struct type_path_entry_t {
2894         type_t           *type;
2895         ir_initializer_t *initializer;
2896         size_t            index;
2897         declaration_t    *compound_entry;
2898 };
2899
2900 typedef struct type_path_t type_path_t;
2901 struct type_path_t {
2902         type_path_entry_t *path;
2903         type_t            *top_type;
2904         bool               invalid;
2905 };
2906
2907 static __attribute__((unused)) void debug_print_type_path(const type_path_t *path)
2908 {
2909         size_t len = ARR_LEN(path->path);
2910
2911         for(size_t i = 0; i < len; ++i) {
2912                 const type_path_entry_t *entry = & path->path[i];
2913
2914                 type_t *type = skip_typeref(entry->type);
2915                 if(is_type_compound(type)) {
2916                         fprintf(stderr, ".%s", entry->compound_entry->symbol->string);
2917                 } else if(is_type_array(type)) {
2918                         fprintf(stderr, "[%u]", entry->index);
2919                 } else {
2920                         fprintf(stderr, "-INVALID-");
2921                 }
2922         }
2923         fprintf(stderr, "  (");
2924         print_type(path->top_type);
2925         fprintf(stderr, ")");
2926 }
2927
2928 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2929 {
2930         size_t len = ARR_LEN(path->path);
2931         assert(len > 0);
2932         return & path->path[len-1];
2933 }
2934
2935 static type_path_entry_t *append_to_type_path(type_path_t *path)
2936 {
2937         size_t len = ARR_LEN(path->path);
2938         ARR_RESIZE(type_path_entry_t, path->path, len+1);
2939
2940         type_path_entry_t *result = & path->path[len];
2941         memset(result, 0, sizeof(result[0]));
2942         return result;
2943 }
2944
2945 static size_t get_compound_size(const compound_type_t *type)
2946 {
2947         declaration_t *declaration = type->declaration;
2948         declaration_t *member      = declaration->scope.declarations;
2949         size_t         size        = 0;
2950         for( ; member != NULL; member = member->next) {
2951                 ++size;
2952         }
2953         /* TODO: cache results? */
2954
2955         return size;
2956 }
2957
2958 static ir_initializer_t *get_initializer_entry(type_path_t *path)
2959 {
2960         type_t *orig_top_type = path->top_type;
2961         type_t *top_type      = skip_typeref(orig_top_type);
2962
2963         assert(is_type_compound(top_type) || is_type_array(top_type));
2964
2965         if(ARR_LEN(path->path) == 0) {
2966                 return NULL;
2967         } else {
2968                 type_path_entry_t *top         = get_type_path_top(path);
2969                 ir_initializer_t  *initializer = top->initializer;
2970                 return get_initializer_compound_value(initializer, top->index);
2971         }
2972 }
2973
2974 static void descend_into_subtype(type_path_t *path)
2975 {
2976         type_t *orig_top_type = path->top_type;
2977         type_t *top_type      = skip_typeref(orig_top_type);
2978
2979         assert(is_type_compound(top_type) || is_type_array(top_type));
2980
2981         ir_initializer_t *initializer = get_initializer_entry(path);
2982
2983         type_path_entry_t *top = append_to_type_path(path);
2984         top->type              = top_type;
2985
2986         size_t len;
2987
2988         if(is_type_compound(top_type)) {
2989                 declaration_t *declaration = top_type->compound.declaration;
2990                 declaration_t *entry       = declaration->scope.declarations;
2991
2992                 top->compound_entry = entry;
2993                 top->index          = 0;
2994                 path->top_type      = entry->type;
2995                 len                 = get_compound_size(&top_type->compound);
2996         } else {
2997                 assert(is_type_array(top_type));
2998                 assert(top_type->array.size > 0);
2999
3000                 top->index     = 0;
3001                 path->top_type = top_type->array.element_type;
3002                 len            = top_type->array.size;
3003         }
3004         if(initializer == NULL
3005                         || get_initializer_kind(initializer) == IR_INITIALIZER_NULL) {
3006                 initializer = create_initializer_compound(len);
3007                 /* we have to set the entry at the 2nd latest path entry... */
3008                 size_t path_len = ARR_LEN(path->path);
3009                 assert(path_len >= 1);
3010                 if(path_len > 1) {
3011                         type_path_entry_t *entry        = & path->path[path_len-2];
3012                         ir_initializer_t  *tinitializer = entry->initializer;
3013                         set_initializer_compound_value(tinitializer, entry->index,
3014                                                        initializer);
3015                 }
3016         }
3017         top->initializer = initializer;
3018 }
3019
3020 static void ascend_from_subtype(type_path_t *path)
3021 {
3022         type_path_entry_t *top = get_type_path_top(path);
3023
3024         path->top_type = top->type;
3025
3026         size_t len = ARR_LEN(path->path);
3027         ARR_RESIZE(type_path_entry_t, path->path, len-1);
3028 }
3029
3030 static void walk_designator(type_path_t *path, const designator_t *designator)
3031 {
3032         /* designators start at current object type */
3033         ARR_RESIZE(type_path_entry_t, path->path, 1);
3034
3035         for( ; designator != NULL; designator = designator->next) {
3036                 type_path_entry_t *top         = get_type_path_top(path);
3037                 type_t            *orig_type   = top->type;
3038                 type_t            *type        = skip_typeref(orig_type);
3039
3040                 if(designator->symbol != NULL) {
3041                         assert(is_type_compound(type));
3042                         size_t    index  = 0;
3043                         symbol_t *symbol = designator->symbol;
3044
3045                         declaration_t *declaration = type->compound.declaration;
3046                         declaration_t *iter        = declaration->scope.declarations;
3047                         for( ; iter != NULL; iter = iter->next, ++index) {
3048                                 if(iter->symbol == symbol) {
3049                                         break;
3050                                 }
3051                         }
3052                         assert(iter != NULL);
3053
3054                         top->type           = orig_type;
3055                         top->compound_entry = iter;
3056                         top->index          = index;
3057                         orig_type           = iter->type;
3058                 } else {
3059                         expression_t *array_index = designator->array_index;
3060                         assert(designator->array_index != NULL);
3061                         assert(is_type_array(type));
3062                         assert(is_type_valid(array_index->base.type));
3063
3064                         long index = fold_constant(array_index);
3065                         assert(index >= 0);
3066 #ifndef NDEBUG
3067                         if(type->array.size_constant == 1) {
3068                                 long array_size = type->array.size;
3069                                 assert(index < array_size);
3070                         }
3071 #endif
3072
3073                         top->type  = orig_type;
3074                         top->index = (size_t) index;
3075                         orig_type  = type->array.element_type;
3076                 }
3077                 path->top_type = orig_type;
3078
3079                 if(designator->next != NULL) {
3080                         descend_into_subtype(path);
3081                 }
3082         }
3083
3084         path->invalid  = false;
3085 }
3086
3087 static void advance_current_object(type_path_t *path)
3088 {
3089         if(path->invalid) {
3090                 /* TODO: handle this... */
3091                 panic("invalid initializer in ast2firm (excessive elements)");
3092                 return;
3093         }
3094
3095         type_path_entry_t *top = get_type_path_top(path);
3096
3097         type_t *type = skip_typeref(top->type);
3098         if(is_type_union(type)) {
3099                 top->compound_entry = NULL;
3100         } else if(is_type_struct(type)) {
3101                 declaration_t *entry = top->compound_entry;
3102
3103                 top->index++;
3104                 entry               = entry->next;
3105                 top->compound_entry = entry;
3106                 if(entry != NULL) {
3107                         path->top_type = entry->type;
3108                         return;
3109                 }
3110         } else {
3111                 assert(is_type_array(type));
3112
3113                 top->index++;
3114                 if(!type->array.size_constant || top->index < type->array.size) {
3115                         return;
3116                 }
3117         }
3118
3119         /* we're past the last member of the current sub-aggregate, try if we
3120          * can ascend in the type hierarchy and continue with another subobject */
3121         size_t len = ARR_LEN(path->path);
3122
3123         if(len > 1) {
3124                 ascend_from_subtype(path);
3125                 advance_current_object(path);
3126         } else {
3127                 path->invalid = true;
3128         }
3129 }
3130
3131
3132 static ir_initializer_t *create_ir_initializer(
3133                 const initializer_t *initializer, type_t *type);
3134
3135 static ir_initializer_t *create_ir_initializer_value(
3136                 const initializer_value_t *initializer)
3137 {
3138         ir_node *value = expression_to_firm(initializer->value);
3139         return create_initializer_const(value);
3140 }
3141
3142 static ir_initializer_t *create_ir_initializer_list(
3143                 const initializer_list_t *initializer, type_t *type)
3144 {
3145         type_path_t path;
3146         memset(&path, 0, sizeof(path));
3147         path.top_type = type;
3148         path.path     = NEW_ARR_F(type_path_entry_t, 0);
3149
3150         descend_into_subtype(&path);
3151
3152         for(size_t i = 0; i < initializer->len; ++i) {
3153                 const initializer_t *sub_initializer = initializer->initializers[i];
3154
3155                 if(sub_initializer->kind == INITIALIZER_DESIGNATOR) {
3156                         walk_designator(&path, sub_initializer->designator.designator);
3157                         continue;
3158                 }
3159
3160                 if(sub_initializer->kind == INITIALIZER_VALUE) {
3161                         /* we might have to descend into types until we're at a scalar
3162                          * type */
3163                         while(true) {
3164                                 type_t *orig_top_type = path.top_type;
3165                                 type_t *top_type      = skip_typeref(orig_top_type);
3166
3167                                 if(is_type_scalar(top_type))
3168                                         break;
3169                                 descend_into_subtype(&path);
3170                         }
3171                 }
3172
3173                 ir_initializer_t *sub_irinitializer
3174                         = create_ir_initializer(sub_initializer, path.top_type);
3175
3176                 size_t path_len = ARR_LEN(path.path);
3177                 assert(path_len >= 1);
3178                 type_path_entry_t *entry        = & path.path[path_len-1];
3179                 ir_initializer_t  *tinitializer = entry->initializer;
3180                 set_initializer_compound_value(tinitializer, entry->index,
3181                                                sub_irinitializer);
3182
3183                 advance_current_object(&path);
3184         }
3185
3186         assert(ARR_LEN(path.path) >= 1);
3187         ir_initializer_t *result = path.path[0].initializer;
3188         DEL_ARR_F(path.path);
3189
3190         return result;
3191 }
3192
3193 static ir_initializer_t *create_ir_initializer_string(
3194                 const initializer_string_t *initializer, type_t *type)
3195 {
3196         size_t            string_len    = initializer->string.size;
3197         assert(type->kind == TYPE_ARRAY && type->array.size_constant);
3198         size_t            len           = type->array.size;
3199         ir_initializer_t *irinitializer = create_initializer_compound(len);
3200
3201         const char *string = initializer->string.begin;
3202         ir_mode    *mode   = get_type_mode(ir_type_const_char);
3203
3204         for(size_t i = 0; i < len; ++i) {
3205                 char c = 0;
3206                 if(i < string_len)
3207                         c = string[i];
3208
3209                 tarval           *tv = new_tarval_from_long(string[i], mode);
3210                 ir_initializer_t *char_initializer = create_initializer_tarval(tv);
3211
3212                 set_initializer_compound_value(irinitializer, i, char_initializer);
3213         }
3214
3215         return irinitializer;
3216 }
3217
3218 static ir_initializer_t *create_ir_initializer_wide_string(
3219                 const initializer_wide_string_t *initializer, type_t *type)
3220 {
3221         size_t            string_len    = initializer->string.size;
3222         assert(type->kind == TYPE_ARRAY && type->array.size_constant);
3223         size_t            len           = type->array.size;
3224         ir_initializer_t *irinitializer = create_initializer_compound(len);
3225
3226         const wchar_rep_t *string = initializer->string.begin;
3227         ir_mode           *mode   = get_type_mode(ir_type_wchar_t);
3228
3229         for(size_t i = 0; i < len; ++i) {
3230                 wchar_rep_t c = 0;
3231                 if(i < string_len) {
3232                         c = string[i];
3233                 }
3234                 tarval *tv = new_tarval_from_long(string[i], mode);
3235                 ir_initializer_t *char_initializer = create_initializer_tarval(tv);
3236
3237                 set_initializer_compound_value(irinitializer, i, char_initializer);
3238         }
3239
3240         return irinitializer;
3241 }
3242
3243 static ir_initializer_t *create_ir_initializer(
3244                 const initializer_t *initializer, type_t *type)
3245 {
3246         switch(initializer->kind) {
3247                 case INITIALIZER_STRING:
3248                         return create_ir_initializer_string(&initializer->string, type);
3249
3250                 case INITIALIZER_WIDE_STRING:
3251                         return create_ir_initializer_wide_string(&initializer->wide_string,
3252                                                                  type);
3253
3254                 case INITIALIZER_LIST:
3255                         return create_ir_initializer_list(&initializer->list, type);
3256
3257                 case INITIALIZER_VALUE:
3258                         return create_ir_initializer_value(&initializer->value);
3259
3260                 case INITIALIZER_DESIGNATOR:
3261                         panic("unexpected designator initializer found");
3262         }
3263         panic("unknown initializer");
3264 }
3265
3266 static void create_dynamic_initializer_sub(ir_initializer_t *initializer,
3267                 ir_type *type, dbg_info *dbgi, ir_node *base_addr)
3268 {
3269         switch(get_initializer_kind(initializer)) {
3270         case IR_INITIALIZER_NULL: {
3271                 ir_mode *mode = get_type_mode(type);
3272                 /* TODO: implement this for compound types... */
3273                 assert(type != NULL);
3274                 tarval  *zero = get_mode_null(mode);
3275                 ir_node *cnst = new_d_Const(dbgi, mode, zero);
3276
3277                 /* TODO: bitfields */
3278                 ir_node *mem    = get_store();
3279                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, cnst);
3280                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
3281                 set_store(proj_m);
3282                 return;
3283         }
3284         case IR_INITIALIZER_CONST: {
3285                 ir_node *node = get_initializer_const_value(initializer);
3286                 ir_mode *mode = get_irn_mode(node);
3287                 assert(get_type_mode(type) == mode);
3288
3289                 /* TODO: bitfields... */
3290                 ir_node *mem    = get_store();
3291                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, node);
3292                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
3293                 set_store(proj_m);
3294                 return;
3295         }
3296         case IR_INITIALIZER_TARVAL: {
3297                 tarval  *tv   = get_initializer_tarval_value(initializer);
3298                 ir_mode *mode = get_tarval_mode(tv);
3299                 ir_node *cnst = new_d_Const(dbgi, mode, tv);
3300                 assert(get_type_mode(type) == mode);
3301
3302                 /* TODO: bitfields... */
3303                 ir_node *mem    = get_store();
3304                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, cnst);
3305                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
3306                 set_store(proj_m);
3307                 return;
3308         }
3309         case IR_INITIALIZER_COMPOUND: {
3310                 assert(is_compound_type(type));
3311                 int n_members;
3312                 if(is_Array_type(type)) {
3313                         assert(has_array_upper_bound(type, 0));
3314                         n_members = get_array_upper_bound_int(type, 0);
3315                 } else {
3316                         n_members = get_compound_n_members(type);
3317                 }
3318
3319                 if(get_initializer_compound_n_entries(initializer)
3320                                 != (unsigned) n_members)
3321                         panic("initializer doesn't match compound type");
3322
3323                 for(int i = 0; i < n_members; ++i) {
3324                         ir_node *addr;
3325                         ir_type *irtype;
3326                         if(is_Array_type(type)) {
3327                                 ir_entity *entity   = get_array_element_entity(type);
3328                                 tarval    *index_tv = new_tarval_from_long(i, mode_uint);
3329                                 ir_node   *cnst     = new_d_Const(dbgi, mode_uint, index_tv);
3330                                 ir_node   *in[1]    = { cnst };
3331                                 irtype = get_array_element_type(type);
3332                                 addr   = new_d_Sel(dbgi, new_NoMem(), base_addr, 1, in, entity);
3333                         } else {
3334                                 ir_entity *member = get_compound_member(type, i);
3335
3336                                 irtype = get_entity_type(member);
3337                                 addr   = new_d_simpleSel(dbgi, new_NoMem(), base_addr, member);
3338                         }
3339
3340                         ir_initializer_t *sub_init
3341                                 = get_initializer_compound_value(initializer, i);
3342
3343                         create_dynamic_initializer_sub(sub_init, irtype, dbgi, addr);
3344                 }
3345                 return;
3346         }
3347         }
3348
3349         panic("invalid IR_INITIALIZER found");
3350 }
3351
3352 static void create_dynamic_initializer(ir_initializer_t *initializer,
3353                 dbg_info *dbgi, ir_entity *entity)
3354 {
3355         ir_node *frame     = get_local_frame(entity);
3356         ir_node *base_addr = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
3357         ir_type *type      = get_entity_type(entity);
3358
3359         create_dynamic_initializer_sub(initializer, type, dbgi, base_addr);
3360 }
3361
3362 static void create_local_initializer(initializer_t *initializer, dbg_info *dbgi,
3363                                      ir_entity *entity, type_t *type)
3364 {
3365         ir_node *memory = get_store();
3366         ir_node *nomem  = new_NoMem();
3367         ir_node *frame  = get_irg_frame(current_ir_graph);
3368         ir_node *addr   = new_d_simpleSel(dbgi, nomem, frame, entity);
3369
3370         if(initializer->kind == INITIALIZER_VALUE) {
3371                 initializer_value_t *initializer_value = &initializer->value;
3372
3373                 ir_node *value = expression_to_firm(initializer_value->value);
3374                 type = skip_typeref(type);
3375                 assign_value(dbgi, addr, type, value);
3376                 return;
3377         }
3378
3379         if(!is_constant_initializer(initializer)) {
3380                 ir_initializer_t *irinitializer
3381                         = create_ir_initializer(initializer, type);
3382
3383                 create_dynamic_initializer(irinitializer, dbgi, entity);
3384                 return;
3385         }
3386
3387         /* create the ir_initializer */
3388         ir_graph *const old_current_ir_graph = current_ir_graph;
3389         current_ir_graph = get_const_code_irg();
3390
3391         ir_initializer_t *irinitializer = create_ir_initializer(initializer, type);
3392
3393         assert(current_ir_graph == get_const_code_irg());
3394         current_ir_graph = old_current_ir_graph;
3395
3396         /* create a "template" entity which is copied to the entity on the stack */
3397         ident     *const id          = unique_ident("initializer");
3398         ir_type   *const irtype      = get_ir_type(type);
3399         ir_type   *const global_type = get_glob_type();
3400         ir_entity *const init_entity = new_d_entity(global_type, id, irtype, dbgi);
3401         set_entity_ld_ident(init_entity, id);
3402
3403         set_entity_variability(init_entity, variability_initialized);
3404         set_entity_visibility(init_entity, visibility_local);
3405         set_entity_allocation(init_entity, allocation_static);
3406
3407         set_entity_initializer(init_entity, irinitializer);
3408
3409         ir_node *const src_addr = create_symconst(dbgi, mode_P_data, init_entity);
3410         ir_node *const copyb    = new_d_CopyB(dbgi, memory, addr, src_addr, irtype);
3411
3412         ir_node *const copyb_mem = new_Proj(copyb, mode_M, pn_CopyB_M_regular);
3413         set_store(copyb_mem);
3414 }
3415
3416 static void create_initializer_local_variable_entity(declaration_t *declaration)
3417 {
3418         initializer_t *initializer = declaration->init.initializer;
3419         dbg_info      *dbgi        = get_dbg_info(&declaration->source_position);
3420         ir_entity     *entity      = declaration->v.entity;
3421         type_t        *type        = declaration->type;
3422         create_local_initializer(initializer, dbgi, entity, type);
3423 }
3424
3425 static void create_declaration_initializer(declaration_t *declaration)
3426 {
3427         initializer_t *initializer = declaration->init.initializer;
3428         if(initializer == NULL)
3429                 return;
3430
3431         declaration_kind_t declaration_kind
3432                 = (declaration_kind_t) declaration->declaration_kind;
3433         if(declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE_ENTITY) {
3434                 create_initializer_local_variable_entity(declaration);
3435                 return;
3436         }
3437
3438         if(initializer->kind == INITIALIZER_VALUE) {
3439                 initializer_value_t *initializer_value = &initializer->value;
3440
3441                 ir_node *value = expression_to_firm(initializer_value->value);
3442
3443                 if(declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE) {
3444                         set_value(declaration->v.value_number, value);
3445                 } else {
3446                         assert(declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
3447
3448                         ir_entity *entity = declaration->v.entity;
3449
3450                         set_entity_variability(entity, variability_initialized);
3451                         set_atomic_ent_value(entity, value);
3452                 }
3453         } else {
3454                 assert(declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE_ENTITY
3455                                 || declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
3456
3457                 ir_entity        *entity        = declaration->v.entity;
3458                 ir_initializer_t *irinitializer
3459                         = create_ir_initializer(initializer, declaration->type);
3460
3461                 set_entity_variability(entity, variability_initialized);
3462                 set_entity_initializer(entity, irinitializer);
3463         }
3464 }
3465
3466 /**
3467  * Creates a Firm local variable from a declaration.
3468  */
3469 static void create_local_variable(declaration_t *declaration)
3470 {
3471         assert(declaration->declaration_kind == DECLARATION_KIND_UNKNOWN);
3472
3473         bool needs_entity = declaration->address_taken;
3474         type_t *type = skip_typeref(declaration->type);
3475
3476         if(is_type_array(type) || is_type_compound(type)) {
3477                 needs_entity = true;
3478         }
3479
3480         if(needs_entity) {
3481                 ir_type *frame_type = get_irg_frame_type(current_ir_graph);
3482                 create_declaration_entity(declaration,
3483                                           DECLARATION_KIND_LOCAL_VARIABLE_ENTITY,
3484                                           frame_type);
3485         } else {
3486                 declaration->declaration_kind = DECLARATION_KIND_LOCAL_VARIABLE;
3487                 declaration->v.value_number   = next_value_number_function;
3488                 set_irg_loc_description(current_ir_graph, next_value_number_function, declaration);
3489                 ++next_value_number_function;
3490         }
3491
3492         create_declaration_initializer(declaration);
3493 }
3494
3495 static void create_local_static_variable(declaration_t *declaration)
3496 {
3497         assert(declaration->declaration_kind == DECLARATION_KIND_UNKNOWN);
3498
3499         type_t    *const type        = skip_typeref(declaration->type);
3500         ir_type   *const global_type = get_glob_type();
3501         ident     *const id          = unique_ident(declaration->symbol->string);
3502         ir_type   *const irtype      = get_ir_type(type);
3503         dbg_info  *const dbgi        = get_dbg_info(&declaration->source_position);
3504         ir_entity *const entity      = new_d_entity(global_type, id, irtype, dbgi);
3505         set_entity_ld_ident(entity, id);
3506
3507         declaration->declaration_kind = DECLARATION_KIND_GLOBAL_VARIABLE;
3508         declaration->v.entity         = entity;
3509         set_entity_variability(entity, variability_uninitialized);
3510         set_entity_visibility(entity, visibility_local);
3511         set_entity_allocation(entity, allocation_static);
3512
3513         ir_graph *const old_current_ir_graph = current_ir_graph;
3514         current_ir_graph = get_const_code_irg();
3515
3516         create_declaration_initializer(declaration);
3517
3518         assert(current_ir_graph == get_const_code_irg());
3519         current_ir_graph = old_current_ir_graph;
3520 }
3521
3522
3523
3524 static void return_statement_to_firm(return_statement_t *statement)
3525 {
3526         if(get_cur_block() == NULL)
3527                 return;
3528
3529         dbg_info *dbgi        = get_dbg_info(&statement->base.source_position);
3530         ir_type  *func_irtype = get_ir_type(current_function_decl->type);
3531
3532
3533         ir_node *in[1];
3534         int      in_len;
3535         if(get_method_n_ress(func_irtype) > 0) {
3536                 ir_type *res_type = get_method_res_type(func_irtype, 0);
3537
3538                 if(statement->value != NULL) {
3539                         ir_node *node = expression_to_firm(statement->value);
3540                         node  = do_strict_conv(dbgi, node);
3541                         in[0] = node;
3542                 } else {
3543                         ir_mode *mode;
3544                         if(is_compound_type(res_type)) {
3545                                 mode = mode_P_data;
3546                         } else {
3547                                 mode = get_type_mode(res_type);
3548                         }
3549                         in[0] = new_Unknown(mode);
3550                 }
3551                 in_len = 1;
3552         } else {
3553                 /* build return_value for its side effects */
3554                 if(statement->value != NULL) {
3555                         expression_to_firm(statement->value);
3556                 }
3557                 in_len = 0;
3558         }
3559
3560         ir_node  *store = get_store();
3561         ir_node  *ret   = new_d_Return(dbgi, store, in_len, in);
3562
3563         ir_node *end_block = get_irg_end_block(current_ir_graph);
3564         add_immBlock_pred(end_block, ret);
3565
3566         set_cur_block(NULL);
3567 }
3568
3569 static ir_node *expression_statement_to_firm(expression_statement_t *statement)
3570 {
3571         if(get_cur_block() == NULL)
3572                 return NULL;
3573
3574         return expression_to_firm(statement->expression);
3575 }
3576
3577 static ir_node *compound_statement_to_firm(compound_statement_t *compound)
3578 {
3579         ir_node     *result    = NULL;
3580         statement_t *statement = compound->statements;
3581         for( ; statement != NULL; statement = statement->base.next) {
3582                 //context2firm(&statement->scope);
3583
3584                 if(statement->base.next == NULL
3585                                 && statement->kind == STATEMENT_EXPRESSION) {
3586                         result = expression_statement_to_firm(
3587                                         &statement->expression);
3588                         break;
3589                 }
3590                 statement_to_firm(statement);
3591         }
3592
3593         return result;
3594 }
3595
3596 static void create_global_variable(declaration_t *declaration)
3597 {
3598         ir_visibility  vis;
3599         ir_type       *var_type;
3600         switch ((storage_class_tag_t)declaration->storage_class) {
3601                 case STORAGE_CLASS_STATIC:
3602                         vis = visibility_local;
3603                         goto global_var;
3604
3605                 case STORAGE_CLASS_EXTERN:
3606                         vis = visibility_external_allocated;
3607                         goto global_var;
3608
3609                 case STORAGE_CLASS_NONE:
3610                         vis = visibility_external_visible;
3611                         goto global_var;
3612
3613                 case STORAGE_CLASS_THREAD:
3614                         vis = visibility_external_visible;
3615                         goto tls_var;
3616
3617                 case STORAGE_CLASS_THREAD_EXTERN:
3618                         vis = visibility_external_allocated;
3619                         goto tls_var;
3620
3621                 case STORAGE_CLASS_THREAD_STATIC:
3622                         vis = visibility_local;
3623                         goto tls_var;
3624
3625 tls_var:
3626                         var_type = get_tls_type();
3627                         goto create_var;
3628
3629 global_var:
3630                         var_type = get_glob_type();
3631                         goto create_var;
3632
3633 create_var:
3634                         create_declaration_entity(declaration,
3635                                                   DECLARATION_KIND_GLOBAL_VARIABLE,
3636                                                   var_type);
3637                         set_entity_visibility(declaration->v.entity, vis);
3638
3639                         return;
3640
3641                 case STORAGE_CLASS_TYPEDEF:
3642                 case STORAGE_CLASS_AUTO:
3643                 case STORAGE_CLASS_REGISTER:
3644                 case STORAGE_CLASS_ENUM_ENTRY:
3645                         break;
3646         }
3647         panic("Invalid storage class for global variable");
3648 }
3649
3650 static void create_local_declaration(declaration_t *declaration)
3651 {
3652         if(declaration->symbol == NULL)
3653                 return;
3654
3655         type_t *type = skip_typeref(declaration->type);
3656
3657         switch ((storage_class_tag_t) declaration->storage_class) {
3658         case STORAGE_CLASS_STATIC:
3659                 create_local_static_variable(declaration);
3660                 return;
3661         case STORAGE_CLASS_EXTERN:
3662                 create_global_variable(declaration);
3663                 create_declaration_initializer(declaration);
3664                 return;
3665         case STORAGE_CLASS_NONE:
3666         case STORAGE_CLASS_AUTO:
3667         case STORAGE_CLASS_REGISTER:
3668                 if(is_type_function(type)) {
3669                         if(declaration->init.statement != NULL) {
3670                                 panic("nested functions not supported yet");
3671                         } else {
3672                                 get_function_entity(declaration);
3673                         }
3674                 } else {
3675                         create_local_variable(declaration);
3676                 }
3677                 return;
3678         case STORAGE_CLASS_ENUM_ENTRY:
3679         case STORAGE_CLASS_TYPEDEF:
3680         case STORAGE_CLASS_THREAD:
3681         case STORAGE_CLASS_THREAD_EXTERN:
3682         case STORAGE_CLASS_THREAD_STATIC:
3683                 return;
3684         }
3685         panic("invalid storage class found");
3686 }
3687
3688 static void declaration_statement_to_firm(declaration_statement_t *statement)
3689 {
3690         declaration_t *declaration = statement->declarations_begin;
3691         declaration_t *end         = statement->declarations_end->next;
3692         for( ; declaration != end; declaration = declaration->next) {
3693                 if(declaration->namespc != NAMESPACE_NORMAL)
3694                         continue;
3695                 create_local_declaration(declaration);
3696         }
3697 }
3698
3699 static void if_statement_to_firm(if_statement_t *statement)
3700 {
3701         ir_node *cur_block = get_cur_block();
3702
3703         ir_node *fallthrough_block = new_immBlock();
3704
3705         /* the true (blocks) */
3706         ir_node *true_block;
3707         if (statement->true_statement != NULL) {
3708                 true_block = new_immBlock();
3709                 statement_to_firm(statement->true_statement);
3710                 if(get_cur_block() != NULL) {
3711                         ir_node *jmp = new_Jmp();
3712                         add_immBlock_pred(fallthrough_block, jmp);
3713                 }
3714         } else {
3715                 true_block = fallthrough_block;
3716         }
3717
3718         /* the false (blocks) */
3719         ir_node *false_block;
3720         if(statement->false_statement != NULL) {
3721                 false_block = new_immBlock();
3722
3723                 statement_to_firm(statement->false_statement);
3724                 if(get_cur_block() != NULL) {
3725                         ir_node *jmp = new_Jmp();
3726                         add_immBlock_pred(fallthrough_block, jmp);
3727                 }
3728         } else {
3729                 false_block = fallthrough_block;
3730         }
3731
3732         /* create the condition */
3733         if(cur_block != NULL) {
3734                 set_cur_block(cur_block);
3735                 create_condition_evaluation(statement->condition, true_block,
3736                                             false_block);
3737         }
3738
3739         mature_immBlock(true_block);
3740         if(false_block != fallthrough_block) {
3741                 mature_immBlock(false_block);
3742         }
3743         mature_immBlock(fallthrough_block);
3744
3745         set_cur_block(fallthrough_block);
3746 }
3747
3748 static void while_statement_to_firm(while_statement_t *statement)
3749 {
3750         ir_node *jmp = NULL;
3751         if(get_cur_block() != NULL) {
3752                 jmp = new_Jmp();
3753         }
3754
3755         /* create the header block */
3756         ir_node *header_block = new_immBlock();
3757         if(jmp != NULL) {
3758                 add_immBlock_pred(header_block, jmp);
3759         }
3760
3761         /* the false block */
3762         ir_node *false_block = new_immBlock();
3763
3764         /* the loop body */
3765         ir_node *body_block;
3766         if (statement->body != NULL) {
3767                 ir_node *old_continue_label = continue_label;
3768                 ir_node *old_break_label    = break_label;
3769                 continue_label              = header_block;
3770                 break_label                 = false_block;
3771
3772                 body_block = new_immBlock();
3773                 statement_to_firm(statement->body);
3774
3775                 assert(continue_label == header_block);
3776                 assert(break_label    == false_block);
3777                 continue_label = old_continue_label;
3778                 break_label    = old_break_label;
3779
3780                 if(get_cur_block() != NULL) {
3781                         jmp = new_Jmp();
3782                         add_immBlock_pred(header_block, jmp);
3783                 }
3784         } else {
3785                 body_block = header_block;
3786         }
3787
3788         /* create the condition */
3789         set_cur_block(header_block);
3790
3791         create_condition_evaluation(statement->condition, body_block, false_block);
3792         mature_immBlock(body_block);
3793         mature_immBlock(false_block);
3794         mature_immBlock(header_block);
3795
3796         set_cur_block(false_block);
3797 }
3798
3799 static void do_while_statement_to_firm(do_while_statement_t *statement)
3800 {
3801         ir_node *jmp = NULL;
3802         if(get_cur_block() != NULL) {
3803                 jmp = new_Jmp();
3804         }
3805
3806         /* create the header block */
3807         ir_node *header_block = new_immBlock();
3808
3809         /* the false block */
3810         ir_node *false_block = new_immBlock();
3811
3812         /* the loop body */
3813         ir_node *body_block = new_immBlock();
3814         if(jmp != NULL) {
3815                 add_immBlock_pred(body_block, jmp);
3816         }
3817
3818         if (statement->body != NULL) {
3819                 ir_node *old_continue_label = continue_label;
3820                 ir_node *old_break_label    = break_label;
3821                 continue_label              = header_block;
3822                 break_label                 = false_block;
3823
3824                 statement_to_firm(statement->body);
3825
3826                 assert(continue_label == header_block);
3827                 assert(break_label    == false_block);
3828                 continue_label = old_continue_label;
3829                 break_label    = old_break_label;
3830
3831                 if (get_cur_block() == NULL) {
3832                         mature_immBlock(header_block);
3833                         mature_immBlock(body_block);
3834                         mature_immBlock(false_block);
3835                         return;
3836                 }
3837         }
3838
3839         ir_node *body_jmp = new_Jmp();
3840         add_immBlock_pred(header_block, body_jmp);
3841         mature_immBlock(header_block);
3842
3843         /* create the condition */
3844         set_cur_block(header_block);
3845
3846         create_condition_evaluation(statement->condition, body_block, false_block);
3847         mature_immBlock(body_block);
3848         mature_immBlock(false_block);
3849         mature_immBlock(header_block);
3850
3851         set_cur_block(false_block);
3852 }
3853
3854 static void for_statement_to_firm(for_statement_t *statement)
3855 {
3856         ir_node *jmp = NULL;
3857         if (get_cur_block() != NULL) {
3858                 if(statement->initialisation != NULL) {
3859                         expression_to_firm(statement->initialisation);
3860                 }
3861
3862                 /* create declarations */
3863                 declaration_t *declaration = statement->scope.declarations;
3864                 for( ; declaration != NULL; declaration = declaration->next) {
3865                         create_local_declaration(declaration);
3866                 }
3867
3868                 jmp = new_Jmp();
3869         }
3870
3871
3872         /* create the step block */
3873         ir_node *const step_block = new_immBlock();
3874         if (statement->step != NULL) {
3875                 expression_to_firm(statement->step);
3876         }
3877         ir_node *const step_jmp = new_Jmp();
3878
3879         /* create the header block */
3880         ir_node *const header_block = new_immBlock();
3881         if (jmp != NULL) {
3882                 add_immBlock_pred(header_block, jmp);
3883         }
3884         add_immBlock_pred(header_block, step_jmp);
3885
3886         /* the false block */
3887         ir_node *const false_block = new_immBlock();
3888
3889         /* the loop body */
3890         ir_node * body_block;
3891         if (statement->body != NULL) {
3892                 ir_node *const old_continue_label = continue_label;
3893                 ir_node *const old_break_label    = break_label;
3894                 continue_label = step_block;
3895                 break_label    = false_block;
3896
3897                 body_block = new_immBlock();
3898                 statement_to_firm(statement->body);
3899
3900                 assert(continue_label == step_block);
3901                 assert(break_label    == false_block);
3902                 continue_label = old_continue_label;
3903                 break_label    = old_break_label;
3904
3905                 if (get_cur_block() != NULL) {
3906                         jmp = new_Jmp();
3907                         add_immBlock_pred(step_block, jmp);
3908                 }
3909         } else {
3910                 body_block = step_block;
3911         }
3912
3913         /* create the condition */
3914         set_cur_block(header_block);
3915         if (statement->condition != NULL) {
3916                 create_condition_evaluation(statement->condition, body_block,
3917                                             false_block);
3918         } else {
3919                 keep_alive(header_block);
3920                 jmp = new_Jmp();
3921                 add_immBlock_pred(body_block, jmp);
3922         }
3923
3924         mature_immBlock(body_block);
3925         mature_immBlock(false_block);
3926         mature_immBlock(step_block);
3927         mature_immBlock(header_block);
3928         mature_immBlock(false_block);
3929
3930         set_cur_block(false_block);
3931 }
3932
3933 static void create_jump_statement(const statement_t *statement,
3934                                   ir_node *target_block)
3935 {
3936         if(get_cur_block() == NULL)
3937                 return;
3938
3939         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
3940         ir_node  *jump = new_d_Jmp(dbgi);
3941         add_immBlock_pred(target_block, jump);
3942
3943         set_cur_block(NULL);
3944 }
3945
3946 static void switch_statement_to_firm(const switch_statement_t *statement)
3947 {
3948         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
3949
3950         ir_node *expression  = expression_to_firm(statement->expression);
3951         ir_node *cond        = new_d_Cond(dbgi, expression);
3952         ir_node *break_block = new_immBlock();
3953
3954         set_cur_block(NULL);
3955
3956         ir_node *const old_switch_cond       = current_switch_cond;
3957         ir_node *const old_break_label       = break_label;
3958         const bool     old_saw_default_label = saw_default_label;
3959         current_switch_cond                  = cond;
3960         break_label                          = break_block;
3961
3962         if (statement->body != NULL) {
3963                 statement_to_firm(statement->body);
3964         }
3965
3966         if(get_cur_block() != NULL) {
3967                 ir_node *jmp = new_Jmp();
3968                 add_immBlock_pred(break_block, jmp);
3969         }
3970
3971         if (!saw_default_label) {
3972                 set_cur_block(get_nodes_block(cond));
3973                 ir_node *const proj = new_d_defaultProj(dbgi, cond,
3974                                                         MAGIC_DEFAULT_PN_NUMBER);
3975                 add_immBlock_pred(break_block, proj);
3976         }
3977
3978         assert(current_switch_cond == cond);
3979         assert(break_label         == break_block);
3980         current_switch_cond = old_switch_cond;
3981         break_label         = old_break_label;
3982         saw_default_label   = old_saw_default_label;
3983
3984         mature_immBlock(break_block);
3985         set_cur_block(break_block);
3986 }
3987
3988 static void case_label_to_firm(const case_label_statement_t *statement)
3989 {
3990         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
3991
3992         ir_node *const fallthrough = (get_cur_block() == NULL ? NULL : new_Jmp());
3993
3994         /* let's create a node and hope firm constant folding creates a Const
3995          * node... */
3996         ir_node *proj;
3997         ir_node *old_block = get_nodes_block(current_switch_cond);
3998         ir_node *block     = new_immBlock();
3999
4000         set_cur_block(old_block);
4001         if(statement->expression != NULL) {
4002                 long start_pn = fold_constant(statement->expression);
4003                 long end_pn = start_pn;
4004                 if (statement->end_range != NULL) {
4005                         end_pn = fold_constant(statement->end_range);
4006                 }
4007                 assert(start_pn <= end_pn);
4008                 /* create jumps for all cases in the given range */
4009                 for (long pn = start_pn; pn <= end_pn; ++pn) {
4010                         if(pn == MAGIC_DEFAULT_PN_NUMBER) {
4011                                 /* oops someone detected our cheating... */
4012                                 panic("magic default pn used");
4013                         }
4014                         proj = new_d_Proj(dbgi, current_switch_cond, mode_X, pn);
4015                         add_immBlock_pred(block, proj);
4016                 }
4017         } else {
4018                 saw_default_label = true;
4019                 proj = new_d_defaultProj(dbgi, current_switch_cond,
4020                                          MAGIC_DEFAULT_PN_NUMBER);
4021
4022                 add_immBlock_pred(block, proj);
4023         }
4024
4025         if (fallthrough != NULL) {
4026                 add_immBlock_pred(block, fallthrough);
4027         }
4028         mature_immBlock(block);
4029         set_cur_block(block);
4030
4031         if(statement->statement != NULL) {
4032                 statement_to_firm(statement->statement);
4033         }
4034 }
4035
4036 static ir_node *get_label_block(declaration_t *label)
4037 {
4038         assert(label->namespc == NAMESPACE_LABEL);
4039
4040         if(label->declaration_kind == DECLARATION_KIND_LABEL_BLOCK) {
4041                 return label->v.block;
4042         }
4043         assert(label->declaration_kind == DECLARATION_KIND_UNKNOWN);
4044
4045         ir_node *old_cur_block = get_cur_block();
4046         ir_node *block         = new_immBlock();
4047         set_cur_block(old_cur_block);
4048
4049         label->declaration_kind = DECLARATION_KIND_LABEL_BLOCK;
4050         label->v.block          = block;
4051
4052         ARR_APP1(ir_node *, imature_blocks, block);
4053
4054         return block;
4055 }
4056
4057 static void label_to_firm(const label_statement_t *statement)
4058 {
4059         ir_node *block = get_label_block(statement->label);
4060
4061         if(get_cur_block() != NULL) {
4062                 ir_node *jmp = new_Jmp();
4063                 add_immBlock_pred(block, jmp);
4064         }
4065
4066         set_cur_block(block);
4067         keep_alive(block);
4068
4069         if(statement->statement != NULL) {
4070                 statement_to_firm(statement->statement);
4071         }
4072 }
4073
4074 static void goto_to_firm(const goto_statement_t *statement)
4075 {
4076         if(get_cur_block() == NULL)
4077                 return;
4078
4079         ir_node *block = get_label_block(statement->label);
4080         ir_node *jmp   = new_Jmp();
4081         add_immBlock_pred(block, jmp);
4082
4083         set_cur_block(NULL);
4084 }
4085
4086 typedef enum modifier_t {
4087         ASM_MODIFIER_WRITE_ONLY   = 1 << 0,
4088         ASM_MODIFIER_READ_WRITE   = 1 << 1,
4089         ASM_MODIFIER_COMMUTATIVE  = 1 << 2,
4090         ASM_MODIFIER_EARLYCLOBBER = 1 << 3,
4091 } modifier_t;
4092
4093 static void asm_statement_to_firm(const asm_statement_t *statement)
4094 {
4095         (void) statement;
4096         fprintf(stderr, "WARNING asm not implemented yet!\n");
4097 #if 0
4098         bool needs_memory = false;
4099
4100         size_t         n_clobbers = 0;
4101         asm_clobber_t *clobber    = statement->clobbers;
4102         for( ; clobber != NULL; clobber = clobber->next) {
4103                 if(strcmp(clobber->clobber, "memory") == 0) {
4104                         needs_memory = true;
4105                         continue;
4106                 }
4107
4108                 ident *id = new_id_from_str(clobber->clobber);
4109                 obstack_ptr_grow(&asm_obst, id);
4110                 ++n_clobbers;
4111         }
4112         assert(obstack_object_size(&asm_obst) == n_clobbers * sizeof(ident*));
4113         ident **clobbers = NULL;
4114         if(n_clobbers > 0) {
4115                 clobbers = obstack_finish(&asm_obst);
4116         }
4117
4118         /* find and count input and output constraints */
4119         asm_constraint_t *constraint = statement->inputs;
4120         for( ; constraint != NULL; constraint = constraint->next) {
4121                 int  modifiers      = 0;
4122                 bool supports_memop = false;
4123                 for(const char *c = constraint->constraints; *c != 0; ++c) {
4124                         /* TODO: improve error messages */
4125                         switch(*c) {
4126                         case '?':
4127                         case '!':
4128                                 panic("multiple alternative assembler constraints not "
4129                                       "supported");
4130                         case 'm':
4131                         case 'o':
4132                         case 'V':
4133                         case '<':
4134                         case '>':
4135                         case 'X':
4136                                 supports_memop = true;
4137                                 obstack_1grow(&asm_obst, *c);
4138                                 break;
4139                         case '=':
4140                                 if(modifiers & ASM_MODIFIER_READ_WRITE)
4141                                         panic("inconsistent register constraints");
4142                                 modifiers |= ASM_MODIFIER_WRITE_ONLY;
4143                                 break;
4144                         case '+':
4145                                 if(modifiers & ASM_MODIFIER_WRITE_ONLY)
4146                                         panic("inconsistent register constraints");
4147                                 modifiers |= ASM_MODIFIER_READ_WRITE;
4148                                 break;
4149                         case '&':
4150                                 modifiers |= ASM_MODIFIER_EARLYCLOBBER;
4151                                 panic("early clobber assembler constraint not supported yet");
4152                                 break;
4153                         case '%':
4154                                 modifiers |= ASM_MODIFIER_COMMUTATIVE;
4155                                 panic("commutative assembler constraint not supported yet");
4156                                 break;
4157                         case '#':
4158                                 /* skip register preferences stuff... */
4159                                 while(*c != 0 && *c != ',')
4160                                         ++c;
4161                                 break;
4162                         case '*':
4163                                 /* skip register preferences stuff... */
4164                                 ++c;
4165                                 break;
4166                         default:
4167                                 obstack_1grow(&asm_obst, *c);
4168                                 break;
4169                         }
4170                 }
4171                 obstack_1grow(&asm_obst, '\0');
4172                 const char *constraint_string = obstack_finish(&asm_obst);
4173
4174                 needs_memory |= supports_memop;
4175                 if(supports_memop) {
4176
4177                 }
4178         }
4179 #endif
4180 }
4181
4182 static void statement_to_firm(statement_t *statement)
4183 {
4184         switch(statement->kind) {
4185         case STATEMENT_INVALID:
4186                 panic("invalid statement found");
4187         case STATEMENT_COMPOUND:
4188                 compound_statement_to_firm(&statement->compound);
4189                 return;
4190         case STATEMENT_RETURN:
4191                 return_statement_to_firm(&statement->returns);
4192                 return;
4193         case STATEMENT_EXPRESSION:
4194                 expression_statement_to_firm(&statement->expression);
4195                 return;
4196         case STATEMENT_IF:
4197                 if_statement_to_firm(&statement->ifs);
4198                 return;
4199         case STATEMENT_WHILE:
4200                 while_statement_to_firm(&statement->whiles);
4201                 return;
4202         case STATEMENT_DO_WHILE:
4203                 do_while_statement_to_firm(&statement->do_while);
4204                 return;
4205         case STATEMENT_DECLARATION:
4206                 declaration_statement_to_firm(&statement->declaration);
4207                 return;
4208         case STATEMENT_BREAK:
4209                 create_jump_statement(statement, break_label);
4210                 return;
4211         case STATEMENT_CONTINUE:
4212                 create_jump_statement(statement, continue_label);
4213                 return;
4214         case STATEMENT_SWITCH:
4215                 switch_statement_to_firm(&statement->switchs);
4216                 return;
4217         case STATEMENT_CASE_LABEL:
4218                 case_label_to_firm(&statement->case_label);
4219                 return;
4220         case STATEMENT_FOR:
4221                 for_statement_to_firm(&statement->fors);
4222                 return;
4223         case STATEMENT_LABEL:
4224                 label_to_firm(&statement->label);
4225                 return;
4226         case STATEMENT_GOTO:
4227                 goto_to_firm(&statement->gotos);
4228                 return;
4229         case STATEMENT_ASM:
4230                 asm_statement_to_firm(&statement->asms);
4231                 return;
4232         }
4233         panic("Statement not implemented\n");
4234 }
4235
4236 static int count_decls_in_expression(const expression_t *expression);
4237
4238 static int count_local_declarations(const declaration_t *      decl,
4239                                     const declaration_t *const end)
4240 {
4241         int count = 0;
4242         for (; decl != end; decl = decl->next) {
4243                 if(decl->namespc != NAMESPACE_NORMAL)
4244                         continue;
4245                 const type_t *type = skip_typeref(decl->type);
4246                 if (!decl->address_taken && is_type_scalar(type))
4247                         ++count;
4248                 const initializer_t *initializer = decl->init.initializer;
4249                 /* FIXME: should walk initializer hierarchies... */
4250                 if(initializer != NULL && initializer->kind == INITIALIZER_VALUE) {
4251                         count += count_decls_in_expression(initializer->value.value);
4252                 }
4253         }
4254         return count;
4255 }
4256
4257 static int count_decls_in_expression(const expression_t *expression) {
4258         if(expression == NULL)
4259                 return 0;
4260
4261         switch(expression->base.kind) {
4262         case EXPR_STATEMENT:
4263                 return count_decls_in_stmts(expression->statement.statement);
4264         EXPR_BINARY_CASES {
4265                 int count_left  = count_decls_in_expression(expression->binary.left);
4266                 int count_right = count_decls_in_expression(expression->binary.right);
4267                 return count_left + count_right;
4268         }
4269         EXPR_UNARY_CASES
4270                 return count_decls_in_expression(expression->unary.value);
4271         case EXPR_CALL: {
4272                 int count = 0;
4273                 call_argument_t *argument = expression->call.arguments;
4274                 for( ; argument != NULL; argument = argument->next) {
4275                         count += count_decls_in_expression(argument->expression);
4276                 }
4277                 return count;
4278         }
4279
4280         default:
4281                 break;
4282         }
4283
4284         /* TODO FIXME: finish/fix that firm patch that allows dynamic value numbers
4285          * (or implement all the missing expressions here/implement a walker)
4286          */
4287
4288         return 0;
4289 }
4290
4291 static int count_decls_in_stmts(const statement_t *stmt)
4292 {
4293         int count = 0;
4294         for (; stmt != NULL; stmt = stmt->base.next) {
4295                 switch (stmt->kind) {
4296                         case STATEMENT_DECLARATION: {
4297                                 const declaration_statement_t *const decl_stmt = &stmt->declaration;
4298                                 count += count_local_declarations(decl_stmt->declarations_begin,
4299                                                                   decl_stmt->declarations_end->next);
4300                                 break;
4301                         }
4302
4303                         case STATEMENT_COMPOUND: {
4304                                 const compound_statement_t *const comp =
4305                                         &stmt->compound;
4306                                 count += count_decls_in_stmts(comp->statements);
4307                                 break;
4308                         }
4309
4310                         case STATEMENT_IF: {
4311                                 const if_statement_t *const if_stmt = &stmt->ifs;
4312                                 count += count_decls_in_expression(if_stmt->condition);
4313                                 count += count_decls_in_stmts(if_stmt->true_statement);
4314                                 count += count_decls_in_stmts(if_stmt->false_statement);
4315                                 break;
4316                         }
4317
4318                         case STATEMENT_SWITCH: {
4319                                 const switch_statement_t *const switch_stmt = &stmt->switchs;
4320                                 count += count_decls_in_expression(switch_stmt->expression);
4321                                 count += count_decls_in_stmts(switch_stmt->body);
4322                                 break;
4323                         }
4324
4325                         case STATEMENT_LABEL: {
4326                                 const label_statement_t *const label_stmt = &stmt->label;
4327                                 if(label_stmt->statement != NULL) {
4328                                         count += count_decls_in_stmts(label_stmt->statement);
4329                                 }
4330                                 break;
4331                         }
4332
4333                         case STATEMENT_WHILE: {
4334                                 const while_statement_t *const while_stmt = &stmt->whiles;
4335                                 count += count_decls_in_expression(while_stmt->condition);
4336                                 count += count_decls_in_stmts(while_stmt->body);
4337                                 break;
4338                         }
4339
4340                         case STATEMENT_DO_WHILE: {
4341                                 const do_while_statement_t *const do_while_stmt = &stmt->do_while;
4342                                 count += count_decls_in_expression(do_while_stmt->condition);
4343                                 count += count_decls_in_stmts(do_while_stmt->body);
4344                                 break;
4345                         }
4346
4347                         case STATEMENT_FOR: {
4348                                 const for_statement_t *const for_stmt = &stmt->fors;
4349                                 count += count_local_declarations(for_stmt->scope.declarations, NULL);
4350                                 count += count_decls_in_expression(for_stmt->initialisation);
4351                                 count += count_decls_in_expression(for_stmt->condition);
4352                                 count += count_decls_in_expression(for_stmt->step);
4353                                 count += count_decls_in_stmts(for_stmt->body);
4354                                 break;
4355                         }
4356
4357                         case STATEMENT_CASE_LABEL: {
4358                                 const case_label_statement_t *label = &stmt->case_label;
4359                                 count += count_decls_in_expression(label->expression);
4360                                 if(label->statement != NULL) {
4361                                         count += count_decls_in_stmts(label->statement);
4362                                 }
4363                                 break;
4364                         }
4365
4366                         case STATEMENT_ASM:
4367                         case STATEMENT_BREAK:
4368                         case STATEMENT_CONTINUE:
4369                                 break;
4370
4371                         case STATEMENT_EXPRESSION: {
4372                                 const expression_statement_t *expr_stmt = &stmt->expression;
4373                                 count += count_decls_in_expression(expr_stmt->expression);
4374                                 break;
4375                         }
4376
4377                         case STATEMENT_GOTO:
4378                         case STATEMENT_INVALID:
4379                                 break;
4380
4381                         case STATEMENT_RETURN: {
4382                                 const return_statement_t *ret_stmt = &stmt->returns;
4383                                 count += count_decls_in_expression(ret_stmt->value);
4384                                 break;
4385                         }
4386                 }
4387         }
4388         return count;
4389 }
4390
4391 static int get_function_n_local_vars(declaration_t *declaration)
4392 {
4393         int count = 0;
4394
4395         /* count parameters */
4396         count += count_local_declarations(declaration->scope.declarations, NULL);
4397
4398         /* count local variables declared in body */
4399         count += count_decls_in_stmts(declaration->init.statement);
4400
4401         return count;
4402 }
4403
4404 static void initialize_function_parameters(declaration_t *declaration)
4405 {
4406         ir_graph        *irg             = current_ir_graph;
4407         ir_node         *args            = get_irg_args(irg);
4408         ir_node         *start_block     = get_irg_start_block(irg);
4409         ir_type         *function_irtype = get_ir_type(declaration->type);
4410
4411         int            n         = 0;
4412         declaration_t *parameter = declaration->scope.declarations;
4413         for( ; parameter != NULL; parameter = parameter->next, ++n) {
4414                 assert(parameter->declaration_kind == DECLARATION_KIND_UNKNOWN);
4415                 type_t *type = skip_typeref(parameter->type);
4416
4417                 bool needs_entity = parameter->address_taken;
4418                 assert(!is_type_array(type));
4419                 if(is_type_compound(type)) {
4420                         needs_entity = true;
4421                 }
4422
4423                 if(needs_entity) {
4424                         ir_entity *entity = get_method_value_param_ent(function_irtype, n);
4425                         ident     *id     = new_id_from_str(parameter->symbol->string);
4426                         set_entity_ident(entity, id);
4427
4428                         parameter->declaration_kind
4429                                 = DECLARATION_KIND_LOCAL_VARIABLE_ENTITY;
4430                         parameter->v.entity = entity;
4431                         continue;
4432                 }
4433
4434                 ir_mode *mode = get_ir_mode(parameter->type);
4435                 long     pn   = n;
4436                 ir_node *proj = new_r_Proj(irg, start_block, args, mode, pn);
4437
4438                 parameter->declaration_kind = DECLARATION_KIND_LOCAL_VARIABLE;
4439                 parameter->v.value_number   = next_value_number_function;
4440                 set_irg_loc_description(current_ir_graph, next_value_number_function, parameter);
4441                 ++next_value_number_function;
4442
4443                 set_value(parameter->v.value_number, proj);
4444         }
4445 }
4446
4447 /**
4448  * Handle additional decl modifiers for IR-graphs
4449  *
4450  * @param irg            the IR-graph
4451  * @param dec_modifiers  additional modifiers
4452  */
4453 static void handle_decl_modifier_irg(ir_graph_ptr irg, decl_modifiers_t decl_modifiers)
4454 {
4455         if (decl_modifiers & DM_NORETURN) {
4456                 /* TRUE if the declaration includes the Microsoft
4457                    __declspec(noreturn) specifier. */
4458                 set_irg_additional_property(irg, mtp_property_noreturn);
4459         }
4460         if (decl_modifiers & DM_NOTHROW) {
4461                 /* TRUE if the declaration includes the Microsoft
4462                    __declspec(nothrow) specifier. */
4463                 set_irg_additional_property(irg, mtp_property_nothrow);
4464         }
4465         if (decl_modifiers & DM_NAKED) {
4466                 /* TRUE if the declaration includes the Microsoft
4467                    __declspec(naked) specifier. */
4468                 set_irg_additional_property(irg, mtp_property_naked);
4469         }
4470         if (decl_modifiers & DM_FORCEINLINE) {
4471                 /* TRUE if the declaration includes the
4472                    Microsoft __forceinline specifier. */
4473                 set_irg_inline_property(irg, irg_inline_forced);
4474         }
4475         if (decl_modifiers & DM_NOINLINE) {
4476                 /* TRUE if the declaration includes the Microsoft
4477                    __declspec(noinline) specifier. */
4478                 set_irg_inline_property(irg, irg_inline_forbidden);
4479         }
4480 }
4481
4482 static void create_function(declaration_t *declaration)
4483 {
4484         ir_entity *function_entity = get_function_entity(declaration);
4485
4486         if(declaration->init.statement == NULL)
4487                 return;
4488
4489         current_function_decl = declaration;
4490         current_function_name = NULL;
4491
4492         assert(imature_blocks == NULL);
4493         imature_blocks = NEW_ARR_F(ir_node*, 0);
4494
4495         int       n_local_vars = get_function_n_local_vars(declaration);
4496         ir_graph *irg          = new_ir_graph(function_entity, n_local_vars);
4497         ir_node  *first_block  = get_cur_block();
4498
4499         /* set inline flags */
4500         if (declaration->is_inline)
4501         set_irg_inline_property(irg, irg_inline_recomended);
4502     handle_decl_modifier_irg(irg, declaration->modifiers);
4503
4504         next_value_number_function = 0;
4505         initialize_function_parameters(declaration);
4506
4507         statement_to_firm(declaration->init.statement);
4508
4509         ir_node *end_block = get_irg_end_block(irg);
4510
4511         /* do we have a return statement yet? */
4512         if(get_cur_block() != NULL) {
4513                 type_t *type = skip_typeref(declaration->type);
4514                 assert(is_type_function(type));
4515                 const function_type_t *func_type   = &type->function;
4516                 const type_t          *return_type
4517                         = skip_typeref(func_type->return_type);
4518
4519                 ir_node *ret;
4520                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
4521                         ret = new_Return(get_store(), 0, NULL);
4522                 } else {
4523                         ir_mode *mode;
4524                         if(is_type_scalar(return_type)) {
4525                                 mode = get_ir_mode(func_type->return_type);
4526                         } else {
4527                                 mode = mode_P_data;
4528                         }
4529
4530                         ir_node *in[1];
4531                         /* ยง5.1.2.2.3 main implicitly returns 0 */
4532                         if (strcmp(declaration->symbol->string, "main") == 0) {
4533                                 in[0] = new_Const(mode, get_mode_null(mode));
4534                         } else {
4535                                 in[0] = new_Unknown(mode);
4536                         }
4537                         ret = new_Return(get_store(), 1, in);
4538                 }
4539                 add_immBlock_pred(end_block, ret);
4540         }
4541
4542         for(int i = 0; i < ARR_LEN(imature_blocks); ++i) {
4543                 mature_immBlock(imature_blocks[i]);
4544         }
4545         DEL_ARR_F(imature_blocks);
4546         imature_blocks = NULL;
4547
4548         mature_immBlock(first_block);
4549         mature_immBlock(end_block);
4550
4551         irg_finalize_cons(irg);
4552
4553         /* finalize the frame type */
4554         ir_type *frame_type = get_irg_frame_type(irg);
4555         int      n          = get_compound_n_members(frame_type);
4556         int      align_all  = 4;
4557         int      offset     = 0;
4558         for(int i = 0; i < n; ++i) {
4559                 ir_entity *entity      = get_compound_member(frame_type, i);
4560                 ir_type   *entity_type = get_entity_type(entity);
4561
4562                 int align = get_type_alignment_bytes(entity_type);
4563                 if(align > align_all)
4564                         align_all = align;
4565                 int misalign = 0;
4566                 if(align > 0) {
4567                         misalign  = offset % align;
4568                         if(misalign > 0) {
4569                                 offset += align - misalign;
4570                         }
4571                 }
4572
4573                 set_entity_offset(entity, offset);
4574                 offset += get_type_size_bytes(entity_type);
4575         }
4576         set_type_size_bytes(frame_type, offset);
4577         set_type_alignment_bytes(frame_type, align_all);
4578
4579         irg_vrfy(irg);
4580 }
4581
4582 static void scope_to_firm(scope_t *scope)
4583 {
4584         /* first pass: create declarations */
4585         declaration_t *declaration = scope->declarations;
4586         for( ; declaration != NULL; declaration = declaration->next) {
4587                 if(declaration->namespc != NAMESPACE_NORMAL)
4588                         continue;
4589                 if(declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY
4590                                 || declaration->storage_class == STORAGE_CLASS_TYPEDEF)
4591                         continue;
4592                 if(declaration->symbol == NULL)
4593                         continue;
4594
4595                 type_t *type = skip_typeref(declaration->type);
4596                 if(is_type_function(type)) {
4597                         get_function_entity(declaration);
4598                 } else {
4599                         create_global_variable(declaration);
4600                 }
4601         }
4602
4603         /* second pass: create code/initializers */
4604         declaration = scope->declarations;
4605         for( ; declaration != NULL; declaration = declaration->next) {
4606                 if(declaration->namespc != NAMESPACE_NORMAL)
4607                         continue;
4608                 if(declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY
4609                                 || declaration->storage_class == STORAGE_CLASS_TYPEDEF)
4610                         continue;
4611                 if(declaration->symbol == NULL)
4612                         continue;
4613
4614                 type_t *type = declaration->type;
4615                 if(type->kind == TYPE_FUNCTION) {
4616                         create_function(declaration);
4617                 } else {
4618                         assert(declaration->declaration_kind
4619                                         == DECLARATION_KIND_GLOBAL_VARIABLE);
4620                         current_ir_graph = get_const_code_irg();
4621                         create_declaration_initializer(declaration);
4622                 }
4623         }
4624 }
4625
4626 void init_ast2firm(void)
4627 {
4628         obstack_init(&asm_obst);
4629         init_atomic_modes();
4630
4631         /* create idents for all known runtime functions */
4632         for (size_t i = 0; i < sizeof(rts_data) / sizeof(rts_data[0]); ++i) {
4633                 predef_idents[rts_data[i].id] = new_id_from_str(rts_data[i].name);
4634         }
4635 }
4636
4637 static void init_ir_types(void)
4638 {
4639         static int ir_types_initialized = 0;
4640         if(ir_types_initialized)
4641                 return;
4642         ir_types_initialized = 1;
4643
4644         type_const_char = make_atomic_type(ATOMIC_TYPE_CHAR, TYPE_QUALIFIER_CONST);
4645         type_void       = make_atomic_type(ATOMIC_TYPE_VOID, TYPE_QUALIFIER_NONE);
4646         type_int        = make_atomic_type(ATOMIC_TYPE_INT,  TYPE_QUALIFIER_NONE);
4647
4648         ir_type_int        = get_ir_type(type_int);
4649         ir_type_const_char = get_ir_type(type_const_char);
4650         ir_type_wchar_t    = get_ir_type(type_wchar_t);
4651         ir_type_void       = get_ir_type(type_int); /* we don't have a real void
4652                                                        type in firm */
4653
4654         type_void->base.firm_type = ir_type_void;
4655 }
4656
4657 void exit_ast2firm(void)
4658 {
4659         obstack_free(&asm_obst, NULL);
4660 }
4661
4662 void translation_unit_to_firm(translation_unit_t *unit)
4663 {
4664         /* just to be sure */
4665         continue_label      = NULL;
4666         break_label         = NULL;
4667         current_switch_cond = NULL;
4668
4669         init_ir_types();
4670
4671         scope_to_firm(&unit->scope);
4672 }