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