introduce Switch node
[libfirm] / ir / be / begnuas.c
1 /*
2  * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Dumps global variables and constants as gas assembler.
23  * @author      Christian Wuerdig, Matthias Braun
24  * @date        04.11.2005
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include "begnuas.h"
30
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <assert.h>
35
36 #include "obst.h"
37 #include "tv.h"
38 #include "irnode.h"
39 #include "irprog.h"
40 #include "entity_t.h"
41 #include "error.h"
42 #include "util.h"
43
44 #include "be_t.h"
45 #include "beemitter.h"
46 #include "be_dbgout.h"
47
48 /** by default, we generate assembler code for the Linux gas */
49 object_file_format_t  be_gas_object_file_format = OBJECT_FILE_FORMAT_ELF;
50 elf_variant_t         be_gas_elf_variant        = ELF_VARIANT_NORMAL;
51 bool                  be_gas_emit_types         = true;
52 char                  be_gas_elf_type_char      = '@';
53
54 static be_gas_section_t current_section = (be_gas_section_t) -1;
55
56 /**
57  * An environment containing all needed dumper data.
58  * Currently we create the file completely in memory first, then
59  * write it to the disk. This is an artifact from the old C-generating backend
60  * and even there NOT needed. So we might change it in the future.
61  */
62 typedef struct be_gas_decl_env {
63         be_gas_section_t     section;
64         const be_main_env_t *main_env;
65 } be_gas_decl_env_t;
66
67 static void emit_section_macho(be_gas_section_t section)
68 {
69         be_gas_section_t  base  = section & GAS_SECTION_TYPE_MASK;
70         be_gas_section_t  flags = section & ~GAS_SECTION_TYPE_MASK;
71         const char       *name;
72
73         if (current_section == section)
74                 return;
75         current_section = section;
76
77         /* shortforms */
78         if (flags == 0) {
79                 switch (base) {
80                 case GAS_SECTION_TEXT:            name = "text";          break;
81                 case GAS_SECTION_DATA:            name = "data";          break;
82                 case GAS_SECTION_RODATA:          name = "const";         break;
83                 case GAS_SECTION_BSS:             name = "data";          break;
84                 case GAS_SECTION_CONSTRUCTORS:    name = "mod_init_func"; break;
85                 case GAS_SECTION_DESTRUCTORS:     name = "mod_term_func"; break;
86                 case GAS_SECTION_PIC_TRAMPOLINES: name = "section\t__IMPORT,__jump_table,symbol_stubs,self_modifying_code+pure_instructions,5"; break;
87                 case GAS_SECTION_PIC_SYMBOLS:     name = "section\t__IMPORT,__pointers,non_lazy_symbol_pointers"; break;
88                 case GAS_SECTION_CSTRING:         name = "cstring";       break;
89                 case GAS_SECTION_DEBUG_INFO:      name = "section __DWARF,__debug_info,regular,debug"; break;
90                 case GAS_SECTION_DEBUG_ABBREV:    name = "section __DWARF,__debug_abbrev,regular,debug"; break;
91                 case GAS_SECTION_DEBUG_LINE:      name = "section __DWARF,__debug_line,regular,debug"; break;
92                 case GAS_SECTION_DEBUG_PUBNAMES:  name = "section __DWARF,__debug_pubnames,regular,debug"; break;
93                 default: panic("unsupported scetion type 0x%X", section);
94                 }
95                 be_emit_irprintf("\t.%s\n", name);
96                 be_emit_write_line();
97         } else if (flags & GAS_SECTION_FLAG_COMDAT) {
98                 switch (base) {
99                 case GAS_SECTION_TEXT:            name = "section __TEXT,__textcoal_nt,coalesced,pure_instructions"; break;
100                 case GAS_SECTION_BSS:
101                 case GAS_SECTION_DATA:            name = "section __DATA,__datacoal_nt,coalesced"; break;
102                 case GAS_SECTION_RODATA:          name = "section __TEXT,__const_coal,coalesced"; break;
103                 case GAS_SECTION_CSTRING:         name = "section __TEXT,__const_coal,coalesced"; break;
104                 default: panic("unsupported scetion type 0x%X", section);
105                 }
106         } else {
107                 panic("unsupported section type 0x%X\n", section);
108         }
109 }
110
111 static void emit_section_sparc(be_gas_section_t section, const ir_entity *entity)
112 {
113         be_gas_section_t base = section & GAS_SECTION_TYPE_MASK;
114         be_gas_section_t flags = section & ~GAS_SECTION_TYPE_MASK;
115         static const char *const basename[GAS_SECTION_LAST+1] = {
116                 "text",
117                 "data",
118                 "rodata",
119                 "bss",
120                 "ctors",
121                 "dtors",
122                 NULL, /* cstring */
123                 NULL, /* pic trampolines */
124                 NULL, /* pic symbols */
125                 "debug_info",
126                 "debug_abbrev",
127                 "debug_line",
128                 "debug_pubnames"
129         };
130
131         if (current_section == section && !(section & GAS_SECTION_FLAG_COMDAT))
132                 return;
133         current_section = section;
134
135         be_emit_cstring("\t.section\t\".");
136
137         /* Part1: section-name */
138         if (flags & GAS_SECTION_FLAG_TLS)
139                 be_emit_char('t');
140         assert(base < (be_gas_section_t)ARRAY_SIZE(basename));
141         be_emit_string(basename[base]);
142
143         if (flags & GAS_SECTION_FLAG_COMDAT) {
144                 be_emit_char('.');
145                 be_gas_emit_entity(entity);
146         }
147         be_emit_char('"');
148
149         /* for the simple sections we're done here */
150         if (flags == 0)
151                 goto end;
152
153         be_emit_cstring(",#alloc");
154
155         switch (base) {
156         case GAS_SECTION_TEXT: be_emit_cstring(",#execinstr"); break;
157         case GAS_SECTION_DATA:
158         case GAS_SECTION_BSS:  be_emit_cstring(",#write"); break;
159         default:
160                 /* nothing */
161                 break;
162         }
163         if (flags & GAS_SECTION_FLAG_TLS) {
164                 be_emit_cstring(",#tls");
165         }
166
167 end:
168         be_emit_char('\n');
169         be_emit_write_line();
170 }
171
172 static void emit_section(be_gas_section_t section, const ir_entity *entity)
173 {
174         be_gas_section_t base = section & GAS_SECTION_TYPE_MASK;
175         be_gas_section_t flags = section & ~GAS_SECTION_TYPE_MASK;
176         const char *f;
177         static const struct {
178                 const char *name;
179                 const char *type;
180                 const char *flags;
181         } sectioninfos[GAS_SECTION_LAST+1] = {
182                 { "text",           "progbits", "ax" },
183                 { "data",           "progbits", "aw" },
184                 { "rodata",         "progbits", "a"  },
185                 { "bss",            "nobits",   "aw" },
186                 { "ctors",          "progbits", "aw" },
187                 { "dtors",          "progbits", "aw" },
188                 { NULL,             NULL,       NULL }, /* cstring */
189                 { NULL,             NULL,       NULL }, /* pic trampolines */
190                 { NULL,             NULL,       NULL }, /* pic symbols */
191                 { "debug_info",     "progbits", ""   },
192                 { "debug_abbrev",   "progbits", ""   },
193                 { "debug_line",     "progbits", ""   },
194                 { "debug_pubnames", "progbits", ""   },
195         };
196
197         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
198                 emit_section_macho(section);
199                 return;
200         } else if(be_gas_elf_variant == ELF_VARIANT_SPARC) {
201                 emit_section_sparc(section, entity);
202                 return;
203         }
204
205         if (current_section == section && !(section & GAS_SECTION_FLAG_COMDAT))
206                 return;
207         current_section = section;
208
209         /* shortforms */
210         if (flags == 0) {
211                 switch (base) {
212                 case GAS_SECTION_TEXT:
213                         be_emit_cstring("\t.text\n");
214                         be_emit_write_line();
215                         return;
216                 case GAS_SECTION_DATA:
217                         be_emit_cstring("\t.data\n");
218                         be_emit_write_line();
219                         return;
220                 case GAS_SECTION_RODATA:
221                         be_emit_cstring("\t.section\t.rodata\n");
222                         be_emit_write_line();
223                         return;
224                 case GAS_SECTION_BSS:
225                         be_emit_cstring("\t.bss\n");
226                         be_emit_write_line();
227                         return;
228                 default:
229                         break;
230                 }
231         }
232
233         assert(base < (be_gas_section_t) ARRAY_SIZE(sectioninfos));
234         be_emit_cstring("\t.section\t.");
235         /* section name */
236         if (flags & GAS_SECTION_FLAG_TLS)
237                 be_emit_char('t');
238         be_emit_string(sectioninfos[base].name);
239         if (flags & GAS_SECTION_FLAG_COMDAT) {
240                 be_emit_char('.');
241                 be_gas_emit_entity(entity);
242         }
243
244         /* section flags */
245         be_emit_cstring(",\"");
246         for (f = sectioninfos[base].flags; *f != '\0'; ++f) {
247                 be_emit_char(*f);
248         }
249         if (flags & GAS_SECTION_FLAG_TLS)
250                 be_emit_char('T');
251         if (flags & GAS_SECTION_FLAG_COMDAT)
252                 be_emit_char('G');
253
254         /* section type */
255         if (be_gas_object_file_format != OBJECT_FILE_FORMAT_COFF) {
256                 be_emit_cstring("\",");
257                 be_emit_char(be_gas_elf_type_char);
258                 be_emit_string(sectioninfos[base].type);
259         }
260
261         if (flags & GAS_SECTION_FLAG_COMDAT) {
262                 be_emit_char(',');
263                 be_gas_emit_entity(entity);
264                 be_emit_cstring(",comdat");
265         }
266         be_emit_char('\n');
267         be_emit_write_line();
268 }
269
270
271
272 void be_gas_emit_switch_section(be_gas_section_t section)
273 {
274         /* you have to produce a switch_section call with entity manually
275          * for comdat sections */
276         assert( !(section & GAS_SECTION_FLAG_COMDAT));
277
278         emit_section(section, NULL);
279 }
280
281 static ir_tarval *get_initializer_tarval(const ir_initializer_t *initializer)
282 {
283         if (initializer->kind == IR_INITIALIZER_TARVAL)
284                 return initializer->tarval.value;
285         if (initializer->kind == IR_INITIALIZER_CONST) {
286                 ir_node *node = initializer->consti.value;
287                 if (is_Const(node)) {
288                         return get_Const_tarval(node);
289                 }
290         }
291         return get_tarval_undefined();
292 }
293
294 static bool initializer_is_string_const(const ir_initializer_t *initializer)
295 {
296         size_t i, len;
297         bool found_printable = false;
298
299         if (initializer->kind != IR_INITIALIZER_COMPOUND)
300                 return false;
301
302         len = initializer->compound.n_initializers;
303         if (len < 1)
304                 return false;
305         for (i = 0; i < len; ++i) {
306                 int               c;
307                 ir_tarval        *tv;
308                 ir_mode          *mode;
309                 ir_initializer_t *sub_initializer
310                         = initializer->compound.initializers[i];
311
312                 tv = get_initializer_tarval(sub_initializer);
313                 if (!tarval_is_constant(tv))
314                         return false;
315
316                 mode = get_tarval_mode(tv);
317                 if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
318                         return false;
319
320                 c = get_tarval_long(tv);
321                 if (isgraph(c) || isspace(c))
322                         found_printable = true;
323                 else if (c != 0)
324                         return false;
325
326                 if (i == len - 1 && c != '\0')
327                         return false;
328         }
329
330         return found_printable;
331 }
332
333 static bool initializer_is_null(const ir_initializer_t *initializer)
334 {
335         switch (initializer->kind) {
336         case IR_INITIALIZER_NULL:
337                 return true;
338         case IR_INITIALIZER_TARVAL: {
339                 ir_tarval *tv = initializer->tarval.value;
340                 return tarval_is_null(tv);
341         }
342         case IR_INITIALIZER_CONST: {
343                 ir_node *value = initializer->consti.value;
344                 if (!is_Const(value))
345                         return false;
346                 return is_Const_null(value);
347         }
348         case IR_INITIALIZER_COMPOUND: {
349                 size_t i;
350                 for (i = 0; i < initializer->compound.n_initializers; ++i) {
351                         ir_initializer_t *subinitializer
352                                 = initializer->compound.initializers[i];
353                         if (!initializer_is_null(subinitializer))
354                                 return false;
355                 }
356                 return true;
357         }
358         }
359         panic("invalid initializer in initializer_is_null");
360 }
361
362 /**
363  * Determine if an entity is a string constant
364  * @param ent The entity
365  * @return 1 if it is a string constant, 0 otherwise
366  */
367 static int entity_is_string_const(const ir_entity *ent)
368 {
369         ir_type *type, *element_type;
370         ir_mode *mode;
371         int i, c, n;
372
373         type = get_entity_type(ent);
374
375         /* if it's an array */
376         if (!is_Array_type(type))
377                 return 0;
378
379         element_type = get_array_element_type(type);
380
381         /* and the array's element type is primitive */
382         if (!is_Primitive_type(element_type))
383                 return 0;
384
385         /* and the mode of the element type is an int of
386          * the same size as the byte mode */
387         mode = get_type_mode(element_type);
388         if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
389                 return 0;
390
391         if (ent->initializer != NULL) {
392                 return initializer_is_string_const(ent->initializer);
393         } else if (entity_has_compound_ent_values(ent)) {
394                 int found_printable = 0;
395                 /* if it contains only printable chars and a 0 at the end */
396                 n = get_compound_ent_n_values(ent);
397                 for (i = 0; i < n; ++i) {
398                         ir_node *irn = get_compound_ent_value(ent, i);
399                         if (! is_Const(irn))
400                                 return 0;
401
402                         c = (int) get_tarval_long(get_Const_tarval(irn));
403
404                         if (isgraph(c) || isspace(c))
405                                 found_printable = 1;
406                         else if (c != 0)
407                                 return 0;
408
409                         if (i == n - 1 && c != '\0')
410                                 return 0;
411                 }
412                 return found_printable;
413         }
414
415         return 0;
416 }
417
418 static bool entity_is_null(const ir_entity *entity)
419 {
420         if (entity->initializer != NULL) {
421                 return initializer_is_null(entity->initializer);
422         } else if (entity_has_compound_ent_values(entity)) {
423                 /* I'm too lazy to implement this case as compound graph paths will be
424                  * remove anyway in the future */
425                 return false;
426         }
427         /* uninitialized, NULL is fine */
428         return true;
429 }
430
431 static bool is_comdat(const ir_entity *entity)
432 {
433         ir_linkage linkage = get_entity_linkage(entity);
434         return (linkage & IR_LINKAGE_MERGE)
435                 && (linkage & IR_LINKAGE_GARBAGE_COLLECT);
436 }
437
438 static be_gas_section_t determine_basic_section(const ir_entity *entity)
439 {
440         ir_linkage linkage;
441
442         if (is_method_entity(entity))
443                 return GAS_SECTION_TEXT;
444
445         linkage = get_entity_linkage(entity);
446         if (linkage & IR_LINKAGE_CONSTANT) {
447                 /* mach-o is the only one with a cstring section */
448                 if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O
449                                 && entity_is_string_const(entity))
450                         return GAS_SECTION_CSTRING;
451
452                 return GAS_SECTION_RODATA;
453         }
454         if (entity_is_null(entity))
455                 return GAS_SECTION_BSS;
456
457         return GAS_SECTION_DATA;
458 }
459
460 static be_gas_section_t determine_section(be_gas_decl_env_t *env,
461                                           const ir_entity *entity)
462 {
463         ir_type *owner = get_entity_owner(entity);
464
465         if (owner == get_segment_type(IR_SEGMENT_GLOBAL)) {
466                 be_gas_section_t section = determine_basic_section(entity);
467                 if (is_comdat(entity))
468                         section |= GAS_SECTION_FLAG_COMDAT;
469                 return section;
470         } else if (env != NULL && owner == env->main_env->pic_symbols_type) {
471                 return GAS_SECTION_PIC_SYMBOLS;
472         } else if (env != NULL && owner == env->main_env->pic_trampolines_type) {
473                 return GAS_SECTION_PIC_TRAMPOLINES;
474         } else if (owner == get_segment_type(IR_SEGMENT_CONSTRUCTORS)) {
475                 return GAS_SECTION_CONSTRUCTORS;
476         } else if (owner == get_segment_type(IR_SEGMENT_DESTRUCTORS)) {
477                 return GAS_SECTION_DESTRUCTORS;
478         } else if (owner == get_segment_type(IR_SEGMENT_THREAD_LOCAL)) {
479                 be_gas_section_t section = determine_basic_section(entity);
480                 if (is_comdat(entity))
481                         section |= GAS_SECTION_FLAG_COMDAT;
482
483                 return section | GAS_SECTION_FLAG_TLS;
484         }
485
486         /* the java frontend keeps some functions inside classes */
487         if (is_Class_type(owner)) {
488                 return determine_basic_section(entity);
489         }
490
491         panic("Couldn't determine section for %+F?!?", entity);
492 }
493
494 static void emit_weak(const ir_entity *entity)
495 {
496         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
497                 be_emit_cstring("\t.weak_reference ");
498         } else {
499                 be_emit_cstring("\t.weak ");
500         }
501         be_gas_emit_entity(entity);
502         be_emit_char('\n');
503         be_emit_write_line();
504 }
505
506 static void emit_visibility(const ir_entity *entity)
507 {
508         ir_linkage linkage = get_entity_linkage(entity);
509
510         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
511                 emit_weak(entity);
512                 /* Note: .weak seems to imply .globl so no need to output .globl */
513         } else if (get_entity_visibility(entity) == ir_visibility_default) {
514                 be_emit_cstring(".globl ");
515                 be_gas_emit_entity(entity);
516                 be_emit_char('\n');
517                 be_emit_write_line();
518         }
519
520         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O
521                         && (linkage & IR_LINKAGE_HIDDEN_USER)
522                         && get_entity_ld_name(entity)[0] != '\0') {
523                 be_emit_cstring("\t.no_dead_strip ");
524                 be_gas_emit_entity(entity);
525                 be_emit_char('\n');
526                 be_emit_write_line();
527         }
528 }
529
530 void be_gas_emit_function_prolog(const ir_entity *entity, unsigned po2alignment)
531 {
532         be_gas_section_t section;
533
534         be_dbg_method_begin(entity);
535
536         section = determine_section(NULL, entity);
537         emit_section(section, entity);
538
539         /* write the begin line (makes the life easier for scripts parsing the
540          * assembler) */
541         be_emit_write_line();
542         be_emit_cstring("# -- Begin  ");
543         be_gas_emit_entity(entity);
544         be_emit_char('\n');
545         be_emit_write_line();
546
547         if (po2alignment > 0) {
548                 const char *fill_byte = "";
549                 unsigned    maximum_skip = (1 << po2alignment) - 1;
550                 /* gcc fills space between function with 0x90... */
551                 if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
552                         fill_byte = "0x90";
553                 }
554                 be_emit_cstring("\t.p2align ");
555                 be_emit_irprintf("%u,%s,%u\n", po2alignment, fill_byte, maximum_skip);
556                 be_emit_write_line();
557         }
558         emit_visibility(entity);
559
560         switch (be_gas_object_file_format) {
561         case OBJECT_FILE_FORMAT_ELF:
562                 be_emit_cstring("\t.type\t");
563                 be_gas_emit_entity(entity);
564                 be_emit_cstring(", ");
565                 be_emit_char(be_gas_elf_type_char);
566                 be_emit_cstring("function\n");
567                 be_emit_write_line();
568                 break;
569         case OBJECT_FILE_FORMAT_COFF:
570                 be_emit_cstring("\t.def\t");
571                 be_gas_emit_entity(entity);
572                 be_emit_cstring(";");
573                 if (get_entity_visibility(entity) == ir_visibility_local) {
574                         be_emit_cstring("\t.scl\t3;");
575                 } else {
576                         be_emit_cstring("\t.scl\t2;");
577                 }
578                 be_emit_cstring("\t.type\t32;\t.endef\n");
579                 be_emit_write_line();
580                 break;
581         case OBJECT_FILE_FORMAT_MACH_O:
582                 break;
583         }
584         be_gas_emit_entity(entity);
585         be_emit_cstring(":\n");
586         be_emit_write_line();
587 }
588
589 void be_gas_emit_function_epilog(const ir_entity *entity)
590 {
591         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF) {
592                 be_emit_cstring("\t.size\t");
593                 be_gas_emit_entity(entity);
594                 be_emit_cstring(", .-");
595                 be_gas_emit_entity(entity);
596                 be_emit_char('\n');
597                 be_emit_write_line();
598         }
599
600         be_emit_cstring("# -- End  ");
601         be_gas_emit_entity(entity);
602         be_emit_char('\n');
603         be_emit_write_line();
604
605         be_dbg_method_end();
606
607         be_emit_char('\n');
608         be_emit_write_line();
609 }
610
611 /**
612  * Output a tarval.
613  *
614  * @param tv     the tarval
615  * @param bytes  the width of the tarvals value in bytes
616  */
617 static void emit_arith_tarval(ir_tarval *tv, unsigned bytes)
618 {
619         switch (bytes) {
620         case 1:
621                 be_emit_irprintf("0x%02x", get_tarval_sub_bits(tv, 0));
622                 return;
623
624         case 2:
625                 be_emit_irprintf("0x%02x%02x",
626                         get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
627                 return;
628
629         case 4:
630                 be_emit_irprintf("0x%02x%02x%02x%02x",
631                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2),
632                         get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
633                 return;
634
635         case 8:
636                 be_emit_irprintf("0x%02x%02x%02x%02x%02x%02x%02x%02x",
637                         get_tarval_sub_bits(tv, 7), get_tarval_sub_bits(tv, 6),
638                         get_tarval_sub_bits(tv, 5), get_tarval_sub_bits(tv, 4),
639                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2),
640                         get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
641                 return;
642         }
643
644         panic("Can't dump a tarval with %d bytes", bytes);
645 }
646
647 /**
648  * Return the label prefix for labeled instructions.
649  */
650 const char *be_gas_insn_label_prefix(void)
651 {
652         return ".LE";
653 }
654
655 /**
656  * Return the tarval of an atomic initializer.
657  *
658  * @param init  a node representing the initializer (on the const code irg)
659  *
660  * @return the tarval
661  */
662 static ir_tarval *get_atomic_init_tv(ir_node *init)
663 {
664         for (;;) {
665                 ir_mode *mode = get_irn_mode(init);
666
667                 switch (get_irn_opcode(init)) {
668
669                 case iro_Cast:
670                         init = get_Cast_op(init);
671                         continue;
672
673                 case iro_Conv:
674                         init = get_Conv_op(init);
675                         continue;
676
677                 case iro_Const:
678                         return get_Const_tarval(init);
679
680                 case iro_SymConst:
681                         switch (get_SymConst_kind(init)) {
682                         case symconst_type_size:
683                                 return new_tarval_from_long(get_type_size_bytes(get_SymConst_type(init)), mode);
684
685                         case symconst_type_align:
686                                 return new_tarval_from_long(get_type_alignment_bytes(get_SymConst_type(init)), mode);
687
688                         case symconst_ofs_ent:
689                                 return new_tarval_from_long(get_entity_offset(get_SymConst_entity(init)), mode);
690
691                         case symconst_enum_const:
692                                 return get_enumeration_value(get_SymConst_enum(init));
693
694                         default:
695                                 return NULL;
696                         }
697
698                 default:
699                         return NULL;
700                 }
701         }
702 }
703
704 /**
705  * Dump an atomic value.
706  *
707  * @param env   the gas output environment
708  * @param init  a node representing the atomic value (on the const code irg)
709  */
710 static void emit_init_expression(be_gas_decl_env_t *env, ir_node *init)
711 {
712         ir_mode *mode = get_irn_mode(init);
713         int bytes     = get_mode_size_bytes(mode);
714         ir_tarval *tv;
715         ir_entity *ent;
716
717         init = skip_Id(init);
718
719         switch (get_irn_opcode(init)) {
720         case iro_Cast:
721                 emit_init_expression(env, get_Cast_op(init));
722                 return;
723
724         case iro_Conv:
725                 emit_init_expression(env, get_Conv_op(init));
726                 return;
727
728         case iro_Const:
729                 tv = get_Const_tarval(init);
730
731                 /* it's an arithmetic value */
732                 emit_arith_tarval(tv, bytes);
733                 return;
734
735         case iro_SymConst:
736                 switch (get_SymConst_kind(init)) {
737                 case symconst_addr_ent:
738                         ent = get_SymConst_entity(init);
739                         be_gas_emit_entity(ent);
740                         break;
741
742                 case symconst_ofs_ent:
743                         ent = get_SymConst_entity(init);
744                         be_emit_irprintf("%d", get_entity_offset(ent));
745                         break;
746
747                 case symconst_type_size:
748                         be_emit_irprintf("%u", get_type_size_bytes(get_SymConst_type(init)));
749                         break;
750
751                 case symconst_type_align:
752                         be_emit_irprintf("%u", get_type_alignment_bytes(get_SymConst_type(init)));
753                         break;
754
755                 case symconst_enum_const:
756                         tv = get_enumeration_value(get_SymConst_enum(init));
757                         emit_arith_tarval(tv, bytes);
758                         break;
759
760                 default:
761                         assert(!"emit_atomic_init(): don't know how to init from this SymConst");
762                 }
763                 return;
764
765         case iro_Add:
766                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
767                         panic("Constant must be int or pointer for '+' to work");
768                 }
769                 emit_init_expression(env, get_Add_left(init));
770                 be_emit_cstring(" + ");
771                 emit_init_expression(env, get_Add_right(init));
772                 return;
773
774         case iro_Sub:
775                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
776                         panic("Constant must be int or pointer for '-' to work");
777                 }
778                 emit_init_expression(env, get_Sub_left(init));
779                 be_emit_cstring(" - ");
780                 emit_init_expression(env, get_Sub_right(init));
781                 return;
782
783         case iro_Mul:
784                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
785                         panic("Constant must be int or pointer for '*' to work");
786                 }
787                 emit_init_expression(env, get_Mul_left(init));
788                 be_emit_cstring(" * ");
789                 emit_init_expression(env, get_Mul_right(init));
790                 return;
791
792         case iro_Unknown:
793                 be_emit_cstring("0");
794                 return;
795
796         default:
797                 panic("emit_atomic_init(): unsupported IR-node %+F", init);
798         }
799 }
800
801 /**
802  * Dumps the type for given size (.byte, .long, ...)
803  *
804  * @param size  the size in bytes
805  */
806 static void emit_size_type(size_t size)
807 {
808         switch (size) {
809         case 1: be_emit_cstring("\t.byte\t");  break;
810         case 2: be_emit_cstring("\t.short\t"); break;
811         case 4: be_emit_cstring("\t.long\t");  break;
812         case 8: be_emit_cstring("\t.quad\t");  break;
813
814         default:
815                 panic("Try to dump a type with %u bytes", (unsigned)size);
816         }
817 }
818
819 /**
820  * Dump a string constant.
821  * No checks are made!!
822  *
823  * @param ent  The entity to dump.
824  */
825 static void emit_string_cst(const ir_entity *ent)
826 {
827         int      i, len;
828         int      output_len;
829         ir_type *type;
830         int      type_size;
831         int      remaining_space;
832
833         len        = get_compound_ent_n_values(ent);
834         output_len = len;
835         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
836                 be_emit_cstring("\t.ascii \"");
837         } else {
838                 be_emit_cstring("\t.string \"");
839                 output_len -= 1;
840         }
841
842         for (i = 0; i < output_len; ++i) {
843                 ir_node *irn;
844                 int c;
845
846                 irn = get_compound_ent_value(ent, i);
847                 c = (int) get_tarval_long(get_Const_tarval(irn));
848
849                 switch (c) {
850                 case '"' : be_emit_cstring("\\\""); break;
851                 case '\n': be_emit_cstring("\\n"); break;
852                 case '\r': be_emit_cstring("\\r"); break;
853                 case '\t': be_emit_cstring("\\t"); break;
854                 case '\\': be_emit_cstring("\\\\"); break;
855                 default  :
856                         if (isprint(c))
857                                 be_emit_char(c);
858                         else
859                                 be_emit_irprintf("\\%03o", c);
860                         break;
861                 }
862         }
863         be_emit_cstring("\"\n");
864         be_emit_write_line();
865
866         type            = get_entity_type(ent);
867         type_size       = get_type_size_bytes(type);
868         remaining_space = type_size - len;
869         assert(remaining_space >= 0);
870         if (remaining_space > 0) {
871                 be_emit_irprintf("\t.space\t%d, 0\n", remaining_space);
872         }
873 }
874
875 static size_t emit_string_initializer(const ir_initializer_t *initializer)
876 {
877         size_t i, len;
878
879         len = initializer->compound.n_initializers;
880         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
881                 be_emit_cstring("\t.ascii \"");
882         } else {
883                 be_emit_cstring("\t.string \"");
884                 len -= 1;
885         }
886
887         for (i = 0; i < len; ++i) {
888                 const ir_initializer_t *sub_initializer
889                         = get_initializer_compound_value(initializer, i);
890
891                 ir_tarval *tv = get_initializer_tarval(sub_initializer);
892                 int        c  = get_tarval_long(tv);
893
894                 switch (c) {
895                 case '"' : be_emit_cstring("\\\""); break;
896                 case '\n': be_emit_cstring("\\n"); break;
897                 case '\r': be_emit_cstring("\\r"); break;
898                 case '\t': be_emit_cstring("\\t"); break;
899                 case '\\': be_emit_cstring("\\\\"); break;
900                 default  :
901                         if (isprint(c))
902                                 be_emit_char(c);
903                         else
904                                 be_emit_irprintf("\\%03o", c);
905                         break;
906                 }
907         }
908         be_emit_cstring("\"\n");
909         be_emit_write_line();
910
911         return initializer->compound.n_initializers;
912 }
913
914 typedef enum normal_or_bitfield_kind {
915         NORMAL = 0,
916         TARVAL,
917         STRING,
918         BITFIELD
919 } normal_or_bitfield_kind;
920
921 typedef struct {
922         normal_or_bitfield_kind kind;
923         ir_type                *type;
924         union {
925                 ir_node                *value;
926                 ir_tarval              *tarval;
927                 unsigned char           bf_val;
928                 const ir_initializer_t *string;
929         } v;
930 } normal_or_bitfield;
931
932 static int is_type_variable_size(ir_type *type)
933 {
934         (void) type;
935         /* TODO */
936         return 0;
937 }
938
939 static size_t get_initializer_size(const ir_initializer_t *initializer,
940                                    ir_type *type)
941 {
942         switch (get_initializer_kind(initializer)) {
943         case IR_INITIALIZER_TARVAL:
944                 assert(get_tarval_mode(get_initializer_tarval_value(initializer)) == get_type_mode(type));
945                 return get_type_size_bytes(type);
946         case IR_INITIALIZER_CONST:
947         case IR_INITIALIZER_NULL:
948                 return get_type_size_bytes(type);
949         case IR_INITIALIZER_COMPOUND:
950                 if (!is_type_variable_size(type)) {
951                         return get_type_size_bytes(type);
952                 } else {
953                         size_t n_entries
954                                 = get_initializer_compound_n_entries(initializer);
955                         size_t i;
956                         unsigned initializer_size = get_type_size_bytes(type);
957                         for (i = 0; i < n_entries; ++i) {
958                                 ir_entity *entity = get_compound_member(type, i);
959                                 ir_type   *type   = get_entity_type(entity);
960
961                                 const ir_initializer_t *sub_initializer
962                                         = get_initializer_compound_value(initializer, i);
963
964                                 unsigned offset = get_entity_offset(entity);
965                                 unsigned size   = get_initializer_size(sub_initializer, type);
966
967                                 if (offset + size > initializer_size) {
968                                         initializer_size = offset + size;
969                                 }
970                         }
971                         return initializer_size;
972                 }
973         }
974
975         panic("found invalid initializer");
976 }
977
978 #ifndef NDEBUG
979 static normal_or_bitfield *glob_vals;
980 static size_t              max_vals;
981 #endif
982
983 static void emit_bitfield(normal_or_bitfield *vals, size_t offset_bits,
984                           const ir_initializer_t *initializer, ir_type *type)
985 {
986         static const size_t BITS_PER_BYTE = 8;
987         ir_mode   *mode      = get_type_mode(type);
988         ir_tarval *tv        = NULL;
989         int        value_len;
990         size_t     bit_offset;
991         size_t     end;
992         bool       big_endian = be_get_backend_param()->byte_order_big_endian;
993
994         switch (get_initializer_kind(initializer)) {
995         case IR_INITIALIZER_NULL:
996                 return;
997         case IR_INITIALIZER_TARVAL:
998                 tv = get_initializer_tarval_value(initializer);
999                 break;
1000         case IR_INITIALIZER_CONST: {
1001                 ir_node *node = get_initializer_const_value(initializer);
1002                 if (!is_Const(node)) {
1003                         panic("bitfield initializer not a Const node");
1004                 }
1005                 tv = get_Const_tarval(node);
1006                 break;
1007         }
1008         case IR_INITIALIZER_COMPOUND:
1009                 panic("bitfield initializer is compound");
1010         }
1011         if (tv == NULL) {
1012                 panic("Couldn't get numeric value for bitfield initializer");
1013         }
1014         tv = tarval_convert_to(tv, get_type_mode(type));
1015
1016         value_len  = get_type_size_bytes(get_primitive_base_type(type));
1017         bit_offset = 0;
1018         end        = get_mode_size_bits(mode);
1019         while (bit_offset < end) {
1020                 size_t        src_offset      = bit_offset / BITS_PER_BYTE;
1021                 size_t        src_offset_bits = bit_offset % BITS_PER_BYTE;
1022                 size_t        dst_offset      = (bit_offset+offset_bits) / BITS_PER_BYTE;
1023                 size_t        dst_offset_bits = (bit_offset+offset_bits) % BITS_PER_BYTE;
1024                 size_t        src_bits_len    = end-bit_offset;
1025                 size_t        dst_bits_len    = BITS_PER_BYTE-dst_offset_bits;
1026                 unsigned char curr_bits;
1027                 normal_or_bitfield *val;
1028                 if (src_bits_len > dst_bits_len)
1029                         src_bits_len = dst_bits_len;
1030
1031                 if (big_endian) {
1032                         val = &vals[value_len - dst_offset - 1];
1033                 } else {
1034                         val = &vals[dst_offset];
1035                 }
1036
1037                 assert((val-glob_vals) < (ptrdiff_t) max_vals);
1038                 assert(val->kind == BITFIELD ||
1039                                 (val->kind == NORMAL && val->v.value == NULL));
1040                 val->kind  = BITFIELD;
1041                 curr_bits  = get_tarval_sub_bits(tv, src_offset);
1042                 curr_bits  = curr_bits >> src_offset_bits;
1043                 if (src_offset_bits + src_bits_len > 8) {
1044                         unsigned next_bits = get_tarval_sub_bits(tv, src_offset+1);
1045                         curr_bits |= next_bits << (8 - src_offset_bits);
1046                 }
1047                 curr_bits &= (1 << src_bits_len) - 1;
1048                 val->v.bf_val |= curr_bits << dst_offset_bits;
1049
1050                 bit_offset += dst_bits_len;
1051         }
1052 }
1053
1054 static void emit_ir_initializer(normal_or_bitfield *vals,
1055                                 const ir_initializer_t *initializer,
1056                                 ir_type *type)
1057 {
1058         assert((size_t) (vals - glob_vals) < max_vals);
1059
1060         if (initializer_is_string_const(initializer)) {
1061                 assert(vals->kind != BITFIELD);
1062                 vals->kind     = STRING;
1063                 vals->v.string = initializer;
1064                 return;
1065         }
1066
1067         switch (get_initializer_kind(initializer)) {
1068         case IR_INITIALIZER_NULL:
1069                 return;
1070         case IR_INITIALIZER_TARVAL: {
1071                 size_t i;
1072
1073                 assert(vals->kind != BITFIELD);
1074                 vals->kind     = TARVAL;
1075                 vals->type     = type;
1076                 vals->v.tarval = get_initializer_tarval_value(initializer);
1077                 assert(get_type_mode(type) == get_tarval_mode(vals->v.tarval));
1078                 for (i = 1; i < get_type_size_bytes(type); ++i) {
1079                         vals[i].kind    = NORMAL;
1080                         vals[i].type    = NULL;
1081                         vals[i].v.value = NULL;
1082                 }
1083                 return;
1084         }
1085         case IR_INITIALIZER_CONST: {
1086                 size_t i;
1087
1088                 assert(vals->kind != BITFIELD);
1089                 vals->kind    = NORMAL;
1090                 vals->type    = type;
1091                 vals->v.value = get_initializer_const_value(initializer);
1092                 for (i = 1; i < get_type_size_bytes(type); ++i) {
1093                         vals[i].kind    = NORMAL;
1094                         vals[i].type    = NULL;
1095                         vals[i].v.value = NULL;
1096                 }
1097                 return;
1098         }
1099         case IR_INITIALIZER_COMPOUND: {
1100                 size_t i = 0;
1101                 size_t n = get_initializer_compound_n_entries(initializer);
1102
1103                 if (is_Array_type(type)) {
1104                         ir_type *element_type = get_array_element_type(type);
1105                         size_t   skip         = get_type_size_bytes(element_type);
1106                         size_t   alignment    = get_type_alignment_bytes(element_type);
1107                         size_t   misalign     = skip % alignment;
1108                         if (misalign != 0) {
1109                                 skip += alignment - misalign;
1110                         }
1111
1112                         for (i = 0; i < n; ++i) {
1113                                 ir_initializer_t *sub_initializer
1114                                         = get_initializer_compound_value(initializer, i);
1115
1116                                 emit_ir_initializer(vals, sub_initializer, element_type);
1117
1118                                 vals += skip;
1119                         }
1120                 } else {
1121                         size_t n_members, i;
1122                         assert(is_compound_type(type));
1123                         n_members = get_compound_n_members(type);
1124                         for (i = 0; i < n_members; ++i) {
1125                                 ir_entity        *member    = get_compound_member(type, i);
1126                                 size_t            offset    = get_entity_offset(member);
1127                                 ir_type          *subtype   = get_entity_type(member);
1128                                 ir_mode          *mode      = get_type_mode(subtype);
1129                                 ir_initializer_t *sub_initializer;
1130
1131                                 assert(i < get_initializer_compound_n_entries(initializer));
1132                                 sub_initializer
1133                                         = get_initializer_compound_value(initializer, i);
1134
1135                                 if (mode != NULL) {
1136                                         size_t offset_bits
1137                                                 = get_entity_offset_bits_remainder(member);
1138
1139                                         if (is_Primitive_type(subtype)
1140                                                         && get_primitive_base_type(subtype) != NULL) {
1141                                                 emit_bitfield(&vals[offset], offset_bits,
1142                                                               sub_initializer, subtype);
1143                                                 continue;
1144                                         } else {
1145                                                 assert(offset_bits == 0);
1146                                         }
1147                                 }
1148
1149                                 emit_ir_initializer(&vals[offset], sub_initializer, subtype);
1150                         }
1151                 }
1152
1153                 return;
1154         }
1155         }
1156         panic("invalid ir_initializer kind found");
1157 }
1158
1159 static void emit_tarval_data(ir_type *type, ir_tarval *tv)
1160 {
1161         size_t size = get_type_size_bytes(type);
1162         if (size == 12) {
1163                 /* this should be an x86 extended float */
1164                 assert(be_get_backend_param()->byte_order_big_endian == 0);
1165
1166                 /* Beware: Mixed endian output!  One little endian number emitted as
1167                  * three longs.  Each long initializer is written in big endian. */
1168                 be_emit_irprintf(
1169                         "\t.long\t0x%02x%02x%02x%02x\n"
1170                         "\t.long\t0x%02x%02x%02x%02x\n"
1171                         "\t.long\t0x%02x%02x%02x%02x\n",
1172                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
1173                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
1174                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
1175                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
1176                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
1177                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8)
1178                 );
1179                 be_emit_write_line();
1180         } else if (size == 16) {
1181                 if (be_get_backend_param()->byte_order_big_endian) {
1182                         be_emit_irprintf(
1183                                 "\t.long\t0x%02x%02x%02x%02x\n"
1184                                 "\t.long\t0x%02x%02x%02x%02x\n"
1185                                 "\t.long\t0x%02x%02x%02x%02x\n"
1186                                 "\t.long\t0x%02x%02x%02x%02x\n",
1187                                 get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 14),
1188                                 get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12),
1189                                 get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
1190                                 get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8),
1191                                 get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
1192                                 get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
1193                                 get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
1194                                 get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0)
1195                         );
1196                 } else {
1197                         /* Beware: Mixed endian output! One little endian number emitted as
1198                          * three longs.  Each long initializer is written in big endian. */
1199                         be_emit_irprintf(
1200                                 "\t.long\t0x%02x%02x%02x%02x\n"
1201                                 "\t.long\t0x%02x%02x%02x%02x\n"
1202                                 "\t.long\t0x%02x%02x%02x%02x\n"
1203                                 "\t.long\t0x%02x%02x%02x%02x\n",
1204                                 get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
1205                                 get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
1206                                 get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
1207                                 get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
1208                                 get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
1209                                 get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8),
1210                                 get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 14),
1211                                 get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12)
1212                         );
1213                 }
1214                 be_emit_write_line();
1215                 return;
1216         } else {
1217                 /* default case */
1218                 emit_size_type(size);
1219                 emit_arith_tarval(tv, size);
1220                 be_emit_char('\n');
1221                 be_emit_write_line();
1222         }
1223 }
1224
1225 /**
1226  * Emit an atomic value.
1227  *
1228  * @param env   the gas output environment
1229  * @param init  a node representing the atomic value (on the const code irg)
1230  */
1231 static void emit_node_data(be_gas_decl_env_t *env, ir_node *init, ir_type *type)
1232 {
1233         size_t size = get_type_size_bytes(type);
1234         if (size == 12 || size == 16) {
1235                 ir_tarval *tv;
1236                 if (!is_Const(init)) {
1237                         panic("12/16byte initializers only support Const nodes yet");
1238                 }
1239                 tv = get_Const_tarval(init);
1240                 emit_tarval_data(type, tv);
1241                 return;
1242         }
1243
1244         emit_size_type(size);
1245         emit_init_expression(env, init);
1246         be_emit_char('\n');
1247         be_emit_write_line();
1248 }
1249
1250 static void emit_initializer(be_gas_decl_env_t *env, const ir_entity *entity)
1251 {
1252         const ir_initializer_t *initializer = entity->initializer;
1253         ir_type                *type;
1254         normal_or_bitfield     *vals;
1255         size_t                  size;
1256         size_t                  k;
1257
1258         if (initializer_is_string_const(initializer)) {
1259                 emit_string_initializer(initializer);
1260                 return;
1261         }
1262
1263         type = get_entity_type(entity);
1264         size = get_initializer_size(initializer, type);
1265
1266         if (size == 0)
1267                 return;
1268
1269         /*
1270          * In the worst case, every initializer allocates one byte.
1271          * Moreover, initializer might be big, do not allocate on stack.
1272          */
1273         vals = XMALLOCNZ(normal_or_bitfield, size);
1274
1275 #ifndef NDEBUG
1276         glob_vals = vals;
1277         max_vals  = size;
1278 #endif
1279
1280         emit_ir_initializer(vals, initializer, type);
1281
1282         /* now write values sorted */
1283         for (k = 0; k < size; ) {
1284                 int                     space     = 0;
1285                 normal_or_bitfield_kind kind      = vals[k].kind;
1286                 int                     elem_size;
1287                 switch (kind) {
1288                 case NORMAL:
1289                         if (vals[k].v.value != NULL) {
1290                                 emit_node_data(env, vals[k].v.value, vals[k].type);
1291                                 elem_size = get_type_size_bytes(vals[k].type);
1292                         } else {
1293                                 elem_size = 0;
1294                         }
1295                         break;
1296                 case TARVAL:
1297                         emit_tarval_data(vals[k].type, vals[k].v.tarval);
1298                         elem_size = get_type_size_bytes(vals[k].type);
1299                         break;
1300                 case STRING:
1301                         elem_size = emit_string_initializer(vals[k].v.string);
1302                         break;
1303                 case BITFIELD:
1304                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1305                         be_emit_write_line();
1306                         elem_size = 1;
1307                         break;
1308                 default:
1309                         panic("internal compiler error (invalid normal_or_bitfield_kind");
1310                 }
1311
1312                 k += elem_size;
1313                 while (k < size && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1314                         ++space;
1315                         ++k;
1316                 }
1317
1318                 /* a gap */
1319                 if (space > 0) {
1320                         be_emit_irprintf("\t.space\t%d, 0\n", space);
1321                         be_emit_write_line();
1322                 }
1323         }
1324         xfree(vals);
1325 }
1326
1327 static void emit_compound_graph_init(be_gas_decl_env_t *env,
1328                                      const ir_entity *ent)
1329 {
1330         normal_or_bitfield *vals;
1331         int i, j, n;
1332         unsigned k, last_ofs;
1333
1334         if (entity_is_string_const(ent)) {
1335                 emit_string_cst(ent);
1336                 return;
1337         }
1338
1339         n = get_compound_ent_n_values(ent);
1340
1341         /* Find the initializer size. Sorrily gcc support a nasty feature:
1342            The last field of a compound may be a flexible array. This allows
1343            initializers bigger than the type size. */
1344         last_ofs = get_type_size_bytes(get_entity_type(ent));
1345         for (i = 0; i < n; ++i) {
1346                 unsigned offset         = get_compound_ent_value_offset_bytes(ent, i);
1347                 unsigned bits_remainder = get_compound_ent_value_offset_bit_remainder(ent, i);
1348                 ir_node  *value         = get_compound_ent_value(ent, i);
1349                 unsigned value_len      = get_mode_size_bits(get_irn_mode(value));
1350
1351                 offset += (value_len + bits_remainder + 7) >> 3;
1352
1353                 if (offset > last_ofs) {
1354                         last_ofs = offset;
1355                 }
1356         }
1357
1358         /*
1359          * In the worst case, every initializer allocates one byte.
1360          * Moreover, initializer might be big, do not allocate on stack.
1361          */
1362         vals = XMALLOCNZ(normal_or_bitfield, last_ofs);
1363
1364         /* collect the values and store them at the offsets */
1365         for (i = 0; i < n; ++i) {
1366                 unsigned offset      = get_compound_ent_value_offset_bytes(ent, i);
1367                 int      offset_bits = get_compound_ent_value_offset_bit_remainder(ent, i);
1368                 ir_node  *value      = get_compound_ent_value(ent, i);
1369                 int      value_len   = get_mode_size_bits(get_irn_mode(value));
1370
1371                 assert(offset_bits >= 0);
1372
1373                 if (offset_bits != 0 ||
1374                                 (value_len != 8 && value_len != 16 && value_len != 32 && value_len != 64)) {
1375                         ir_tarval *tv = get_atomic_init_tv(value);
1376                         unsigned char curr_bits, last_bits = 0;
1377                         if (tv == NULL) {
1378                                 panic("Couldn't get numeric value for bitfield initializer '%s'",
1379                                                 get_entity_ld_name(ent));
1380                         }
1381                         /* normalize offset */
1382                         offset += offset_bits >> 3;
1383                         offset_bits &= 7;
1384
1385                         for (j = 0; value_len + offset_bits > 0; ++j) {
1386                                 assert(offset + j < last_ofs);
1387                                 assert(vals[offset + j].kind == BITFIELD || vals[offset + j].v.value == NULL);
1388                                 vals[offset + j].kind = BITFIELD;
1389                                 curr_bits = get_tarval_sub_bits(tv, j);
1390                                 vals[offset + j].v.bf_val |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1391                                 value_len -= 8;
1392                                 last_bits = curr_bits;
1393                         }
1394                 } else {
1395                         int i;
1396
1397                         assert(offset < last_ofs);
1398                         assert(vals[offset].kind == NORMAL);
1399                         for (i = 1; i < value_len / 8; ++i) {
1400                                 assert(vals[offset + i].v.value == NULL);
1401                         }
1402                         vals[offset].v.value = value;
1403                 }
1404         }
1405
1406         /* now write them sorted */
1407         for (k = 0; k < last_ofs; ) {
1408                 int space = 0, skip = 0;
1409                 if (vals[k].kind == NORMAL) {
1410                         if (vals[k].v.value != NULL) {
1411                                 emit_node_data(env, vals[k].v.value, vals[k].type);
1412                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
1413                         } else {
1414                                 space = 1;
1415                         }
1416                 } else {
1417                         assert(vals[k].kind == BITFIELD);
1418                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1419                 }
1420
1421                 ++k;
1422                 while (k < last_ofs && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1423                         ++space;
1424                         ++k;
1425                 }
1426                 space -= skip;
1427                 assert(space >= 0);
1428
1429                 /* a gap */
1430                 if (space > 0) {
1431                         be_emit_irprintf("\t.space\t%d, 0\n", space);
1432                         be_emit_write_line();
1433                 }
1434         }
1435         xfree(vals);
1436 }
1437
1438 static void emit_align(unsigned p2alignment)
1439 {
1440         be_emit_irprintf("\t.p2align\t%u\n", log2_floor(p2alignment));
1441         be_emit_write_line();
1442 }
1443
1444 static unsigned get_effective_entity_alignment(const ir_entity *entity)
1445 {
1446         unsigned alignment = get_entity_alignment(entity);
1447         if (alignment == 0) {
1448                 ir_type *type = get_entity_type(entity);
1449                 alignment     = get_type_alignment_bytes(type);
1450         }
1451         return alignment;
1452 }
1453
1454 static void emit_common(const ir_entity *entity)
1455 {
1456         unsigned size      = get_type_size_bytes(get_entity_type(entity));
1457         unsigned alignment = get_effective_entity_alignment(entity);
1458
1459         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
1460                 emit_weak(entity);
1461         }
1462
1463         switch (be_gas_object_file_format) {
1464         case OBJECT_FILE_FORMAT_MACH_O:
1465                 be_emit_cstring("\t.comm ");
1466                 be_gas_emit_entity(entity);
1467                 be_emit_irprintf(",%u,%u\n", size, log2_floor(alignment));
1468                 be_emit_write_line();
1469                 return;
1470         case OBJECT_FILE_FORMAT_ELF:
1471                 be_emit_cstring("\t.comm ");
1472                 be_gas_emit_entity(entity);
1473                 be_emit_irprintf(",%u,%u\n", size, alignment);
1474                 be_emit_write_line();
1475                 return;
1476         case OBJECT_FILE_FORMAT_COFF:
1477                 be_emit_cstring("\t.comm ");
1478                 be_gas_emit_entity(entity);
1479                 be_emit_irprintf(",%u # %u\n", size, alignment);
1480                 be_emit_write_line();
1481                 return;
1482         }
1483         panic("invalid object file format");
1484 }
1485
1486 static void emit_local_common(const ir_entity *entity)
1487 {
1488         unsigned size      = get_type_size_bytes(get_entity_type(entity));
1489         unsigned alignment = get_effective_entity_alignment(entity);
1490
1491         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
1492                 emit_weak(entity);
1493         }
1494
1495         switch (be_gas_object_file_format) {
1496         case OBJECT_FILE_FORMAT_MACH_O:
1497                 be_emit_cstring("\t.lcomm ");
1498                 be_gas_emit_entity(entity);
1499                 be_emit_irprintf(",%u,%u\n", size, log2_floor(alignment));
1500                 be_emit_write_line();
1501                 return;
1502         case OBJECT_FILE_FORMAT_ELF:
1503                 be_emit_cstring("\t.local ");
1504                 be_gas_emit_entity(entity);
1505                 be_emit_cstring("\n");
1506                 be_emit_write_line();
1507                 be_emit_cstring("\t.comm ");
1508                 be_gas_emit_entity(entity);
1509                 be_emit_irprintf(",%u,%u\n", size, alignment);
1510                 be_emit_write_line();
1511                 return;
1512         case OBJECT_FILE_FORMAT_COFF:
1513                 be_emit_cstring("\t.lcomm ");
1514                 be_gas_emit_entity(entity);
1515                 be_emit_irprintf(",%u # %u\n", size, alignment);
1516                 be_emit_write_line();
1517                 return;
1518         }
1519         panic("invalid object file format");
1520 }
1521
1522 static void emit_indirect_symbol(const ir_entity *entity, be_gas_section_t section)
1523 {
1524         /* we can only do PIC code on macho so far */
1525         assert(be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O);
1526
1527         be_gas_emit_entity(entity);
1528         be_emit_cstring(":\n");
1529         be_emit_write_line();
1530         be_emit_cstring("\t.indirect_symbol ");
1531         be_emit_ident(get_entity_ident(entity));
1532         be_emit_char('\n');
1533         be_emit_write_line();
1534         if (section == GAS_SECTION_PIC_TRAMPOLINES) {
1535                 be_emit_cstring("\thlt ; hlt ; hlt ; hlt ; hlt\n");
1536                 be_emit_write_line();
1537         } else {
1538                 assert(section == GAS_SECTION_PIC_SYMBOLS);
1539                 be_emit_cstring("\t.long 0\n");
1540                 be_emit_write_line();
1541         }
1542 }
1543
1544 char const *be_gas_get_private_prefix(void)
1545 {
1546         return be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O ? "L" : ".L";
1547 }
1548
1549 void be_gas_emit_entity(const ir_entity *entity)
1550 {
1551         if (entity->type == firm_code_type) {
1552                 ir_label_t label = get_entity_label(entity);
1553                 be_emit_irprintf("%s_%lu", be_gas_get_private_prefix(), label);
1554                 return;
1555         }
1556
1557         if (get_entity_visibility(entity) == ir_visibility_private) {
1558                 be_emit_string(be_gas_get_private_prefix());
1559         }
1560         be_emit_ident(get_entity_ld_ident(entity));
1561 }
1562
1563 void be_gas_emit_block_name(const ir_node *block)
1564 {
1565         if (has_Block_entity(block)) {
1566                 ir_entity *entity = get_Block_entity(block);
1567                 be_gas_emit_entity(entity);
1568         } else {
1569                 be_emit_irprintf("%s%ld", be_gas_get_private_prefix(), get_irn_node_nr(block));
1570         }
1571 }
1572
1573 /**
1574  * Dump a global entity.
1575  *
1576  * @param env  the gas output environment
1577  * @param ent  the entity to be dumped
1578  */
1579 static void emit_global(be_gas_decl_env_t *env, const ir_entity *entity)
1580 {
1581         ir_type          *type       = get_entity_type(entity);
1582         ident            *ld_ident   = get_entity_ld_ident(entity);
1583         unsigned          alignment  = get_effective_entity_alignment(entity);
1584         be_gas_section_t  section    = determine_section(env, entity);
1585         ir_visibility     visibility = get_entity_visibility(entity);
1586         ir_linkage        linkage    = get_entity_linkage(entity);
1587
1588         /* block labels are already emittet in the code */
1589         if (type == firm_code_type)
1590                 return;
1591
1592         /* we already emitted all methods. Except for the trampolines which
1593          * the assembler/linker generates */
1594         if (is_Method_type(type) && section != GAS_SECTION_PIC_TRAMPOLINES) {
1595                 /* functions with graph are already emitted with
1596                  * be_gas_emit_function_prolog */
1597                 if (get_entity_irg(entity) == NULL) {
1598                         emit_visibility(entity);
1599                 }
1600                 return;
1601         }
1602
1603         be_dbg_variable(entity);
1604
1605         if (section == GAS_SECTION_BSS) {
1606                 switch (visibility) {
1607                 case ir_visibility_local:
1608                 case ir_visibility_private:
1609                         emit_local_common(entity);
1610                         return;
1611                 case ir_visibility_default:
1612                         if (linkage & IR_LINKAGE_MERGE) {
1613                                 emit_common(entity);
1614                                 return;
1615                         }
1616                         break;
1617                 case ir_visibility_external:
1618                         if (linkage & IR_LINKAGE_MERGE)
1619                                 panic("merge link semantic not supported for extern entities");
1620                         break;
1621                 }
1622         }
1623
1624         emit_visibility(entity);
1625         if (visibility == ir_visibility_external) {
1626                 /* nothing to do for externally defined values */
1627                 return;
1628         }
1629
1630         if (!is_po2(alignment))
1631                 panic("alignment not a power of 2");
1632
1633         emit_section(section, entity);
1634
1635         if (section == GAS_SECTION_PIC_TRAMPOLINES
1636                         || section == GAS_SECTION_PIC_SYMBOLS) {
1637                 emit_indirect_symbol(entity, section);
1638                 return;
1639         }
1640
1641         /* alignment */
1642         if (alignment > 1) {
1643                 emit_align(alignment);
1644         }
1645         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF
1646                         && be_gas_emit_types
1647                         && visibility != ir_visibility_private) {
1648                 be_emit_cstring("\t.type\t");
1649                 be_gas_emit_entity(entity);
1650                 be_emit_cstring(", ");
1651                 be_emit_char(be_gas_elf_type_char);
1652                 be_emit_cstring("object\n\t.size\t");\
1653                 be_gas_emit_entity(entity);
1654                 be_emit_irprintf(", %u\n", get_type_size_bytes(type));
1655         }
1656
1657         if (get_id_str(ld_ident)[0] != '\0') {
1658             be_gas_emit_entity(entity);
1659                 be_emit_cstring(":\n");
1660                 be_emit_write_line();
1661         }
1662
1663         if (entity_is_null(entity)) {
1664                 unsigned size = get_type_size_bytes(type);
1665                 if (size > 0) {
1666                         be_emit_irprintf("\t.space %u, 0\n", get_type_size_bytes(type));
1667                         be_emit_write_line();
1668                 }
1669         } else if (entity_has_compound_ent_values(entity)) {
1670                 emit_compound_graph_init(env, entity);
1671         } else {
1672                 assert(entity->initializer != NULL);
1673                 emit_initializer(env, entity);
1674         }
1675 }
1676
1677 /**
1678  * Dumps declarations of global variables and the initialization code.
1679  *
1680  * @param gt                a global like type, either the global or the TLS one
1681  * @param env               an environment
1682  */
1683 static void be_gas_emit_globals(ir_type *gt, be_gas_decl_env_t *env)
1684 {
1685         size_t i, n = get_compound_n_members(gt);
1686
1687         for (i = 0; i < n; i++) {
1688                 ir_entity *ent = get_compound_member(gt, i);
1689                 emit_global(env, ent);
1690         }
1691 }
1692
1693 /* Generate all entities. */
1694 static void emit_global_decls(const be_main_env_t *main_env)
1695 {
1696         be_gas_decl_env_t env;
1697         memset(&env, 0, sizeof(env));
1698
1699         /* dump global type */
1700         env.main_env = main_env;
1701         env.section  = (be_gas_section_t) -1;
1702
1703         be_gas_emit_globals(get_glob_type(), &env);
1704         be_gas_emit_globals(get_tls_type(), &env);
1705         be_gas_emit_globals(get_segment_type(IR_SEGMENT_CONSTRUCTORS), &env);
1706         be_gas_emit_globals(get_segment_type(IR_SEGMENT_DESTRUCTORS), &env);
1707         be_gas_emit_globals(main_env->pic_symbols_type, &env);
1708         be_gas_emit_globals(main_env->pic_trampolines_type, &env);
1709
1710         /**
1711          * ".subsections_via_symbols marks object files which are OK to divide
1712          * their section contents into individual blocks".
1713          * From my understanding this means no label points in the middle of an
1714          * object which we want to address as a whole. Firm code should be fine
1715          * with this.
1716          */
1717         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
1718                 be_emit_cstring("\t.subsections_via_symbols\n");
1719                 be_emit_write_line();
1720         }
1721 }
1722
1723 void be_emit_jump_table(const ir_node *node, const ir_switch_table *table,
1724                         ir_entity *entity, get_cfop_target_func get_cfop_target)
1725 {
1726         unsigned          n_outs    = arch_get_irn_n_outs(node);
1727         const ir_node   **targets   = XMALLOCNZ(const ir_node*, n_outs);
1728         size_t            n_entries = ir_switch_table_get_n_entries(table);
1729         unsigned long     length    = 0;
1730         size_t            e;
1731         const ir_edge_t  *edge;
1732         unsigned          i;
1733         const ir_node   **labels;
1734
1735         /* go over all proj's and collect their jump targets */
1736         foreach_out_edge(node, edge) {
1737                 ir_node *proj   = get_edge_src_irn(edge);
1738                 long     pn     = get_Proj_proj(proj);
1739                 ir_node *target = get_cfop_target(proj);
1740                 assert(targets[pn] == NULL);
1741                 targets[pn] = target;
1742         }
1743
1744         /* go over table to determine max value (note that we normalized the
1745          * ranges so that the minimum is 0) */
1746         for (e = 0; e < n_entries; ++e) {
1747                 const ir_switch_table_entry *entry
1748                         = ir_switch_table_get_entry_const(table, e);
1749                 ir_tarval *max = entry->max;
1750                 unsigned long val;
1751                 if (entry->pn == 0)
1752                         continue;
1753                 if (!tarval_is_long(max))
1754                         panic("switch case overflow (%+F)", node);
1755                 val = (unsigned long) get_tarval_long(max);
1756                 if (val > length) {
1757                         length = val;
1758                 }
1759         }
1760
1761         /* the 16000 isn't a real limit of the architecture. But should protect us
1762          * from seamingly endless compiler runs */
1763         if (length > 16000) {
1764                 /* switch lowerer should have broken this monster to pieces... */
1765                 panic("too large switch encountered (%+F)", node);
1766         }
1767         ++length;
1768
1769         labels = XMALLOCNZ(const ir_node*, length);
1770         for (e = 0; e < n_entries; ++e) {
1771                 const ir_switch_table_entry *entry
1772                         = ir_switch_table_get_entry_const(table, e);
1773                 ir_tarval     *min    = entry->min;
1774                 ir_tarval     *max    = entry->max;
1775                 const ir_node *target = targets[entry->pn];
1776                 assert(entry->pn < (long)n_outs);
1777                 if (min == max) {
1778                         unsigned long val = (unsigned long)get_tarval_long(max);
1779                         labels[val] = target;
1780                 } else {
1781                         unsigned long min_val;
1782                         unsigned long max_val;
1783                         unsigned long i;
1784                         if (!tarval_is_long(min))
1785                                 panic("switch case overflow (%+F)", node);
1786                         min_val = (unsigned long)get_tarval_long(min);
1787                         max_val = (unsigned long)get_tarval_long(max);
1788                         assert(min_val <= max_val);
1789                         for (i = min_val; i <= max_val; ++i) {
1790                                 labels[i] = target;
1791                         }
1792                 }
1793         }
1794
1795         /* emit table */
1796         if (entity != NULL) {
1797                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
1798                 be_emit_cstring("\t.align 4\n");
1799                 be_gas_emit_entity(entity);
1800                 be_emit_cstring(":\n");
1801         }
1802
1803         for (i = 0; i < length; ++i) {
1804                 const ir_node *block = labels[i];
1805                 if (block == NULL)
1806                         block = targets[0];
1807                 be_emit_cstring("\t.long ");
1808                 be_gas_emit_block_name(block);
1809                 be_emit_char('\n');
1810                 be_emit_write_line();
1811         }
1812
1813         if (entity != NULL)
1814                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
1815
1816         xfree(labels);
1817         xfree(targets);
1818 }
1819
1820 static void emit_global_asms(void)
1821 {
1822         size_t n = get_irp_n_asms();
1823         size_t i;
1824
1825         be_gas_emit_switch_section(GAS_SECTION_TEXT);
1826         for (i = 0; i < n; ++i) {
1827                 ident *asmtext = get_irp_asm(i);
1828
1829                 be_emit_cstring("#APP\n");
1830                 be_emit_write_line();
1831                 be_emit_ident(asmtext);
1832                 be_emit_char('\n');
1833                 be_emit_write_line();
1834                 be_emit_cstring("#NO_APP\n");
1835                 be_emit_write_line();
1836         }
1837 }
1838
1839 void be_gas_begin_compilation_unit(const be_main_env_t *env)
1840 {
1841         be_dbg_open();
1842         be_dbg_unit_begin(env->cup_name);
1843         be_dbg_types();
1844
1845         emit_global_asms();
1846 }
1847
1848 void be_gas_end_compilation_unit(const be_main_env_t *env)
1849 {
1850         emit_global_decls(env);
1851
1852         be_dbg_unit_end();
1853         be_dbg_close();
1854 }