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