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