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