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