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