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