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