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