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