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