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