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