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