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