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