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