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