bfb32a9f77a21d6531111276479686650288aeaa
[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 size_t get_initializer_size(const ir_initializer_t *initializer,
934                                    ir_type *type)
935 {
936         switch (get_initializer_kind(initializer)) {
937         case IR_INITIALIZER_TARVAL:
938                 assert(get_tarval_mode(get_initializer_tarval_value(initializer)) == get_type_mode(type));
939                 return get_type_size_bytes(type);
940         case IR_INITIALIZER_CONST:
941         case IR_INITIALIZER_NULL:
942                 return get_type_size_bytes(type);
943         case IR_INITIALIZER_COMPOUND:
944                 if (is_Array_type(type)) {
945                         if (is_array_variable_size(type)) {
946                                 ir_type   *element_type = get_array_element_type(type);
947                                 unsigned   element_size = get_type_size_bytes(element_type);
948                                 unsigned   element_align
949                                         = get_type_alignment_bytes(element_type);
950                                 unsigned   misalign     = element_size % element_align;
951                                 size_t     n_inits
952                                         = get_initializer_compound_n_entries(initializer);
953                                 element_size += element_align - misalign;
954                                 return n_inits * element_size;
955                         } else {
956                                 return get_type_size_bytes(type);
957                         }
958                 } else {
959                         assert(is_compound_type(type));
960                         size_t size = get_type_size_bytes(type);
961                         if (is_compound_variable_size(type)) {
962                                 /* last initializer has to be an array of variable size */
963                                 size_t l = get_initializer_compound_n_entries(initializer)-1;
964                                 const ir_initializer_t *last
965                                         = get_initializer_compound_value(initializer, l);
966                                 const ir_entity *last_ent  = get_compound_member(type, l);
967                                 ir_type         *last_type = get_entity_type(last_ent);
968                                 assert(is_array_variable_size(last_type));
969                                 size += get_initializer_size(last, last_type);
970                         }
971                         return size;
972                 }
973         }
974
975         panic("found invalid initializer");
976 }
977
978 #ifndef NDEBUG
979 static normal_or_bitfield *glob_vals;
980 static size_t              max_vals;
981 #endif
982
983 static void emit_bitfield(normal_or_bitfield *vals, size_t offset_bits,
984                           const ir_initializer_t *initializer, ir_type *type)
985 {
986         static const size_t BITS_PER_BYTE = 8;
987         ir_mode   *mode      = get_type_mode(type);
988         ir_tarval *tv        = NULL;
989         int        value_len;
990         size_t     bit_offset;
991         size_t     end;
992         bool       big_endian = be_get_backend_param()->byte_order_big_endian;
993
994         switch (get_initializer_kind(initializer)) {
995         case IR_INITIALIZER_NULL:
996                 return;
997         case IR_INITIALIZER_TARVAL:
998                 tv = get_initializer_tarval_value(initializer);
999                 break;
1000         case IR_INITIALIZER_CONST: {
1001                 ir_node *node = get_initializer_const_value(initializer);
1002                 if (!is_Const(node)) {
1003                         panic("bitfield initializer not a Const node");
1004                 }
1005                 tv = get_Const_tarval(node);
1006                 break;
1007         }
1008         case IR_INITIALIZER_COMPOUND:
1009                 panic("bitfield initializer is compound");
1010         }
1011         if (tv == NULL) {
1012                 panic("Couldn't get numeric value for bitfield initializer");
1013         }
1014         tv = tarval_convert_to(tv, get_type_mode(type));
1015
1016         value_len  = get_type_size_bytes(get_primitive_base_type(type));
1017         bit_offset = 0;
1018         end        = get_mode_size_bits(mode);
1019         while (bit_offset < end) {
1020                 size_t        src_offset      = bit_offset / BITS_PER_BYTE;
1021                 size_t        src_offset_bits = bit_offset % BITS_PER_BYTE;
1022                 size_t        dst_offset      = (bit_offset+offset_bits) / BITS_PER_BYTE;
1023                 size_t        dst_offset_bits = (bit_offset+offset_bits) % BITS_PER_BYTE;
1024                 size_t        src_bits_len    = end-bit_offset;
1025                 size_t        dst_bits_len    = BITS_PER_BYTE-dst_offset_bits;
1026                 unsigned char curr_bits;
1027                 normal_or_bitfield *val;
1028                 if (src_bits_len > dst_bits_len)
1029                         src_bits_len = dst_bits_len;
1030
1031                 if (big_endian) {
1032                         val = &vals[value_len - dst_offset - 1];
1033                 } else {
1034                         val = &vals[dst_offset];
1035                 }
1036
1037                 assert((val-glob_vals) < (ptrdiff_t) max_vals);
1038                 assert(val->kind == BITFIELD ||
1039                                 (val->kind == NORMAL && val->v.value == NULL));
1040                 val->kind  = BITFIELD;
1041                 curr_bits  = get_tarval_sub_bits(tv, src_offset);
1042                 curr_bits  = curr_bits >> src_offset_bits;
1043                 if (src_offset_bits + src_bits_len > 8) {
1044                         unsigned next_bits = get_tarval_sub_bits(tv, src_offset+1);
1045                         curr_bits |= next_bits << (8 - src_offset_bits);
1046                 }
1047                 curr_bits &= (1 << src_bits_len) - 1;
1048                 val->v.bf_val |= curr_bits << dst_offset_bits;
1049
1050                 bit_offset += dst_bits_len;
1051         }
1052 }
1053
1054 static void emit_ir_initializer(normal_or_bitfield *vals,
1055                                 const ir_initializer_t *initializer,
1056                                 ir_type *type)
1057 {
1058         assert((size_t) (vals - glob_vals) < max_vals);
1059
1060         if (initializer_is_string_const(initializer)) {
1061                 assert(vals->kind != BITFIELD);
1062                 vals->kind     = STRING;
1063                 vals->v.string = initializer;
1064                 return;
1065         }
1066
1067         switch (get_initializer_kind(initializer)) {
1068         case IR_INITIALIZER_NULL:
1069                 return;
1070         case IR_INITIALIZER_TARVAL: {
1071                 size_t i;
1072
1073                 assert(vals->kind != BITFIELD);
1074                 vals->kind     = TARVAL;
1075                 vals->type     = type;
1076                 vals->v.tarval = get_initializer_tarval_value(initializer);
1077                 assert(get_type_mode(type) == get_tarval_mode(vals->v.tarval));
1078                 for (i = 1; i < get_type_size_bytes(type); ++i) {
1079                         vals[i].kind    = NORMAL;
1080                         vals[i].type    = NULL;
1081                         vals[i].v.value = NULL;
1082                 }
1083                 return;
1084         }
1085         case IR_INITIALIZER_CONST: {
1086                 size_t i;
1087
1088                 assert(vals->kind != BITFIELD);
1089                 vals->kind    = NORMAL;
1090                 vals->type    = type;
1091                 vals->v.value = get_initializer_const_value(initializer);
1092                 for (i = 1; i < get_type_size_bytes(type); ++i) {
1093                         vals[i].kind    = NORMAL;
1094                         vals[i].type    = NULL;
1095                         vals[i].v.value = NULL;
1096                 }
1097                 return;
1098         }
1099         case IR_INITIALIZER_COMPOUND: {
1100                 size_t i = 0;
1101                 size_t n = get_initializer_compound_n_entries(initializer);
1102
1103                 if (is_Array_type(type)) {
1104                         ir_type *element_type = get_array_element_type(type);
1105                         size_t   skip         = get_type_size_bytes(element_type);
1106                         size_t   alignment    = get_type_alignment_bytes(element_type);
1107                         size_t   misalign     = skip % alignment;
1108                         if (misalign != 0) {
1109                                 skip += alignment - misalign;
1110                         }
1111
1112                         for (i = 0; i < n; ++i) {
1113                                 ir_initializer_t *sub_initializer
1114                                         = get_initializer_compound_value(initializer, i);
1115
1116                                 emit_ir_initializer(vals, sub_initializer, element_type);
1117
1118                                 vals += skip;
1119                         }
1120                 } else {
1121                         size_t n_members, i;
1122                         assert(is_compound_type(type));
1123                         n_members = get_compound_n_members(type);
1124                         for (i = 0; i < n_members; ++i) {
1125                                 ir_entity        *member    = get_compound_member(type, i);
1126                                 size_t            offset    = get_entity_offset(member);
1127                                 ir_type          *subtype   = get_entity_type(member);
1128                                 ir_mode          *mode      = get_type_mode(subtype);
1129                                 ir_initializer_t *sub_initializer;
1130
1131                                 assert(i < get_initializer_compound_n_entries(initializer));
1132                                 sub_initializer
1133                                         = get_initializer_compound_value(initializer, i);
1134
1135                                 if (mode != NULL) {
1136                                         size_t offset_bits
1137                                                 = get_entity_offset_bits_remainder(member);
1138
1139                                         if (is_Primitive_type(subtype)
1140                                                         && get_primitive_base_type(subtype) != NULL) {
1141                                                 emit_bitfield(&vals[offset], offset_bits,
1142                                                               sub_initializer, subtype);
1143                                                 continue;
1144                                         } else {
1145                                                 assert(offset_bits == 0);
1146                                         }
1147                                 }
1148
1149                                 emit_ir_initializer(&vals[offset], sub_initializer, subtype);
1150                         }
1151                 }
1152
1153                 return;
1154         }
1155         }
1156         panic("invalid ir_initializer kind found");
1157 }
1158
1159 static void emit_tarval_data(ir_type *type, ir_tarval *tv)
1160 {
1161         size_t size = get_type_size_bytes(type);
1162         if (size == 12) {
1163                 /* this should be an x86 extended float */
1164                 assert(be_get_backend_param()->byte_order_big_endian == 0);
1165
1166                 /* Beware: Mixed endian output!  One little endian number emitted as
1167                  * three longs.  Each long initializer is written in big endian. */
1168                 be_emit_irprintf(
1169                         "\t.long\t0x%02x%02x%02x%02x\n"
1170                         "\t.long\t0x%02x%02x%02x%02x\n"
1171                         "\t.long\t0x%02x%02x%02x%02x\n",
1172                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
1173                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
1174                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
1175                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
1176                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
1177                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8)
1178                 );
1179                 be_emit_write_line();
1180         } else if (size == 16) {
1181                 if (be_get_backend_param()->byte_order_big_endian) {
1182                         be_emit_irprintf(
1183                                 "\t.long\t0x%02x%02x%02x%02x\n"
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                                 get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 14),
1188                                 get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12),
1189                                 get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
1190                                 get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8),
1191                                 get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
1192                                 get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
1193                                 get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
1194                                 get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0)
1195                         );
1196                 } else {
1197                         /* Beware: Mixed endian output! One little endian number emitted as
1198                          * three longs.  Each long initializer is written in big endian. */
1199                         be_emit_irprintf(
1200                                 "\t.long\t0x%02x%02x%02x%02x\n"
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                                 get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
1205                                 get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
1206                                 get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
1207                                 get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
1208                                 get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
1209                                 get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8),
1210                                 get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 14),
1211                                 get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12)
1212                         );
1213                 }
1214                 be_emit_write_line();
1215                 return;
1216         } else {
1217                 /* default case */
1218                 emit_size_type(size);
1219                 emit_arith_tarval(tv, size);
1220                 be_emit_char('\n');
1221                 be_emit_write_line();
1222         }
1223 }
1224
1225 /**
1226  * Emit an atomic value.
1227  *
1228  * @param env   the gas output environment
1229  * @param init  a node representing the atomic value (on the const code irg)
1230  */
1231 static void emit_node_data(be_gas_decl_env_t *env, ir_node *init, ir_type *type)
1232 {
1233         size_t size = get_type_size_bytes(type);
1234         if (size == 12 || size == 16) {
1235                 ir_tarval *tv;
1236                 if (!is_Const(init)) {
1237                         panic("12/16byte initializers only support Const nodes yet");
1238                 }
1239                 tv = get_Const_tarval(init);
1240                 emit_tarval_data(type, tv);
1241                 return;
1242         }
1243
1244         emit_size_type(size);
1245         emit_init_expression(env, init);
1246         be_emit_char('\n');
1247         be_emit_write_line();
1248 }
1249
1250 static void emit_initializer(be_gas_decl_env_t *env, const ir_entity *entity)
1251 {
1252         const ir_initializer_t *initializer = entity->initializer;
1253         ir_type                *type;
1254         normal_or_bitfield     *vals;
1255         size_t                  size;
1256         size_t                  k;
1257
1258         if (initializer_is_string_const(initializer)) {
1259                 emit_string_initializer(initializer);
1260                 return;
1261         }
1262
1263         type = get_entity_type(entity);
1264         size = get_initializer_size(initializer, type);
1265
1266         if (size == 0)
1267                 return;
1268
1269         /*
1270          * In the worst case, every initializer allocates one byte.
1271          * Moreover, initializer might be big, do not allocate on stack.
1272          */
1273         vals = XMALLOCNZ(normal_or_bitfield, size);
1274
1275 #ifndef NDEBUG
1276         glob_vals = vals;
1277         max_vals  = size;
1278 #endif
1279
1280         emit_ir_initializer(vals, initializer, type);
1281
1282         /* now write values sorted */
1283         for (k = 0; k < size; ) {
1284                 int                     space     = 0;
1285                 normal_or_bitfield_kind kind      = vals[k].kind;
1286                 int                     elem_size;
1287                 switch (kind) {
1288                 case NORMAL:
1289                         if (vals[k].v.value != NULL) {
1290                                 emit_node_data(env, vals[k].v.value, vals[k].type);
1291                                 elem_size = get_type_size_bytes(vals[k].type);
1292                         } else {
1293                                 elem_size = 0;
1294                         }
1295                         break;
1296                 case TARVAL:
1297                         emit_tarval_data(vals[k].type, vals[k].v.tarval);
1298                         elem_size = get_type_size_bytes(vals[k].type);
1299                         break;
1300                 case STRING:
1301                         elem_size = emit_string_initializer(vals[k].v.string);
1302                         break;
1303                 case BITFIELD:
1304                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1305                         be_emit_write_line();
1306                         elem_size = 1;
1307                         break;
1308                 default:
1309                         panic("internal compiler error (invalid normal_or_bitfield_kind");
1310                 }
1311
1312                 k += elem_size;
1313                 while (k < size && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1314                         ++space;
1315                         ++k;
1316                 }
1317
1318                 /* a gap */
1319                 if (space > 0) {
1320                         be_emit_irprintf("\t.space\t%d, 0\n", space);
1321                         be_emit_write_line();
1322                 }
1323         }
1324         xfree(vals);
1325 }
1326
1327 static void emit_compound_graph_init(be_gas_decl_env_t *env,
1328                                      const ir_entity *ent)
1329 {
1330         normal_or_bitfield *vals;
1331         int i, j, n;
1332         unsigned k, last_ofs;
1333
1334         if (entity_is_string_const(ent)) {
1335                 emit_string_cst(ent);
1336                 return;
1337         }
1338
1339         n = get_compound_ent_n_values(ent);
1340
1341         /* Find the initializer size. Sorrily gcc support a nasty feature:
1342            The last field of a compound may be a flexible array. This allows
1343            initializers bigger than the type size. */
1344         last_ofs = get_type_size_bytes(get_entity_type(ent));
1345         for (i = 0; i < n; ++i) {
1346                 unsigned offset         = get_compound_ent_value_offset_bytes(ent, i);
1347                 unsigned bits_remainder = get_compound_ent_value_offset_bit_remainder(ent, i);
1348                 ir_node  *value         = get_compound_ent_value(ent, i);
1349                 unsigned value_len      = get_mode_size_bits(get_irn_mode(value));
1350
1351                 offset += (value_len + bits_remainder + 7) >> 3;
1352
1353                 if (offset > last_ofs) {
1354                         last_ofs = offset;
1355                 }
1356         }
1357
1358         /*
1359          * In the worst case, every initializer allocates one byte.
1360          * Moreover, initializer might be big, do not allocate on stack.
1361          */
1362         vals = XMALLOCNZ(normal_or_bitfield, last_ofs);
1363
1364         /* collect the values and store them at the offsets */
1365         for (i = 0; i < n; ++i) {
1366                 unsigned offset      = get_compound_ent_value_offset_bytes(ent, i);
1367                 int      offset_bits = get_compound_ent_value_offset_bit_remainder(ent, i);
1368                 ir_node  *value      = get_compound_ent_value(ent, i);
1369                 int      value_len   = get_mode_size_bits(get_irn_mode(value));
1370
1371                 assert(offset_bits >= 0);
1372
1373                 if (offset_bits != 0 ||
1374                                 (value_len != 8 && value_len != 16 && value_len != 32 && value_len != 64)) {
1375                         ir_tarval *tv = get_atomic_init_tv(value);
1376                         unsigned char curr_bits, last_bits = 0;
1377                         if (tv == NULL) {
1378                                 panic("Couldn't get numeric value for bitfield initializer '%s'",
1379                                                 get_entity_ld_name(ent));
1380                         }
1381                         /* normalize offset */
1382                         offset += offset_bits >> 3;
1383                         offset_bits &= 7;
1384
1385                         for (j = 0; value_len + offset_bits > 0; ++j) {
1386                                 assert(offset + j < last_ofs);
1387                                 assert(vals[offset + j].kind == BITFIELD || vals[offset + j].v.value == NULL);
1388                                 vals[offset + j].kind = BITFIELD;
1389                                 curr_bits = get_tarval_sub_bits(tv, j);
1390                                 vals[offset + j].v.bf_val |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1391                                 value_len -= 8;
1392                                 last_bits = curr_bits;
1393                         }
1394                 } else {
1395                         int i;
1396
1397                         assert(offset < last_ofs);
1398                         assert(vals[offset].kind == NORMAL);
1399                         for (i = 1; i < value_len / 8; ++i) {
1400                                 assert(vals[offset + i].v.value == NULL);
1401                         }
1402                         vals[offset].v.value = value;
1403                 }
1404         }
1405
1406         /* now write them sorted */
1407         for (k = 0; k < last_ofs; ) {
1408                 int space = 0, skip = 0;
1409                 if (vals[k].kind == NORMAL) {
1410                         if (vals[k].v.value != NULL) {
1411                                 emit_node_data(env, vals[k].v.value, vals[k].type);
1412                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
1413                         } else {
1414                                 space = 1;
1415                         }
1416                 } else {
1417                         assert(vals[k].kind == BITFIELD);
1418                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1419                 }
1420
1421                 ++k;
1422                 while (k < last_ofs && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1423                         ++space;
1424                         ++k;
1425                 }
1426                 space -= skip;
1427                 assert(space >= 0);
1428
1429                 /* a gap */
1430                 if (space > 0) {
1431                         be_emit_irprintf("\t.space\t%d, 0\n", space);
1432                         be_emit_write_line();
1433                 }
1434         }
1435         xfree(vals);
1436 }
1437
1438 static void emit_align(unsigned p2alignment)
1439 {
1440         be_emit_irprintf("\t.p2align\t%u\n", log2_floor(p2alignment));
1441         be_emit_write_line();
1442 }
1443
1444 static unsigned get_effective_entity_alignment(const ir_entity *entity)
1445 {
1446         unsigned alignment = get_entity_alignment(entity);
1447         if (alignment == 0) {
1448                 ir_type *type = get_entity_type(entity);
1449                 alignment     = get_type_alignment_bytes(type);
1450         }
1451         return alignment;
1452 }
1453
1454 static void emit_common(const ir_entity *entity)
1455 {
1456         unsigned size      = get_type_size_bytes(get_entity_type(entity));
1457         unsigned alignment = get_effective_entity_alignment(entity);
1458
1459         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
1460                 emit_weak(entity);
1461         }
1462
1463         switch (be_gas_object_file_format) {
1464         case OBJECT_FILE_FORMAT_MACH_O:
1465                 be_emit_cstring("\t.comm ");
1466                 be_gas_emit_entity(entity);
1467                 be_emit_irprintf(",%u,%u\n", size, log2_floor(alignment));
1468                 be_emit_write_line();
1469                 return;
1470         case OBJECT_FILE_FORMAT_ELF:
1471                 be_emit_cstring("\t.comm ");
1472                 be_gas_emit_entity(entity);
1473                 be_emit_irprintf(",%u,%u\n", size, alignment);
1474                 be_emit_write_line();
1475                 return;
1476         case OBJECT_FILE_FORMAT_COFF:
1477                 be_emit_cstring("\t.comm ");
1478                 be_gas_emit_entity(entity);
1479                 be_emit_irprintf(",%u # %u\n", size, alignment);
1480                 be_emit_write_line();
1481                 return;
1482         }
1483         panic("invalid object file format");
1484 }
1485
1486 static void emit_local_common(const ir_entity *entity)
1487 {
1488         unsigned size      = get_type_size_bytes(get_entity_type(entity));
1489         unsigned alignment = get_effective_entity_alignment(entity);
1490
1491         if (get_entity_linkage(entity) & IR_LINKAGE_WEAK) {
1492                 emit_weak(entity);
1493         }
1494
1495         switch (be_gas_object_file_format) {
1496         case OBJECT_FILE_FORMAT_MACH_O:
1497                 be_emit_cstring("\t.lcomm ");
1498                 be_gas_emit_entity(entity);
1499                 be_emit_irprintf(",%u,%u\n", size, log2_floor(alignment));
1500                 be_emit_write_line();
1501                 return;
1502         case OBJECT_FILE_FORMAT_ELF:
1503                 be_emit_cstring("\t.local ");
1504                 be_gas_emit_entity(entity);
1505                 be_emit_cstring("\n");
1506                 be_emit_write_line();
1507                 be_emit_cstring("\t.comm ");
1508                 be_gas_emit_entity(entity);
1509                 be_emit_irprintf(",%u,%u\n", size, alignment);
1510                 be_emit_write_line();
1511                 return;
1512         case OBJECT_FILE_FORMAT_COFF:
1513                 be_emit_cstring("\t.lcomm ");
1514                 be_gas_emit_entity(entity);
1515                 be_emit_irprintf(",%u # %u\n", size, alignment);
1516                 be_emit_write_line();
1517                 return;
1518         }
1519         panic("invalid object file format");
1520 }
1521
1522 static void emit_indirect_symbol(const ir_entity *entity, be_gas_section_t section)
1523 {
1524         /* we can only do PIC code on macho so far */
1525         assert(be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O);
1526
1527         be_gas_emit_entity(entity);
1528         be_emit_cstring(":\n");
1529         be_emit_write_line();
1530         be_emit_cstring("\t.indirect_symbol ");
1531         be_emit_ident(get_entity_ident(entity));
1532         be_emit_char('\n');
1533         be_emit_write_line();
1534         if (section == GAS_SECTION_PIC_TRAMPOLINES) {
1535                 be_emit_cstring("\thlt ; hlt ; hlt ; hlt ; hlt\n");
1536                 be_emit_write_line();
1537         } else {
1538                 assert(section == GAS_SECTION_PIC_SYMBOLS);
1539                 be_emit_cstring("\t.long 0\n");
1540                 be_emit_write_line();
1541         }
1542 }
1543
1544 char const *be_gas_get_private_prefix(void)
1545 {
1546         return be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O ? "L" : ".L";
1547 }
1548
1549 void be_gas_emit_entity(const ir_entity *entity)
1550 {
1551         if (entity->type == get_code_type()) {
1552                 ir_label_t label = get_entity_label(entity);
1553                 be_emit_irprintf("%s_%lu", be_gas_get_private_prefix(), label);
1554                 return;
1555         }
1556
1557         if (get_entity_visibility(entity) == ir_visibility_private) {
1558                 be_emit_string(be_gas_get_private_prefix());
1559         }
1560         be_emit_ident(get_entity_ld_ident(entity));
1561 }
1562
1563 void be_gas_emit_block_name(const ir_node *block)
1564 {
1565         if (get_Block_entity(block) != NULL) {
1566                 ir_entity *entity = get_Block_entity(block);
1567                 be_gas_emit_entity(entity);
1568         } else {
1569                 be_emit_irprintf("%s%ld", be_gas_get_private_prefix(), get_irn_node_nr(block));
1570         }
1571 }
1572
1573 /**
1574  * Dump a global entity.
1575  *
1576  * @param env  the gas output environment
1577  * @param ent  the entity to be dumped
1578  */
1579 static void emit_global(be_gas_decl_env_t *env, const ir_entity *entity)
1580 {
1581         ir_type          *type       = get_entity_type(entity);
1582         ident            *ld_ident   = get_entity_ld_ident(entity);
1583         unsigned          alignment  = get_effective_entity_alignment(entity);
1584         be_gas_section_t  section    = determine_section(env, entity);
1585         ir_visibility     visibility = get_entity_visibility(entity);
1586         ir_linkage        linkage    = get_entity_linkage(entity);
1587
1588         /* block labels are already emittet in the code */
1589         if (type == get_code_type())
1590                 return;
1591
1592         /* we already emitted all methods. Except for the trampolines which
1593          * the assembler/linker generates */
1594         if (is_Method_type(type) && section != GAS_SECTION_PIC_TRAMPOLINES) {
1595                 /* functions with graph are already emitted with
1596                  * be_gas_emit_function_prolog */
1597                 if (get_entity_irg(entity) == NULL) {
1598                         emit_visibility(entity);
1599                 }
1600                 return;
1601         }
1602
1603         be_dbg_variable(entity);
1604
1605         if (section == GAS_SECTION_BSS) {
1606                 switch (visibility) {
1607                 case ir_visibility_local:
1608                 case ir_visibility_private:
1609                         emit_local_common(entity);
1610                         return;
1611                 case ir_visibility_default:
1612                         if (linkage & IR_LINKAGE_MERGE) {
1613                                 emit_common(entity);
1614                                 return;
1615                         }
1616                         break;
1617                 case ir_visibility_external:
1618                         if (linkage & IR_LINKAGE_MERGE)
1619                                 panic("merge link semantic not supported for extern entities");
1620                         break;
1621                 }
1622         }
1623
1624         emit_visibility(entity);
1625         if (visibility == ir_visibility_external) {
1626                 /* nothing to do for externally defined values */
1627                 return;
1628         }
1629
1630         if (!is_po2(alignment))
1631                 panic("alignment not a power of 2");
1632
1633         emit_section(section, entity);
1634
1635         if (section == GAS_SECTION_PIC_TRAMPOLINES
1636                         || section == GAS_SECTION_PIC_SYMBOLS) {
1637                 emit_indirect_symbol(entity, section);
1638                 return;
1639         }
1640
1641         /* alignment */
1642         if (alignment > 1) {
1643                 emit_align(alignment);
1644         }
1645         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_ELF
1646                         && be_gas_emit_types
1647                         && visibility != ir_visibility_private) {
1648                 be_emit_cstring("\t.type\t");
1649                 be_gas_emit_entity(entity);
1650                 be_emit_cstring(", ");
1651                 be_emit_char(be_gas_elf_type_char);
1652                 be_emit_cstring("object\n\t.size\t");\
1653                 be_gas_emit_entity(entity);
1654                 be_emit_irprintf(", %u\n", get_type_size_bytes(type));
1655         }
1656
1657         if (get_id_str(ld_ident)[0] != '\0') {
1658             be_gas_emit_entity(entity);
1659                 be_emit_cstring(":\n");
1660                 be_emit_write_line();
1661         }
1662
1663         if (entity_is_null(entity)) {
1664                 unsigned size = get_type_size_bytes(type);
1665                 if (size > 0) {
1666                         be_emit_irprintf("\t.space %u, 0\n", get_type_size_bytes(type));
1667                         be_emit_write_line();
1668                 }
1669         } else if (entity_has_compound_ent_values(entity)) {
1670                 emit_compound_graph_init(env, entity);
1671         } else {
1672                 assert(entity->initializer != NULL);
1673                 emit_initializer(env, entity);
1674         }
1675 }
1676
1677 /**
1678  * Dumps declarations of global variables and the initialization code.
1679  *
1680  * @param gt                a global like type, either the global or the TLS one
1681  * @param env               an environment
1682  */
1683 static void be_gas_emit_globals(ir_type *gt, be_gas_decl_env_t *env)
1684 {
1685         size_t i, n = get_compound_n_members(gt);
1686
1687         for (i = 0; i < n; i++) {
1688                 ir_entity *ent = get_compound_member(gt, i);
1689                 emit_global(env, ent);
1690         }
1691 }
1692
1693 /* Generate all entities. */
1694 static void emit_global_decls(const be_main_env_t *main_env)
1695 {
1696         be_gas_decl_env_t env;
1697         memset(&env, 0, sizeof(env));
1698
1699         /* dump global type */
1700         env.main_env = main_env;
1701         env.section  = (be_gas_section_t) -1;
1702
1703         be_gas_emit_globals(get_glob_type(), &env);
1704         be_gas_emit_globals(get_tls_type(), &env);
1705         be_gas_emit_globals(get_segment_type(IR_SEGMENT_CONSTRUCTORS), &env);
1706         be_gas_emit_globals(get_segment_type(IR_SEGMENT_DESTRUCTORS), &env);
1707         be_gas_emit_globals(main_env->pic_symbols_type, &env);
1708         be_gas_emit_globals(main_env->pic_trampolines_type, &env);
1709
1710         /**
1711          * ".subsections_via_symbols marks object files which are OK to divide
1712          * their section contents into individual blocks".
1713          * From my understanding this means no label points in the middle of an
1714          * object which we want to address as a whole. Firm code should be fine
1715          * with this.
1716          */
1717         if (be_gas_object_file_format == OBJECT_FILE_FORMAT_MACH_O) {
1718                 be_emit_cstring("\t.subsections_via_symbols\n");
1719                 be_emit_write_line();
1720         }
1721 }
1722
1723 void be_emit_jump_table(const ir_node *node, const ir_switch_table *table,
1724                         ir_entity *entity, get_cfop_target_func get_cfop_target)
1725 {
1726         unsigned          n_outs    = arch_get_irn_n_outs(node);
1727         const ir_node   **targets   = XMALLOCNZ(const ir_node*, n_outs);
1728         size_t            n_entries = ir_switch_table_get_n_entries(table);
1729         unsigned long     length    = 0;
1730         size_t            e;
1731         const ir_edge_t  *edge;
1732         unsigned          i;
1733         const ir_node   **labels;
1734
1735         /* go over all proj's and collect their jump targets */
1736         foreach_out_edge(node, edge) {
1737                 ir_node *proj   = get_edge_src_irn(edge);
1738                 long     pn     = get_Proj_proj(proj);
1739                 ir_node *target = get_cfop_target(proj);
1740                 assert(targets[pn] == NULL);
1741                 targets[pn] = target;
1742         }
1743
1744         /* go over table to determine max value (note that we normalized the
1745          * ranges so that the minimum is 0) */
1746         for (e = 0; e < n_entries; ++e) {
1747                 const ir_switch_table_entry *entry
1748                         = ir_switch_table_get_entry_const(table, e);
1749                 ir_tarval *max = entry->max;
1750                 unsigned long val;
1751                 if (entry->pn == 0)
1752                         continue;
1753                 if (!tarval_is_long(max))
1754                         panic("switch case overflow (%+F)", node);
1755                 val = (unsigned long) get_tarval_long(max);
1756                 if (val > length) {
1757                         length = val;
1758                 }
1759         }
1760
1761         /* the 16000 isn't a real limit of the architecture. But should protect us
1762          * from seamingly endless compiler runs */
1763         if (length > 16000) {
1764                 /* switch lowerer should have broken this monster to pieces... */
1765                 panic("too large switch encountered (%+F)", node);
1766         }
1767         ++length;
1768
1769         labels = XMALLOCNZ(const ir_node*, length);
1770         for (e = 0; e < n_entries; ++e) {
1771                 const ir_switch_table_entry *entry
1772                         = ir_switch_table_get_entry_const(table, e);
1773                 ir_tarval     *min    = entry->min;
1774                 ir_tarval     *max    = entry->max;
1775                 const ir_node *target = targets[entry->pn];
1776                 assert(entry->pn < (long)n_outs);
1777                 if (min == max) {
1778                         unsigned long val = (unsigned long)get_tarval_long(max);
1779                         labels[val] = target;
1780                 } else {
1781                         unsigned long min_val;
1782                         unsigned long max_val;
1783                         unsigned long i;
1784                         if (!tarval_is_long(min))
1785                                 panic("switch case overflow (%+F)", node);
1786                         min_val = (unsigned long)get_tarval_long(min);
1787                         max_val = (unsigned long)get_tarval_long(max);
1788                         assert(min_val <= max_val);
1789                         for (i = min_val; i <= max_val; ++i) {
1790                                 labels[i] = target;
1791                         }
1792                 }
1793         }
1794
1795         /* emit table */
1796         if (entity != NULL) {
1797                 be_gas_emit_switch_section(GAS_SECTION_RODATA);
1798                 be_emit_cstring("\t.align 4\n");
1799                 be_gas_emit_entity(entity);
1800                 be_emit_cstring(":\n");
1801         }
1802
1803         for (i = 0; i < length; ++i) {
1804                 const ir_node *block = labels[i];
1805                 if (block == NULL)
1806                         block = targets[0];
1807                 be_emit_cstring("\t.long ");
1808                 be_gas_emit_block_name(block);
1809                 be_emit_char('\n');
1810                 be_emit_write_line();
1811         }
1812
1813         if (entity != NULL)
1814                 be_gas_emit_switch_section(GAS_SECTION_TEXT);
1815
1816         xfree(labels);
1817         xfree(targets);
1818 }
1819
1820 static void emit_global_asms(void)
1821 {
1822         size_t n = get_irp_n_asms();
1823         size_t i;
1824
1825         be_gas_emit_switch_section(GAS_SECTION_TEXT);
1826         for (i = 0; i < n; ++i) {
1827                 ident *asmtext = get_irp_asm(i);
1828
1829                 be_emit_cstring("#APP\n");
1830                 be_emit_write_line();
1831                 be_emit_ident(asmtext);
1832                 be_emit_char('\n');
1833                 be_emit_write_line();
1834                 be_emit_cstring("#NO_APP\n");
1835                 be_emit_write_line();
1836         }
1837 }
1838
1839 void be_gas_begin_compilation_unit(const be_main_env_t *env)
1840 {
1841         be_dbg_open();
1842         be_dbg_unit_begin(env->cup_name);
1843         be_dbg_types();
1844
1845         emit_global_asms();
1846 }
1847
1848 void be_gas_end_compilation_unit(const be_main_env_t *env)
1849 {
1850         emit_global_decls(env);
1851
1852         be_dbg_unit_end();
1853         be_dbg_close();
1854 }