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