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