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