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