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