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