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