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