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