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