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