be0d0ead87f4f7f4ee0289988f43c7d4403bdab9
[libfirm] / ir / be / begnuas.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Dumps global variables and constants as gas assembler.
23  * @author      Christian Wuerdig, Matthias Braun
24  * @date        04.11.2005
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include "begnuas.h"
30
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <assert.h>
35
36 #include "obst.h"
37 #include "tv.h"
38 #include "irnode.h"
39 #include "irprog.h"
40 #include "pdeq.h"
41 #include "entity_t.h"
42 #include "error.h"
43
44 #include "be_t.h"
45 #include "beemitter.h"
46 #include "be_dbgout.h"
47
48 /** by default, we generate assembler code for the Linux gas */
49 be_gas_flavour_t be_gas_flavour       = GAS_FLAVOUR_ELF;
50 char             be_gas_elf_type_char = '@';
51 bool             be_gas_emit_types    = true;
52
53 static be_gas_section_t current_section = (be_gas_section_t) -1;
54
55 /**
56  * Return the pseudo-instruction to be issued for a section switch
57  * depending on the current flavour.
58  *
59  * @param section  the section to switch to
60  *
61  * @return  the pseudo-instruction
62  */
63 static const char *get_section_name(be_gas_section_t section) {
64         static const char *text[GAS_FLAVOUR_LAST+1][GAS_SECTION_LAST+1] = {
65                 { /* GAS_FLAVOUR_ELF */
66                         ".section\t.text",
67                         ".section\t.data",
68                         ".section\t.rodata",
69                         ".section\t.bss",
70                         ".section\t.tbss,\"awT\",@nobits",
71                         ".section\t.ctors,\"aw\",@progbits",
72                         ".section\t.dtors,\"aw\",@progbits",
73                         NULL, /* no cstring section */
74                         NULL,
75                         NULL
76                 },
77                 { /* GAS_FLAVOUR_MINGW */
78                         ".section\t.text",
79                         ".section\t.data",
80                         ".section .rdata,\"dr\"",
81                         ".section\t.bss",
82                         ".section\t.tbss,\"awT\",@nobits",
83                         ".section\t.ctors,\"w\"",
84                         ".section\t.dtors,\"w\"",
85                         NULL,
86                         NULL,
87                         NULL
88                 },
89                 { /* GAS_FLAVOUR_YASM */
90                         ".section\t.text",
91                         ".section\t.data",
92                         ".section\t.rodata",
93                         ".section\t.bss",
94                         ".section\t.tbss,\"awT\",@nobits",
95                         ".section\t.ctors,\"aw\",@progbits",
96                         ".section\t.dtors,\"aw\",@progbits",
97                         NULL,
98                         NULL,
99                         NULL
100                 },
101                 { /* GAS_FLAVOUR_MACH_O */
102                         ".text",
103                         ".data",
104                         ".const",
105                         ".data",
106                         NULL,             /* TLS is not supported on Mach-O */
107                         ".mod_init_func",
108                         NULL,             /* TODO: how is this called? */
109                         ".cstring",
110                         ".section\t__IMPORT,__jump_table,symbol_stubs,self_modifying_code+pure_instructions,5",
111                         ".section\t__IMPORT,__pointers,non_lazy_symbol_pointers"
112                 }
113         };
114
115         assert((int) be_gas_flavour >= 0 && be_gas_flavour <= GAS_FLAVOUR_LAST);
116         assert((int) section >= 0 && section <= GAS_SECTION_LAST);
117         return text[be_gas_flavour][section];
118 }
119
120 void be_gas_emit_switch_section(be_gas_section_t section) {
121         if (current_section == section)
122                 return;
123
124         be_emit_char('\t');
125         be_emit_string(get_section_name(section));
126         be_emit_char('\n');
127         be_emit_write_line();
128         current_section = section;
129 }
130
131 void be_gas_emit_function_prolog(ir_entity *entity, unsigned po2alignment)
132 {
133         const char *name = get_entity_ld_name(entity);
134         const char *fill_byte = "";
135         unsigned    maximum_skip;
136
137         be_gas_emit_switch_section(GAS_SECTION_TEXT);
138
139         /* write the begin line (used by scripts processing the assembler... */
140         be_emit_write_line();
141         be_emit_cstring("# -- Begin  ");
142         be_emit_string(name);
143         be_emit_char('\n');
144         be_emit_write_line();
145
146         /* gcc fills space between function with 0x90, no idea if this is needed */
147         if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
148                 fill_byte = "0x90";
149         }
150
151         if (po2alignment > 0) {
152                 maximum_skip = (1 << po2alignment) - 1;
153                 be_emit_cstring("\t.p2align ");
154                 be_emit_irprintf("%u,%s,%u\n", po2alignment, fill_byte, maximum_skip);
155                 be_emit_write_line();
156         }
157         if (get_entity_visibility(entity) == visibility_external_visible) {
158                 be_emit_cstring(".globl ");
159                 be_emit_string(name);
160                 be_emit_char('\n');
161                 be_emit_write_line();
162         }
163
164         switch (be_gas_flavour) {
165         case GAS_FLAVOUR_ELF:
166                 be_emit_cstring("\t.type\t");
167                 be_emit_string(name);
168                 be_emit_cstring(", ");
169                 be_emit_char(be_gas_elf_type_char);
170                 be_emit_cstring("function\n");
171                 be_emit_write_line();
172                 break;
173         case GAS_FLAVOUR_MINGW:
174                 be_emit_cstring("\t.def\t");
175                 be_emit_string(name);
176                 if (get_entity_visibility(entity) == visibility_external_visible) {
177                         be_emit_cstring(";\t.scl\t2;\t.type\t32;\t.endef\n");
178                 } else {
179                         be_emit_cstring(";\t.scl\t3;\t.type\t32;\t.endef\n");
180                 }
181                 be_emit_write_line();
182                 break;
183         case GAS_FLAVOUR_MACH_O:
184         case GAS_FLAVOUR_YASM:
185                 break;
186         }
187         be_emit_string(name);
188         be_emit_cstring(":\n");
189         be_emit_write_line();
190 }
191
192 void be_gas_emit_function_epilog(ir_entity *entity)
193 {
194         const char *name = get_entity_ld_name(entity);
195
196         if (be_gas_flavour == GAS_FLAVOUR_ELF) {
197                 be_emit_cstring("\t.size\t");
198                 be_emit_string(name);
199                 be_emit_cstring(", .-");
200                 be_emit_string(name);
201                 be_emit_char('\n');
202                 be_emit_write_line();
203         }
204
205         be_emit_cstring("# -- End  ");
206         be_emit_string(name);
207         be_emit_char('\n');
208         be_emit_write_line();
209 }
210
211 /**
212  * An environment containing all needed dumper data.
213  * Currently we create the file completely in memory first, then
214  * write it to the disk. This is an artifact from the old C-generating backend
215  * and even there NOT needed. So we might change it in the future.
216  */
217 typedef struct _be_gas_decl_env {
218         be_gas_section_t     section;
219         waitq               *worklist;           /**< A worklist we use to place not yet handled entities on. */
220 } be_gas_decl_env_t;
221
222 /************************************************************************/
223
224 /**
225  * Output a tarval.
226  *
227  * @param tv     the tarval
228  * @param bytes  the width of the tarvals value in bytes
229  */
230 static void dump_arith_tarval(tarval *tv, int bytes)
231 {
232         switch (bytes) {
233         case 1:
234                 be_emit_irprintf("0x%02x", get_tarval_sub_bits(tv, 0));
235                 return;
236
237         case 2:
238                 be_emit_irprintf("0x%02x%02x", get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
239                 return;
240
241         case 4:
242                 be_emit_irprintf("0x%02x%02x%02x%02x",
243                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
244                 return;
245
246         case 8:
247                 be_emit_irprintf("0x%02x%02x%02x%02x%02x%02x%02x%02x",
248                         get_tarval_sub_bits(tv, 7), get_tarval_sub_bits(tv, 6), get_tarval_sub_bits(tv, 5), get_tarval_sub_bits(tv, 4),
249                         get_tarval_sub_bits(tv, 3), get_tarval_sub_bits(tv, 2), get_tarval_sub_bits(tv, 1), get_tarval_sub_bits(tv, 0));
250                 return;
251
252         case 12:
253                 /* Beware: Mixed endian output!  One little endian number emitted as
254                  * three longs.  Each long initializer is written in big endian. */
255                 be_emit_irprintf(
256                         "\t.long\t0x%02x%02x%02x%02x\n"
257                         "\t.long\t0x%02x%02x%02x%02x\n"
258                         "\t.long\t0x%02x%02x%02x%02x",
259                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
260                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0),
261                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
262                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
263                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
264                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8)
265                 );
266                 return;
267
268         case 16:
269                 be_emit_irprintf(
270                         "\t.long\t0x%02x%02x%02x%02x0x%02x%02x%02x%02x0x%02x%02x%02x%02x0x%02x%02x%02x%02x",
271                         get_tarval_sub_bits(tv, 15), get_tarval_sub_bits(tv, 16),
272                         get_tarval_sub_bits(tv, 13), get_tarval_sub_bits(tv, 12),
273                         get_tarval_sub_bits(tv, 11), get_tarval_sub_bits(tv, 10),
274                         get_tarval_sub_bits(tv,  9), get_tarval_sub_bits(tv,  8),
275                         get_tarval_sub_bits(tv,  7), get_tarval_sub_bits(tv,  6),
276                         get_tarval_sub_bits(tv,  5), get_tarval_sub_bits(tv,  4),
277                         get_tarval_sub_bits(tv,  3), get_tarval_sub_bits(tv,  2),
278                         get_tarval_sub_bits(tv,  1), get_tarval_sub_bits(tv,  0)
279                 );
280                 return;
281         }
282
283         panic("Can't dump a tarval with %d bytes", bytes);
284 }
285
286 /**
287  * Return the label prefix for labeled blocks.
288  */
289 const char *be_gas_block_label_prefix(void) {
290         return ".LG";
291 }
292
293 /**
294  * Return the label prefix for labeled instructions.
295  */
296 const char *be_gas_insn_label_prefix(void) {
297         return ".LE";
298 }
299
300 void be_gas_emit_entity(ir_entity *entity)
301 {
302         if (entity->type == firm_code_type) {
303                 ir_label_t label = get_entity_label(entity);
304                 be_emit_string(be_gas_block_label_prefix());
305                 be_emit_irprintf("%lu", label);
306         } else {
307                 be_emit_ident(get_entity_ld_ident(entity));
308         }
309 }
310
311 /**
312  * Return the tarval of an atomic initializer.
313  *
314  * @param init  a node representing the initializer (on the const code irg)
315  *
316  * @return the tarval
317  */
318 static tarval *get_atomic_init_tv(ir_node *init)
319 {
320         for (;;) {
321                 ir_mode *mode = get_irn_mode(init);
322
323                 switch (get_irn_opcode(init)) {
324
325                 case iro_Cast:
326                         init = get_Cast_op(init);
327                         continue;
328
329                 case iro_Conv:
330                         init = get_Conv_op(init);
331                         continue;
332
333                 case iro_Const:
334                         return get_Const_tarval(init);
335
336                 case iro_SymConst:
337                         switch (get_SymConst_kind(init)) {
338                         case symconst_type_size:
339                                 return new_tarval_from_long(get_type_size_bytes(get_SymConst_type(init)), mode);
340
341                         case symconst_type_align:
342                                 return new_tarval_from_long(get_type_alignment_bytes(get_SymConst_type(init)), mode);
343
344                         case symconst_ofs_ent:
345                                 return new_tarval_from_long(get_entity_offset(get_SymConst_entity(init)), mode);
346
347                         case symconst_enum_const:
348                                 return get_enumeration_value(get_SymConst_enum(init));
349
350                         default:
351                                 return NULL;
352                         }
353
354                 default:
355                         return NULL;
356                 }
357         }
358 }
359
360 /**
361  * Dump an atomic value.
362  *
363  * @param env   the gas output environment
364  * @param init  a node representing the atomic value (on the const code irg)
365  */
366 static void do_dump_atomic_init(be_gas_decl_env_t *env, ir_node *init)
367 {
368         ir_mode *mode = get_irn_mode(init);
369         int bytes     = get_mode_size_bytes(mode);
370         tarval *tv;
371         ir_entity *ent;
372
373         init = skip_Id(init);
374
375         switch (get_irn_opcode(init)) {
376         case iro_Cast:
377                 do_dump_atomic_init(env, get_Cast_op(init));
378                 return;
379
380         case iro_Conv:
381                 do_dump_atomic_init(env, get_Conv_op(init));
382                 return;
383
384         case iro_Const:
385                 tv = get_Const_tarval(init);
386
387                 /* it's a arithmetic value */
388                 dump_arith_tarval(tv, bytes);
389                 return;
390
391         case iro_SymConst:
392                 switch (get_SymConst_kind(init)) {
393                 case symconst_addr_name:
394                         be_emit_ident(get_SymConst_name(init));
395                         break;
396
397                 case symconst_addr_ent:
398                         ent = get_SymConst_entity(init);
399                         if (!is_entity_backend_marked(ent)) {
400                                 waitq_put(env->worklist, ent);
401                                 set_entity_backend_marked(ent, 1);
402                         }
403                         be_gas_emit_entity(ent);
404                         break;
405
406                 case symconst_ofs_ent:
407                         ent = get_SymConst_entity(init);
408                         be_emit_irprintf("%d", get_entity_offset(ent));
409                         break;
410
411                 case symconst_type_size:
412                         be_emit_irprintf("%u", get_type_size_bytes(get_SymConst_type(init)));
413                         break;
414
415                 case symconst_type_align:
416                         be_emit_irprintf("%u", get_type_alignment_bytes(get_SymConst_type(init)));
417                         break;
418
419                 case symconst_enum_const:
420                         tv = get_enumeration_value(get_SymConst_enum(init));
421                         dump_arith_tarval(tv, bytes);
422                         break;
423
424                 default:
425                         assert(!"dump_atomic_init(): don't know how to init from this SymConst");
426                 }
427                 return;
428
429         case iro_Add:
430                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
431                         panic("Constant must be int or pointer for '+' to work");
432                 }
433                 do_dump_atomic_init(env, get_Add_left(init));
434                 be_emit_cstring(" + ");
435                 do_dump_atomic_init(env, get_Add_right(init));
436                 return;
437
438         case iro_Sub:
439                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
440                         panic("Constant must be int or pointer for '-' to work");
441                 }
442                 do_dump_atomic_init(env, get_Sub_left(init));
443                 be_emit_cstring(" - ");
444                 do_dump_atomic_init(env, get_Sub_right(init));
445                 return;
446
447         case iro_Mul:
448                 if (!mode_is_int(mode) && !mode_is_reference(mode)) {
449                         panic("Constant must be int or pointer for '*' to work");
450                 }
451                 do_dump_atomic_init(env, get_Mul_left(init));
452                 be_emit_cstring(" * ");
453                 do_dump_atomic_init(env, get_Mul_right(init));
454                 return;
455
456         case iro_Unknown:
457                 be_emit_cstring("0");
458                 return;
459
460         default:
461                 panic("dump_atomic_init(): unsupported IR-node %+F", init);
462         }
463 }
464
465 /**
466  * Dumps the type for given size (.byte, .long, ...)
467  *
468  * @param size  the size in bytes
469  */
470 static void dump_size_type(size_t size) {
471         switch (size) {
472         case 1:
473                 be_emit_cstring("\t.byte\t");
474                 break;
475
476         case 2:
477                 be_emit_cstring("\t.short\t");
478                 break;
479
480         case 4:
481                 be_emit_cstring("\t.long\t");
482                 break;
483
484         case 8:
485                 be_emit_cstring("\t.quad\t");
486                 break;
487
488         case 10:
489         case 12:
490                 /* handled in arith */
491                 break;
492
493         case 16:
494                 be_emit_cstring("\t.octa\t");
495                 break;
496
497         default:
498                 panic("Try to dump a type with %u bytes", (unsigned)size);
499         }
500 }
501
502 /**
503  * Emit an atomic value.
504  *
505  * @param env   the gas output environment
506  * @param init  a node representing the atomic value (on the const code irg)
507  */
508 static void dump_atomic_init(be_gas_decl_env_t *env, ir_node *init)
509 {
510         ir_mode *mode = get_irn_mode(init);
511         int bytes     = get_mode_size_bytes(mode);
512
513         dump_size_type(bytes);
514         do_dump_atomic_init(env, init);
515         be_emit_char('\n');
516         be_emit_write_line();
517 }
518
519 /************************************************************************/
520 /* Routines to dump global variables                                    */
521 /************************************************************************/
522
523 static int initializer_is_string_const(const ir_initializer_t *initializer)
524 {
525         size_t i, len;
526         int found_printable = 0;
527
528         if (initializer->kind != IR_INITIALIZER_COMPOUND)
529                 return 0;
530
531         len = initializer->compound.n_initializers;
532         if (len < 1)
533                 return 0;
534         for (i = 0; i < len; ++i) {
535                 int               c;
536                 tarval           *tv;
537                 ir_mode          *mode;
538                 ir_initializer_t *sub_initializer
539                         = initializer->compound.initializers[i];
540
541                 if (sub_initializer->kind != IR_INITIALIZER_TARVAL)
542                         return 0;
543
544                 tv   = sub_initializer->tarval.value;
545                 mode = get_tarval_mode(tv);
546
547                 if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
548                         return 0;
549
550                 c = get_tarval_long(tv);
551                 if (isgraph(c) || isspace(c))
552                         found_printable = 1;
553                 else if (c != 0)
554                         return 0;
555
556                 if (i == len - 1 && c != '\0')
557                         return 0;
558         }
559
560         return found_printable;
561 }
562
563 /**
564  * Determine if an entity is a string constant
565  * @param ent The entity
566  * @return 1 if it is a string constant, 0 otherwise
567  */
568 static int ent_is_string_const(ir_entity *ent)
569 {
570         ir_type *type, *element_type;
571         ir_mode *mode;
572         int i, c, n;
573         int found_printable = 0;
574
575         type = get_entity_type(ent);
576
577         /* if it's an array */
578         if (!is_Array_type(type))
579                 return 0;
580
581         element_type = get_array_element_type(type);
582
583         /* and the array's element type is primitive */
584         if (!is_Primitive_type(element_type))
585                 return 0;
586
587         /* and the mode of the element type is an int of
588          * the same size as the byte mode */
589         mode = get_type_mode(element_type);
590         if (!mode_is_int(mode) || get_mode_size_bits(mode) != 8)
591                 return 0;
592
593         if (ent->has_initializer) {
594                 /* TODO */
595                 return 0;
596         } else {
597                 /* if it contains only printable chars and a 0 at the end */
598                 n = get_compound_ent_n_values(ent);
599                 for (i = 0; i < n; ++i) {
600                         ir_node *irn = get_compound_ent_value(ent, i);
601                         if (! is_Const(irn))
602                                 return 0;
603
604                         c = (int) get_tarval_long(get_Const_tarval(irn));
605
606                         if (isgraph(c) || isspace(c))
607                                 found_printable = 1;
608                         else if (c != 0)
609                                 return 0;
610
611                         if (i == n - 1 && c != '\0')
612                                 return 0;
613                 }
614         }
615
616         /* then we can emit it as a string constant */
617         return found_printable;
618 }
619
620 /**
621  * Dump a string constant.
622  * No checks are made!!
623  *
624  * @param ent  The entity to dump.
625  */
626 static void dump_string_cst(ir_entity *ent)
627 {
628         int      i, len;
629         int      output_len;
630         ir_type *type;
631         int      type_size;
632         int      remaining_space;
633
634         len        = get_compound_ent_n_values(ent);
635         output_len = len;
636         if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
637                 be_emit_cstring("\t.ascii \"");
638         } else {
639                 be_emit_cstring("\t.string \"");
640                 output_len -= 1;
641         }
642
643         for (i = 0; i < output_len; ++i) {
644                 ir_node *irn;
645                 int c;
646
647                 irn = get_compound_ent_value(ent, i);
648                 c = (int) get_tarval_long(get_Const_tarval(irn));
649
650                 switch (c) {
651                 case '"' : be_emit_cstring("\\\""); break;
652                 case '\n': be_emit_cstring("\\n"); break;
653                 case '\r': be_emit_cstring("\\r"); break;
654                 case '\t': be_emit_cstring("\\t"); break;
655                 case '\\': be_emit_cstring("\\\\"); break;
656                 default  :
657                         if (isprint(c))
658                                 be_emit_char(c);
659                         else
660                                 be_emit_irprintf("\\%o", c);
661                         break;
662                 }
663         }
664         be_emit_cstring("\"\n");
665         be_emit_write_line();
666
667         type            = get_entity_type(ent);
668         type_size       = get_type_size_bytes(type);
669         remaining_space = type_size - len;
670         assert(remaining_space >= 0);
671         if (remaining_space > 0) {
672                 be_emit_irprintf("\t.space\t%d\n", remaining_space);
673         }
674 }
675
676 static void dump_string_initializer(const ir_initializer_t *initializer)
677 {
678         size_t i, len;
679
680         len = initializer->compound.n_initializers;
681         if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
682                 be_emit_cstring("\t.ascii \"");
683         } else {
684                 be_emit_cstring("\t.string \"");
685                 len -= 1;
686         }
687
688         for (i = 0; i < len; ++i) {
689                 const ir_initializer_t *sub_initializer
690                         = get_initializer_compound_value(initializer, i);
691
692                 tarval *tv = get_initializer_tarval_value(sub_initializer);
693                 int     c  = get_tarval_long(tv);
694
695                 switch (c) {
696                 case '"' : be_emit_cstring("\\\""); break;
697                 case '\n': be_emit_cstring("\\n"); break;
698                 case '\r': be_emit_cstring("\\r"); break;
699                 case '\t': be_emit_cstring("\\t"); break;
700                 case '\\': be_emit_cstring("\\\\"); break;
701                 default  :
702                         if (isprint(c))
703                                 be_emit_char(c);
704                         else
705                                 be_emit_irprintf("\\%o", c);
706                         break;
707                 }
708         }
709         be_emit_cstring("\"\n");
710         be_emit_write_line();
711 }
712
713 enum normal_or_bitfield_kind {
714         NORMAL = 0,
715         TARVAL,
716         BITFIELD
717 };
718
719 typedef struct {
720         enum normal_or_bitfield_kind kind;
721         union {
722                 ir_node       *value;
723                 tarval        *tarval;
724                 unsigned char  bf_val;
725         } v;
726 } normal_or_bitfield;
727
728 static int is_type_variable_size(ir_type *type)
729 {
730         (void) type;
731         /* TODO */
732         return 0;
733 }
734
735 static size_t get_initializer_size(const ir_initializer_t *initializer,
736                                    ir_type *type)
737 {
738         switch (get_initializer_kind(initializer)) {
739         case IR_INITIALIZER_TARVAL:
740                 assert(get_tarval_mode(get_initializer_tarval_value(initializer)) == get_type_mode(type));
741                 return get_type_size_bytes(type);
742         case IR_INITIALIZER_CONST:
743         case IR_INITIALIZER_NULL:
744                 return get_type_size_bytes(type);
745         case IR_INITIALIZER_COMPOUND:
746                 if (!is_type_variable_size(type)) {
747                         return get_type_size_bytes(type);
748                 } else {
749                         unsigned n_entries
750                                 = get_initializer_compound_n_entries(initializer);
751                         unsigned i;
752                         unsigned initializer_size = get_type_size_bytes(type);
753                         for (i = 0; i < n_entries; ++i) {
754                                 ir_entity *entity = get_compound_member(type, i);
755                                 ir_type   *type   = get_entity_type(entity);
756
757                                 const ir_initializer_t *sub_initializer
758                                         = get_initializer_compound_value(initializer, i);
759
760                                 unsigned offset = get_entity_offset(entity);
761                                 unsigned size   = get_initializer_size(sub_initializer, type);
762
763                                 if (offset + size > initializer_size) {
764                                         initializer_size = offset + size;
765                                 }
766                         }
767                         return initializer_size;
768                 }
769         }
770
771         panic("found invalid initializer");
772 }
773
774 #ifndef NDEBUG
775 static normal_or_bitfield *glob_vals;
776 static size_t              max_vals;
777 #endif
778
779 static void dump_bitfield(normal_or_bitfield *vals, size_t offset_bits,
780                           const ir_initializer_t *initializer, ir_type *type)
781 {
782         unsigned char  last_bits = 0;
783         ir_mode       *mode      = get_type_mode(type);
784         tarval        *tv        = NULL;
785         unsigned char  curr_bits;
786         int            value_len;
787         int            j;
788
789         switch (get_initializer_kind(initializer)) {
790         case IR_INITIALIZER_NULL:
791                 return;
792         case IR_INITIALIZER_TARVAL:
793                 tv = get_initializer_tarval_value(initializer);
794                 break;
795         case IR_INITIALIZER_CONST: {
796                 ir_node *node = get_initializer_const_value(initializer);
797                 if (!is_Const(node)) {
798                         panic("bitfield initializer not a Const node");
799                 }
800                 tv = get_Const_tarval(node);
801                 break;
802         }
803         case IR_INITIALIZER_COMPOUND:
804                 panic("bitfield initializer is compound");
805         }
806         if (tv == NULL) {
807                 panic("Couldn't get numeric value for bitfield initializer");
808         }
809         tv = tarval_convert_to(tv, get_type_mode(type));
810
811         /* normalize offset */
812         vals        += offset_bits >> 3;
813         offset_bits &= 7;
814         value_len    = get_mode_size_bits(mode);
815
816         /* combine bits with existing bits */
817         for (j = 0; value_len + (int) offset_bits > 0; ++j) {
818                 assert((size_t) (vals - glob_vals) + j < max_vals);
819                 assert(vals[j].kind == BITFIELD ||
820                                 (vals[j].kind == NORMAL && vals[j].v.value == NULL));
821                 vals[j].kind = BITFIELD;
822                 curr_bits    = get_tarval_sub_bits(tv, j);
823                 vals[j].v.bf_val
824                         |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
825                 value_len -= 8;
826                 last_bits = curr_bits;
827         }
828 }
829
830 static void dump_ir_initializer(normal_or_bitfield *vals,
831                                 const ir_initializer_t *initializer,
832                                 ir_type *type)
833 {
834         assert((size_t) (vals - glob_vals) < max_vals);
835
836         switch (get_initializer_kind(initializer)) {
837         case IR_INITIALIZER_NULL:
838                 return;
839         case IR_INITIALIZER_TARVAL: {
840                 size_t i;
841
842                 assert(vals->kind != BITFIELD);
843                 vals->kind     = TARVAL;
844                 vals->v.tarval = get_initializer_tarval_value(initializer);
845                 assert(get_type_mode(type) == get_tarval_mode(vals->v.tarval));
846                 for (i = 1; i < get_type_size_bytes(type); ++i) {
847                         vals[i].kind    = NORMAL;
848                         vals[i].v.value = NULL;
849                 }
850                 return;
851         }
852         case IR_INITIALIZER_CONST: {
853                 size_t i;
854
855                 assert(vals->kind != BITFIELD);
856                 vals->kind    = NORMAL;
857                 vals->v.value = get_initializer_const_value(initializer);
858                 for (i = 1; i < get_type_size_bytes(type); ++i) {
859                         vals[i].kind    = NORMAL;
860                         vals[i].v.value = NULL;
861                 }
862                 return;
863         }
864         case IR_INITIALIZER_COMPOUND: {
865                 size_t i = 0;
866                 size_t n = get_initializer_compound_n_entries(initializer);
867
868                 if (is_Array_type(type)) {
869                         ir_type *element_type = get_array_element_type(type);
870                         size_t   skip         = get_type_size_bytes(element_type);
871                         size_t   alignment    = get_type_alignment_bytes(element_type);
872                         size_t   misalign     = skip % alignment;
873                         if (misalign != 0) {
874                                 skip += alignment - misalign;
875                         }
876
877                         for (i = 0; i < n; ++i) {
878                                 ir_initializer_t *sub_initializer
879                                         = get_initializer_compound_value(initializer, i);
880
881                                 dump_ir_initializer(vals, sub_initializer, element_type);
882
883                                 vals += skip;
884                         }
885                 } else {
886                         size_t n_members, i;
887                         assert(is_compound_type(type));
888                         n_members = get_compound_n_members(type);
889                         for (i = 0; i < n_members; ++i) {
890                                 ir_entity        *member    = get_compound_member(type, i);
891                                 size_t            offset    = get_entity_offset(member);
892                                 ir_type          *subtype   = get_entity_type(member);
893                                 ir_mode          *mode      = get_type_mode(subtype);
894                                 ir_initializer_t *sub_initializer;
895
896                                 assert(i < get_initializer_compound_n_entries(initializer));
897                                 sub_initializer
898                                         = get_initializer_compound_value(initializer, i);
899
900                                 if (mode != NULL) {
901                                         size_t offset_bits
902                                                 = get_entity_offset_bits_remainder(member);
903                                         size_t value_len   = get_mode_size_bits(mode);
904
905                                         if (offset_bits != 0 ||
906                                                 (value_len != 8 && value_len != 16 && value_len != 32
907                                                  && value_len != 64)) {
908                                                 dump_bitfield(&vals[offset], offset_bits,
909                                                               sub_initializer, subtype);
910                                                 continue;
911                                         }
912                                 }
913
914                                 dump_ir_initializer(&vals[offset], sub_initializer, subtype);
915                         }
916                 }
917
918                 return;
919         }
920         }
921         panic("invalid ir_initializer kind found");
922 }
923
924 static void dump_initializer(be_gas_decl_env_t *env, ir_entity *entity)
925 {
926         const ir_initializer_t *initializer = entity->attr.initializer;
927         ir_type                *type;
928         normal_or_bitfield     *vals;
929         size_t                  size;
930         size_t                  k;
931
932         if (initializer_is_string_const(initializer)) {
933                 dump_string_initializer(initializer);
934                 return;
935         }
936
937         type = get_entity_type(entity);
938         size = get_initializer_size(initializer, type);
939
940         if (size == 0)
941                 return;
942
943         /*
944          * In the worst case, every initializer allocates one byte.
945          * Moreover, initializer might be big, do not allocate on stack.
946          */
947         vals = XMALLOCNZ(normal_or_bitfield, size);
948
949 #ifndef NDEBUG
950         glob_vals = vals;
951         max_vals  = size;
952 #endif
953
954         dump_ir_initializer(vals, initializer, type);
955
956         /* now write values sorted */
957         for (k = 0; k < size; ) {
958                 int space     = 0;
959                 int elem_size = 1;
960                 if (vals[k].kind == NORMAL) {
961                         if (vals[k].v.value != NULL) {
962                                 dump_atomic_init(env, vals[k].v.value);
963                                 elem_size = get_mode_size_bytes(get_irn_mode(vals[k].v.value));
964                         } else {
965                                 elem_size = 0;
966                         }
967                 } else if (vals[k].kind == TARVAL) {
968                         tarval *tv   = vals[k].v.tarval;
969                         size_t  size = get_mode_size_bytes(get_tarval_mode(tv));
970
971                         assert(tv != NULL);
972
973                         elem_size = size;
974                         dump_size_type(size);
975                         dump_arith_tarval(tv, size);
976                         be_emit_char('\n');
977                         be_emit_write_line();
978                 } else {
979                         assert(vals[k].kind == BITFIELD);
980                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
981                         be_emit_write_line();
982                 }
983
984                 k += elem_size;
985                 while (k < size && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
986                         ++space;
987                         ++k;
988                 }
989
990                 /* a gap */
991                 if (space > 0) {
992                         be_emit_irprintf("\t.space\t%d\n", space);
993                         be_emit_write_line();
994                 }
995         }
996         xfree(vals);
997 }
998
999 /**
1000  * Dump an initializer for a compound entity.
1001  */
1002 static void dump_compound_init(be_gas_decl_env_t *env, ir_entity *ent)
1003 {
1004         normal_or_bitfield *vals;
1005         int i, j, n;
1006         unsigned k, last_ofs;
1007
1008         if (ent->has_initializer) {
1009                 dump_initializer(env, ent);
1010                 return;
1011         }
1012
1013         n = get_compound_ent_n_values(ent);
1014
1015         /* Find the initializer size. Sorrily gcc support a nasty feature:
1016            The last field of a compound may be a flexible array. This allows
1017            initializers bigger than the type size. */
1018         last_ofs = get_type_size_bytes(get_entity_type(ent));
1019         for (i = 0; i < n; ++i) {
1020                 unsigned offset         = get_compound_ent_value_offset_bytes(ent, i);
1021                 unsigned bits_remainder = get_compound_ent_value_offset_bit_remainder(ent, i);
1022                 ir_node  *value         = get_compound_ent_value(ent, i);
1023                 unsigned value_len      = get_mode_size_bits(get_irn_mode(value));
1024
1025                 offset += (value_len + bits_remainder + 7) >> 3;
1026
1027                 if (offset > last_ofs) {
1028                         last_ofs = offset;
1029                 }
1030         }
1031
1032         /*
1033          * In the worst case, every initializer allocates one byte.
1034          * Moreover, initializer might be big, do not allocate on stack.
1035          */
1036         vals = XMALLOCNZ(normal_or_bitfield, last_ofs);
1037
1038         /* collect the values and store them at the offsets */
1039         for (i = 0; i < n; ++i) {
1040                 unsigned offset      = get_compound_ent_value_offset_bytes(ent, i);
1041                 int      offset_bits = get_compound_ent_value_offset_bit_remainder(ent, i);
1042                 ir_node  *value      = get_compound_ent_value(ent, i);
1043                 int      value_len   = get_mode_size_bits(get_irn_mode(value));
1044
1045                 assert(offset_bits >= 0);
1046
1047                 if (offset_bits != 0 ||
1048                         (value_len != 8 && value_len != 16 && value_len != 32 && value_len != 64)) {
1049                         tarval *tv = get_atomic_init_tv(value);
1050                         unsigned char curr_bits, last_bits = 0;
1051                         if (tv == NULL) {
1052                                 panic("Couldn't get numeric value for bitfield initializer '%s'",
1053                                       get_entity_ld_name(ent));
1054                         }
1055                         /* normalize offset */
1056                         offset += offset_bits >> 3;
1057                         offset_bits &= 7;
1058
1059                         for (j = 0; value_len + offset_bits > 0; ++j) {
1060                                 assert(offset + j < last_ofs);
1061                                 assert(vals[offset + j].kind == BITFIELD || vals[offset + j].v.value == NULL);
1062                                 vals[offset + j].kind = BITFIELD;
1063                                 curr_bits = get_tarval_sub_bits(tv, j);
1064                                 vals[offset + j].v.bf_val |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1065                                 value_len -= 8;
1066                                 last_bits = curr_bits;
1067                         }
1068                 } else {
1069                         int i;
1070
1071                         assert(offset < last_ofs);
1072                         assert(vals[offset].kind == NORMAL);
1073                         for (i = 1; i < value_len / 8; ++i) {
1074                                 assert(vals[offset + i].v.value == NULL);
1075                         }
1076                         vals[offset].v.value = value;
1077                 }
1078         }
1079
1080         /* now write them sorted */
1081         for (k = 0; k < last_ofs; ) {
1082                 int space = 0, skip = 0;
1083                 if (vals[k].kind == NORMAL) {
1084                         if (vals[k].v.value != NULL) {
1085                                 dump_atomic_init(env, vals[k].v.value);
1086                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
1087                         } else {
1088                                 space = 1;
1089                         }
1090                 } else {
1091                         assert(vals[k].kind == BITFIELD);
1092                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1093                 }
1094
1095                 ++k;
1096                 while (k < last_ofs && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1097                         ++space;
1098                         ++k;
1099                 }
1100                 space -= skip;
1101                 assert(space >= 0);
1102
1103                 /* a gap */
1104                 if (space > 0) {
1105                         be_emit_irprintf("\t.space\t%d\n", space);
1106                         be_emit_write_line();
1107                 }
1108         }
1109         xfree(vals);
1110 }
1111
1112 static void emit_align(unsigned p2alignment)
1113 {
1114         be_emit_irprintf("\t.p2align\t%u\n", log2_floor(p2alignment));
1115         be_emit_write_line();
1116 }
1117
1118 static unsigned get_effective_entity_alignment(ir_entity *entity)
1119 {
1120         unsigned alignment = get_entity_alignment(entity);
1121         if (alignment == 0) {
1122                 ir_type *type = get_entity_type(entity);
1123                 alignment     = get_type_alignment_bytes(type);
1124         }
1125         return alignment;
1126 }
1127
1128
1129 /**
1130  * Dump a global entity.
1131  *
1132  * @param env           the gas output environment
1133  * @param ent           the entity to be dumped
1134  */
1135 static void dump_global(be_gas_decl_env_t *env, ir_entity *ent)
1136 {
1137         ir_type          *type           = get_entity_type(ent);
1138         ident            *ld_ident       = get_entity_ld_ident(ent);
1139         unsigned          alignment      = get_effective_entity_alignment(ent);
1140         int               emit_as_common = 0;
1141         be_gas_section_t  section        = env->section;
1142         ir_variability    variability    = get_entity_variability(ent);
1143         ir_visibility     visibility     = get_entity_visibility(ent);
1144
1145         if (is_Method_type(type) && section != GAS_SECTION_PIC_TRAMPOLINES) {
1146                 return;
1147         }
1148         if (type == firm_code_type) {
1149                 return;
1150         }
1151
1152         if (section != (be_gas_section_t) -1) {
1153                 emit_as_common = 0;
1154         } else if (variability == variability_constant) {
1155                 /* a constant entity, put it on the rdata */
1156                 section = GAS_SECTION_RODATA;
1157                 if (be_gas_flavour == GAS_FLAVOUR_MACH_O
1158                                 && ent_is_string_const(ent)) {
1159                         section = GAS_SECTION_CSTRING;
1160                 }
1161         } else if (variability == variability_uninitialized) {
1162                 /* uninitialized entity put it in bss segment */
1163                 section = GAS_SECTION_COMMON;
1164                 if (visibility != visibility_local)
1165                         emit_as_common = 1;
1166         } else {
1167                 section = GAS_SECTION_DATA;
1168         }
1169
1170         if (!emit_as_common) {
1171                 be_gas_emit_switch_section(section);
1172         }
1173
1174         be_dbg_variable(ent);
1175
1176         /* global or not global */
1177         if (visibility == visibility_external_visible && !emit_as_common) {
1178                 be_emit_cstring(".globl\t");
1179                 be_emit_ident(ld_ident);
1180                 be_emit_char('\n');
1181                 be_emit_write_line();
1182         } else if (visibility == visibility_external_allocated) {
1183                 be_emit_cstring(".globl\t");
1184                 be_emit_ident(ld_ident);
1185                 be_emit_char('\n');
1186                 be_emit_write_line();
1187                 /* we can return now... */
1188                 return;
1189         }
1190         if (!is_po2(alignment))
1191                 panic("alignment not a power of 2");
1192         /* alignment */
1193         if (alignment > 1 && !emit_as_common && section != GAS_SECTION_PIC_TRAMPOLINES
1194                         && section != GAS_SECTION_PIC_SYMBOLS) {
1195                 emit_align(alignment);
1196         }
1197
1198         if (visibility != visibility_external_allocated && !emit_as_common
1199                         && be_gas_flavour == GAS_FLAVOUR_ELF
1200                         && be_gas_emit_types) {
1201                 be_emit_cstring("\t.type\t");
1202                 be_emit_ident(ld_ident);
1203                 be_emit_cstring(", ");
1204                 be_emit_char(be_gas_elf_type_char);
1205                 be_emit_cstring("object\n\t.size\t");
1206                 be_emit_ident(ld_ident);
1207                 be_emit_irprintf(", %u\n", get_type_size_bytes(type));
1208         }
1209
1210         if (!emit_as_common) {
1211                 be_emit_ident(ld_ident);
1212                 be_emit_cstring(":\n");
1213                 be_emit_write_line();
1214         }
1215
1216         if (variability == variability_uninitialized) {
1217                 if (emit_as_common) {
1218                         switch (be_gas_flavour) {
1219                         case GAS_FLAVOUR_MACH_O:
1220                                 be_emit_irprintf("\t.comm %s,%u,%u\n",
1221                                         get_id_str(ld_ident), get_type_size_bytes(type),
1222                                         log2_floor(alignment));
1223                                 break;
1224                         case GAS_FLAVOUR_ELF:
1225                         case GAS_FLAVOUR_YASM:
1226                                 be_emit_irprintf("\t.comm %s,%u,%u\n",
1227                                         get_id_str(ld_ident), get_type_size_bytes(type), alignment);
1228                                 be_emit_write_line();
1229                                 break;
1230                         case GAS_FLAVOUR_MINGW:
1231                                 be_emit_irprintf("\t.comm %s,%u # %u\n",
1232                                         get_id_str(ld_ident), get_type_size_bytes(type), alignment);
1233                                 be_emit_write_line();
1234                                 break;
1235                         }
1236                 } else if (section == GAS_SECTION_PIC_TRAMPOLINES
1237                                 || section == GAS_SECTION_PIC_SYMBOLS) {
1238                         if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
1239                                 be_emit_cstring("\t.indirect_symbol ");
1240                                 be_emit_ident(get_entity_ident(ent));
1241                                 be_emit_char('\n');
1242                                 be_emit_write_line();
1243                                 if (section == GAS_SECTION_PIC_TRAMPOLINES) {
1244                                         be_emit_cstring("\thlt ; hlt ; hlt ; hlt ; hlt\n");
1245                                         be_emit_write_line();
1246                                 } else {
1247                                         assert(section == GAS_SECTION_PIC_SYMBOLS);
1248                                         be_emit_cstring("\t.long 0\n");
1249                                         be_emit_write_line();
1250                                 }
1251                         } else {
1252                                 panic("PIC trampolines not yet supported in this gas mode");
1253                         }
1254                 } else {
1255                         be_emit_irprintf("\t.space %u\n", get_type_size_bytes(type));
1256                         be_emit_write_line();
1257                 }
1258         } else {
1259                 if (is_atomic_entity(ent)) {
1260                         dump_atomic_init(env, get_atomic_ent_value(ent));
1261                 } else {
1262                         /* sort_compound_ent_values(ent); */
1263
1264                         switch (get_type_tpop_code(get_entity_type(ent))) {
1265                         case tpo_array:
1266                                 if (ent_is_string_const(ent))
1267                                         dump_string_cst(ent);
1268                                 else
1269                                         dump_compound_init(env, ent);
1270                                 break;
1271                         case tpo_struct:
1272                         case tpo_class:
1273                         case tpo_union:
1274                                 dump_compound_init(env, ent);
1275                                 break;
1276                         default:
1277                                 panic("Unimplemented type kind in dump_global()");
1278                         }
1279                 }
1280         }
1281 }
1282
1283 /**
1284  * Dumps declarations of global variables and the initialization code.
1285  *
1286  * @param gt                a global like type, either the global or the TLS one
1287  * @param env               an environment
1288  * @param only_emit_marked  if non-zero, external allocated entities that do not have
1289  *                          its visited flag set are ignored
1290  */
1291 static void be_gas_dump_globals(ir_type *gt, be_gas_decl_env_t *env,
1292                                 int only_emit_marked)
1293 {
1294         int i, n = get_compound_n_members(gt);
1295         waitq *worklist = new_waitq();
1296
1297         if (only_emit_marked) {
1298                 for (i = 0; i < n; i++) {
1299                         ir_entity *ent = get_compound_member(gt, i);
1300                         if (is_entity_backend_marked(ent) ||
1301                             get_entity_visibility(ent) != visibility_external_allocated) {
1302                                 waitq_put(worklist, ent);
1303                                 set_entity_backend_marked(ent, 1);
1304                         }
1305                 }
1306         } else {
1307                 for (i = 0; i < n; i++) {
1308                         ir_entity *ent = get_compound_member(gt, i);
1309                         set_entity_backend_marked(ent, 1);
1310                         waitq_put(worklist, ent);
1311                 }
1312         }
1313
1314         env->worklist = worklist;
1315
1316         while (!waitq_empty(worklist)) {
1317                 ir_entity *ent = waitq_get(worklist);
1318
1319                 dump_global(env, ent);
1320         }
1321
1322         del_waitq(worklist);
1323         env->worklist = NULL;
1324 }
1325
1326 /************************************************************************/
1327
1328 /* Generate all entities. */
1329 void be_gas_emit_decls(const be_main_env_t *main_env,
1330                        int only_emit_marked_entities)
1331 {
1332         be_gas_decl_env_t env;
1333         memset(&env, 0, sizeof(env));
1334
1335         /* dump global type */
1336         env.section = (be_gas_section_t) -1;
1337         be_gas_dump_globals(get_glob_type(), &env, only_emit_marked_entities);
1338         env.section = GAS_SECTION_TLS;
1339         be_gas_dump_globals(get_tls_type(), &env, only_emit_marked_entities);
1340         env.section = GAS_SECTION_CONSTRUCTORS;
1341         be_gas_dump_globals(get_segment_type(IR_SEGMENT_CONSTRUCTORS), &env,
1342                             only_emit_marked_entities);
1343         env.section = GAS_SECTION_DESTRUCTORS;
1344         be_gas_dump_globals(get_segment_type(IR_SEGMENT_DESTRUCTORS), &env,
1345                             only_emit_marked_entities);
1346
1347         env.section = GAS_SECTION_PIC_SYMBOLS;
1348         be_gas_dump_globals(main_env->pic_symbols_type, &env,
1349                             only_emit_marked_entities);
1350
1351         if (get_compound_n_members(main_env->pic_trampolines_type) > 0) {
1352                 env.section = GAS_SECTION_PIC_TRAMPOLINES;
1353                 be_gas_dump_globals(main_env->pic_trampolines_type, &env,
1354                                     only_emit_marked_entities);
1355                 if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
1356                         be_emit_cstring("\t.subsections_via_symbols\n");
1357                         be_emit_write_line();
1358                 }
1359         }
1360 }