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