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