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