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