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