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