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