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