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