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