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