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