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