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