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