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