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