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