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