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