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