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