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