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