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