- kicked useless blocks
[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         case IR_INITIALIZER_CONST:
736         case IR_INITIALIZER_NULL:
737                 return get_type_size_bytes(type);
738         case IR_INITIALIZER_COMPOUND:
739                 if (!is_type_variable_size(type)) {
740                         return get_type_size_bytes(type);
741                 } else {
742                         unsigned n_entries
743                                 = get_initializer_compound_n_entries(initializer);
744                         unsigned i;
745                         unsigned initializer_size = get_type_size_bytes(type);
746                         for (i = 0; i < n_entries; ++i) {
747                                 ir_entity *entity = get_compound_member(type, i);
748                                 ir_type   *type   = get_entity_type(entity);
749
750                                 const ir_initializer_t *sub_initializer
751                                         = get_initializer_compound_value(initializer, i);
752
753                                 unsigned offset = get_entity_offset(entity);
754                                 unsigned size   = get_initializer_size(sub_initializer, type);
755
756                                 if (offset + size > initializer_size) {
757                                         initializer_size = offset + size;
758                                 }
759                         }
760                         return initializer_size;
761                 }
762         }
763
764         panic("found invalid initializer");
765 }
766
767 #ifndef NDEBUG
768 static normal_or_bitfield *glob_vals;
769 static size_t              max_vals;
770 #endif
771
772 static void dump_bitfield(normal_or_bitfield *vals, size_t offset_bits,
773                           const ir_initializer_t *initializer, ir_type *type)
774 {
775         unsigned char  last_bits = 0;
776         ir_mode       *mode      = get_type_mode(type);
777         tarval        *tv        = NULL;
778         unsigned char  curr_bits;
779         int            value_len;
780         int            j;
781
782         switch (get_initializer_kind(initializer)) {
783         case IR_INITIALIZER_NULL:
784                 return;
785         case IR_INITIALIZER_TARVAL:
786                 tv = get_initializer_tarval_value(initializer);
787                 break;
788         case IR_INITIALIZER_CONST: {
789                 ir_node *node = get_initializer_const_value(initializer);
790                 if (!is_Const(node)) {
791                         panic("bitfield initializer not a Const node");
792                 }
793                 tv = get_Const_tarval(node);
794                 break;
795         }
796         case IR_INITIALIZER_COMPOUND:
797                 panic("bitfield initializer is compound");
798         }
799         if (tv == NULL) {
800                 panic("Couldn't get numeric value for bitfield initializer");
801         }
802         tv = tarval_convert_to(tv, get_type_mode(type));
803
804         /* normalize offset */
805         vals        += offset_bits >> 3;
806         offset_bits &= 7;
807         value_len    = get_mode_size_bits(mode);
808
809         /* combine bits with existing bits */
810         for (j = 0; value_len + (int) offset_bits > 0; ++j) {
811                 assert((size_t) (vals - glob_vals) + j < max_vals);
812                 assert(vals[j].kind == BITFIELD ||
813                                 (vals[j].kind == NORMAL && vals[j].v.value == NULL));
814                 vals[j].kind = BITFIELD;
815                 curr_bits    = get_tarval_sub_bits(tv, j);
816                 vals[j].v.bf_val
817                         |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
818                 value_len -= 8;
819                 last_bits = curr_bits;
820         }
821 }
822
823 static void dump_ir_initializer(normal_or_bitfield *vals,
824                                 const ir_initializer_t *initializer,
825                                 ir_type *type)
826 {
827         assert((size_t) (vals - glob_vals) < max_vals);
828
829         switch (get_initializer_kind(initializer)) {
830         case IR_INITIALIZER_NULL:
831                 return;
832         case IR_INITIALIZER_TARVAL: {
833                 size_t i;
834
835                 assert(vals->kind != BITFIELD);
836                 vals->kind     = TARVAL;
837                 vals->v.tarval = get_initializer_tarval_value(initializer);
838                 assert(get_type_mode(type) == get_tarval_mode(vals->v.tarval));
839                 for (i = 1; i < get_type_size_bytes(type); ++i) {
840                         vals[i].kind    = NORMAL;
841                         vals[i].v.value = NULL;
842                 }
843                 return;
844         }
845         case IR_INITIALIZER_CONST: {
846                 size_t i;
847
848                 assert(vals->kind != BITFIELD);
849                 vals->kind    = NORMAL;
850                 vals->v.value = get_initializer_const_value(initializer);
851                 for (i = 1; i < get_type_size_bytes(type); ++i) {
852                         vals[i].kind    = NORMAL;
853                         vals[i].v.value = NULL;
854                 }
855                 return;
856         }
857         case IR_INITIALIZER_COMPOUND: {
858                 size_t i = 0;
859                 size_t n = get_initializer_compound_n_entries(initializer);
860
861                 if (is_Array_type(type)) {
862                         ir_type *element_type = get_array_element_type(type);
863                         size_t   skip         = get_type_size_bytes(element_type);
864                         size_t   alignment    = get_type_alignment_bytes(element_type);
865                         size_t   misalign     = skip % alignment;
866                         if (misalign != 0) {
867                                 skip += alignment - misalign;
868                         }
869
870                         for (i = 0; i < n; ++i) {
871                                 ir_initializer_t *sub_initializer
872                                         = get_initializer_compound_value(initializer, i);
873
874                                 dump_ir_initializer(vals, sub_initializer, element_type);
875
876                                 vals += skip;
877                         }
878                 } else {
879                         size_t n_members, i;
880                         assert(is_compound_type(type));
881                         n_members = get_compound_n_members(type);
882                         for (i = 0; i < n_members; ++i) {
883                                 ir_entity        *member    = get_compound_member(type, i);
884                                 size_t            offset    = get_entity_offset(member);
885                                 ir_type          *subtype   = get_entity_type(member);
886                                 ir_mode          *mode      = get_type_mode(subtype);
887                                 ir_initializer_t *sub_initializer;
888
889                                 assert(i < get_initializer_compound_n_entries(initializer));
890                                 sub_initializer
891                                         = get_initializer_compound_value(initializer, i);
892
893                                 if (mode != NULL) {
894                                         size_t offset_bits
895                                                 = get_entity_offset_bits_remainder(member);
896                                         size_t value_len   = get_mode_size_bits(mode);
897
898                                         if (offset_bits != 0 ||
899                                                 (value_len != 8 && value_len != 16 && value_len != 32
900                                                  && value_len != 64)) {
901                                                 dump_bitfield(&vals[offset], offset_bits,
902                                                               sub_initializer, subtype);
903                                                 continue;
904                                         }
905                                 }
906
907                                 dump_ir_initializer(&vals[offset], sub_initializer, subtype);
908                         }
909                 }
910
911                 return;
912         }
913         }
914         panic("invalid ir_initializer kind found");
915 }
916
917 static void dump_initializer(be_gas_decl_env_t *env, ir_entity *entity)
918 {
919         const ir_initializer_t *initializer = entity->attr.initializer;
920         ir_type                *type;
921         normal_or_bitfield     *vals;
922         size_t                  size;
923         size_t                  k;
924
925         if (initializer_is_string_const(initializer)) {
926                 dump_string_initializer(initializer);
927                 return;
928         }
929
930         type = get_entity_type(entity);
931         size = get_initializer_size(initializer, type);
932
933         if (size == 0)
934                 return;
935
936         /*
937          * In the worst case, every initializer allocates one byte.
938          * Moreover, initializer might be big, do not allocate on stack.
939          */
940         vals = XMALLOCNZ(normal_or_bitfield, size);
941
942 #ifndef NDEBUG
943         glob_vals = vals;
944         max_vals  = size;
945 #endif
946
947         dump_ir_initializer(vals, initializer, type);
948
949         /* now write values sorted */
950         for (k = 0; k < size; ) {
951                 int space     = 0;
952                 int elem_size = 1;
953                 if (vals[k].kind == NORMAL) {
954                         if (vals[k].v.value != NULL) {
955                                 dump_atomic_init(env, vals[k].v.value);
956                                 elem_size = get_mode_size_bytes(get_irn_mode(vals[k].v.value));
957                         } else {
958                                 elem_size = 0;
959                         }
960                 } else if (vals[k].kind == TARVAL) {
961                         tarval *tv   = vals[k].v.tarval;
962                         size_t  size = get_mode_size_bytes(get_tarval_mode(tv));
963
964                         assert(tv != NULL);
965
966                         elem_size = size;
967                         dump_size_type(size);
968                         dump_arith_tarval(tv, size);
969                         be_emit_char('\n');
970                         be_emit_write_line();
971                 } else {
972                         assert(vals[k].kind == BITFIELD);
973                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
974                         be_emit_write_line();
975                 }
976
977                 k += elem_size;
978                 while (k < size && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
979                         ++space;
980                         ++k;
981                 }
982
983                 /* a gap */
984                 if (space > 0) {
985                         be_emit_irprintf("\t.space\t%d\n", space);
986                         be_emit_write_line();
987                 }
988         }
989         xfree(vals);
990 }
991
992 /**
993  * Dump an initializer for a compound entity.
994  */
995 static void dump_compound_init(be_gas_decl_env_t *env, ir_entity *ent)
996 {
997         normal_or_bitfield *vals;
998         int i, j, n;
999         unsigned k, last_ofs;
1000
1001         if (ent->has_initializer) {
1002                 dump_initializer(env, ent);
1003                 return;
1004         }
1005
1006         n = get_compound_ent_n_values(ent);
1007
1008         /* Find the initializer size. Sorrily gcc support a nasty feature:
1009            The last field of a compound may be a flexible array. This allows
1010            initializers bigger than the type size. */
1011         last_ofs = get_type_size_bytes(get_entity_type(ent));
1012         for (i = 0; i < n; ++i) {
1013                 unsigned offset         = get_compound_ent_value_offset_bytes(ent, i);
1014                 unsigned bits_remainder = get_compound_ent_value_offset_bit_remainder(ent, i);
1015                 ir_node  *value         = get_compound_ent_value(ent, i);
1016                 unsigned value_len      = get_mode_size_bits(get_irn_mode(value));
1017
1018                 offset += (value_len + bits_remainder + 7) >> 3;
1019
1020                 if (offset > last_ofs) {
1021                         last_ofs = offset;
1022                 }
1023         }
1024
1025         /*
1026          * In the worst case, every initializer allocates one byte.
1027          * Moreover, initializer might be big, do not allocate on stack.
1028          */
1029         vals = XMALLOCNZ(normal_or_bitfield, last_ofs);
1030
1031         /* collect the values and store them at the offsets */
1032         for (i = 0; i < n; ++i) {
1033                 unsigned offset      = get_compound_ent_value_offset_bytes(ent, i);
1034                 int      offset_bits = get_compound_ent_value_offset_bit_remainder(ent, i);
1035                 ir_node  *value      = get_compound_ent_value(ent, i);
1036                 int      value_len   = get_mode_size_bits(get_irn_mode(value));
1037
1038                 assert(offset_bits >= 0);
1039
1040                 if (offset_bits != 0 ||
1041                         (value_len != 8 && value_len != 16 && value_len != 32 && value_len != 64)) {
1042                         tarval *tv = get_atomic_init_tv(value);
1043                         unsigned char curr_bits, last_bits = 0;
1044                         if (tv == NULL) {
1045                                 panic("Couldn't get numeric value for bitfield initializer '%s'",
1046                                       get_entity_ld_name(ent));
1047                         }
1048                         /* normalize offset */
1049                         offset += offset_bits >> 3;
1050                         offset_bits &= 7;
1051
1052                         for (j = 0; value_len + offset_bits > 0; ++j) {
1053                                 assert(offset + j < last_ofs);
1054                                 assert(vals[offset + j].kind == BITFIELD || vals[offset + j].v.value == NULL);
1055                                 vals[offset + j].kind = BITFIELD;
1056                                 curr_bits = get_tarval_sub_bits(tv, j);
1057                                 vals[offset + j].v.bf_val |= (last_bits >> (8 - offset_bits)) | (curr_bits << offset_bits);
1058                                 value_len -= 8;
1059                                 last_bits = curr_bits;
1060                         }
1061                 } else {
1062                         int i;
1063
1064                         assert(offset < last_ofs);
1065                         assert(vals[offset].kind == NORMAL);
1066                         for (i = 1; i < value_len / 8; ++i) {
1067                                 assert(vals[offset + i].v.value == NULL);
1068                         }
1069                         vals[offset].v.value = value;
1070                 }
1071         }
1072
1073         /* now write them sorted */
1074         for (k = 0; k < last_ofs; ) {
1075                 int space = 0, skip = 0;
1076                 if (vals[k].kind == NORMAL) {
1077                         if (vals[k].v.value != NULL) {
1078                                 dump_atomic_init(env, vals[k].v.value);
1079                                 skip = get_mode_size_bytes(get_irn_mode(vals[k].v.value)) - 1;
1080                         } else {
1081                                 space = 1;
1082                         }
1083                 } else {
1084                         assert(vals[k].kind == BITFIELD);
1085                         be_emit_irprintf("\t.byte\t%d\n", vals[k].v.bf_val);
1086                 }
1087
1088                 ++k;
1089                 while (k < last_ofs && vals[k].kind == NORMAL && vals[k].v.value == NULL) {
1090                         ++space;
1091                         ++k;
1092                 }
1093                 space -= skip;
1094                 assert(space >= 0);
1095
1096                 /* a gap */
1097                 if (space > 0) {
1098                         be_emit_irprintf("\t.space\t%d\n", space);
1099                         be_emit_write_line();
1100                 }
1101         }
1102         xfree(vals);
1103 }
1104
1105 static void emit_align(unsigned p2alignment)
1106 {
1107         be_emit_irprintf("\t.p2align\t%u\n", log2_floor(p2alignment));
1108         be_emit_write_line();
1109 }
1110
1111 static unsigned get_effective_entity_alignment(ir_entity *entity)
1112 {
1113         unsigned alignment = get_entity_alignment(entity);
1114         if (alignment == 0) {
1115                 ir_type *type = get_entity_type(entity);
1116                 alignment     = get_type_alignment_bytes(type);
1117         }
1118         return alignment;
1119 }
1120
1121
1122 /**
1123  * Dump a global entity.
1124  *
1125  * @param env           the gas output environment
1126  * @param ent           the entity to be dumped
1127  */
1128 static void dump_global(be_gas_decl_env_t *env, ir_entity *ent)
1129 {
1130         ir_type          *type           = get_entity_type(ent);
1131         ident            *ld_ident       = get_entity_ld_ident(ent);
1132         unsigned          alignment      = get_effective_entity_alignment(ent);
1133         int               emit_as_common = 0;
1134         be_gas_section_t  section        = env->section;
1135         ir_variability    variability    = get_entity_variability(ent);
1136         ir_visibility     visibility     = get_entity_visibility(ent);
1137
1138         if (is_Method_type(type) && section != GAS_SECTION_PIC_TRAMPOLINES) {
1139                 return;
1140         }
1141         if (type == firm_code_type) {
1142                 return;
1143         }
1144
1145         if (section != (be_gas_section_t) -1) {
1146                 emit_as_common = 0;
1147         } else if (variability == variability_constant) {
1148                 /* a constant entity, put it on the rdata */
1149                 section = GAS_SECTION_RODATA;
1150                 if (be_gas_flavour == GAS_FLAVOUR_MACH_O
1151                                 && ent_is_string_const(ent)) {
1152                         section = GAS_SECTION_CSTRING;
1153                 }
1154         } else if (variability == variability_uninitialized) {
1155                 /* uninitialized entity put it in bss segment */
1156                 section = GAS_SECTION_COMMON;
1157                 if (visibility != visibility_local)
1158                         emit_as_common = 1;
1159         } else {
1160                 section = GAS_SECTION_DATA;
1161         }
1162
1163         if (!emit_as_common) {
1164                 be_gas_emit_switch_section(section);
1165         }
1166
1167         be_dbg_variable(ent);
1168
1169         /* global or not global */
1170         if (visibility == visibility_external_visible && !emit_as_common) {
1171                 be_emit_cstring(".globl\t");
1172                 be_emit_ident(ld_ident);
1173                 be_emit_char('\n');
1174                 be_emit_write_line();
1175         } else if (visibility == visibility_external_allocated) {
1176                 be_emit_cstring(".globl\t");
1177                 be_emit_ident(ld_ident);
1178                 be_emit_char('\n');
1179                 be_emit_write_line();
1180                 /* we can return now... */
1181                 return;
1182         }
1183         if (!is_po2(alignment))
1184                 panic("alignment not a power of 2");
1185         /* alignment */
1186         if (alignment > 1 && !emit_as_common && section != GAS_SECTION_PIC_TRAMPOLINES
1187                         && section != GAS_SECTION_PIC_SYMBOLS) {
1188                 emit_align(alignment);
1189         }
1190
1191         if (visibility != visibility_external_allocated && !emit_as_common
1192                         && be_gas_flavour == GAS_FLAVOUR_ELF
1193                         && be_gas_emit_types) {
1194                 be_emit_cstring("\t.type\t");
1195                 be_emit_ident(ld_ident);
1196                 be_emit_cstring(", @object\n\t.size\t");
1197                 be_emit_ident(ld_ident);
1198                 be_emit_irprintf(", %u\n", get_type_size_bytes(type));
1199         }
1200
1201         if (!emit_as_common) {
1202                 be_emit_ident(ld_ident);
1203                 be_emit_cstring(":\n");
1204                 be_emit_write_line();
1205         }
1206
1207         if (variability == variability_uninitialized) {
1208                 if (emit_as_common) {
1209                         switch (be_gas_flavour) {
1210                         case GAS_FLAVOUR_MACH_O:
1211                                 be_emit_irprintf("\t.comm %s,%u,%u\n",
1212                                         get_id_str(ld_ident), get_type_size_bytes(type),
1213                                         log2_floor(alignment));
1214                                 break;
1215                         case GAS_FLAVOUR_ELF:
1216                         case GAS_FLAVOUR_YASM:
1217                                 be_emit_irprintf("\t.comm %s,%u,%u\n",
1218                                         get_id_str(ld_ident), get_type_size_bytes(type), alignment);
1219                                 be_emit_write_line();
1220                                 break;
1221                         case GAS_FLAVOUR_MINGW:
1222                                 be_emit_irprintf("\t.comm %s,%u # %u\n",
1223                                         get_id_str(ld_ident), get_type_size_bytes(type), alignment);
1224                                 be_emit_write_line();
1225                                 break;
1226                         }
1227                 } else if (section == GAS_SECTION_PIC_TRAMPOLINES
1228                                 || section == GAS_SECTION_PIC_SYMBOLS) {
1229                         if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
1230                                 be_emit_cstring("\t.indirect_symbol ");
1231                                 be_emit_ident(get_entity_ident(ent));
1232                                 be_emit_char('\n');
1233                                 be_emit_write_line();
1234                                 if (section == GAS_SECTION_PIC_TRAMPOLINES) {
1235                                         be_emit_cstring("\thlt ; hlt ; hlt ; hlt ; hlt\n");
1236                                         be_emit_write_line();
1237                                 } else {
1238                                         assert(section == GAS_SECTION_PIC_SYMBOLS);
1239                                         be_emit_cstring("\t.long 0\n");
1240                                         be_emit_write_line();
1241                                 }
1242                         } else {
1243                                 panic("PIC trampolines not yet supported in this gas mode");
1244                         }
1245                 } else {
1246                         be_emit_irprintf("\t.space %u\n", get_type_size_bytes(type));
1247                         be_emit_write_line();
1248                 }
1249         } else {
1250                 if (is_atomic_entity(ent)) {
1251                         dump_atomic_init(env, get_atomic_ent_value(ent));
1252                 } else {
1253                         /* sort_compound_ent_values(ent); */
1254
1255                         switch (get_type_tpop_code(get_entity_type(ent))) {
1256                         case tpo_array:
1257                                 if (ent_is_string_const(ent))
1258                                         dump_string_cst(ent);
1259                                 else
1260                                         dump_compound_init(env, ent);
1261                                 break;
1262                         case tpo_struct:
1263                         case tpo_class:
1264                         case tpo_union:
1265                                 dump_compound_init(env, ent);
1266                                 break;
1267                         default:
1268                                 panic("Unimplemented type kind in dump_global()");
1269                         }
1270                 }
1271         }
1272 }
1273
1274 /**
1275  * Dumps declarations of global variables and the initialization code.
1276  *
1277  * @param gt                a global like type, either the global or the TLS one
1278  * @param env               an environment
1279  * @param only_emit_marked  if non-zero, external allocated entities that do not have
1280  *                          its visited flag set are ignored
1281  */
1282 static void be_gas_dump_globals(ir_type *gt, be_gas_decl_env_t *env,
1283                                 int only_emit_marked)
1284 {
1285         int i, n = get_compound_n_members(gt);
1286         waitq *worklist = new_waitq();
1287
1288         if (only_emit_marked) {
1289                 for (i = 0; i < n; i++) {
1290                         ir_entity *ent = get_compound_member(gt, i);
1291                         if (is_entity_backend_marked(ent) ||
1292                             get_entity_visibility(ent) != visibility_external_allocated) {
1293                                 waitq_put(worklist, ent);
1294                                 set_entity_backend_marked(ent, 1);
1295                         }
1296                 }
1297         } else {
1298                 for (i = 0; i < n; i++) {
1299                         ir_entity *ent = get_compound_member(gt, i);
1300                         set_entity_backend_marked(ent, 1);
1301                         waitq_put(worklist, ent);
1302                 }
1303         }
1304
1305         env->worklist = worklist;
1306
1307         while (!waitq_empty(worklist)) {
1308                 ir_entity *ent = waitq_get(worklist);
1309
1310                 dump_global(env, ent);
1311         }
1312
1313         del_waitq(worklist);
1314         env->worklist = NULL;
1315 }
1316
1317 /************************************************************************/
1318
1319 /* Generate all entities. */
1320 void be_gas_emit_decls(const be_main_env_t *main_env,
1321                        int only_emit_marked_entities)
1322 {
1323         be_gas_decl_env_t env;
1324         memset(&env, 0, sizeof(env));
1325
1326         /* dump global type */
1327         env.section = (be_gas_section_t) -1;
1328         be_gas_dump_globals(get_glob_type(), &env, only_emit_marked_entities);
1329         env.section = GAS_SECTION_TLS;
1330         be_gas_dump_globals(get_tls_type(), &env, only_emit_marked_entities);
1331         env.section = GAS_SECTION_CONSTRUCTORS;
1332         be_gas_dump_globals(get_segment_type(IR_SEGMENT_CONSTRUCTORS), &env,
1333                             only_emit_marked_entities);
1334         env.section = GAS_SECTION_DESTRUCTORS;
1335         be_gas_dump_globals(get_segment_type(IR_SEGMENT_DESTRUCTORS), &env,
1336                             only_emit_marked_entities);
1337
1338         env.section = GAS_SECTION_PIC_SYMBOLS;
1339         be_gas_dump_globals(main_env->pic_symbols_type, &env,
1340                             only_emit_marked_entities);
1341
1342         if (get_compound_n_members(main_env->pic_trampolines_type) > 0) {
1343                 env.section = GAS_SECTION_PIC_TRAMPOLINES;
1344                 be_gas_dump_globals(main_env->pic_trampolines_type, &env,
1345                                     only_emit_marked_entities);
1346                 if (be_gas_flavour == GAS_FLAVOUR_MACH_O) {
1347                         be_emit_cstring("\t.subsections_via_symbols\n");
1348                         be_emit_write_line();
1349                 }
1350         }
1351 }