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