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