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