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