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