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