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