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