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