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