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