When creating a staticaly linked ELF program should not include
[tinycc.git] / tccasm.c
blobf22ed9f59ed15f7f65397ba43e7ebf1a7b869e8c
1 /*
2 * GAS like assembler for TCC
3 *
4 * Copyright (c) 2001-2004 Fabrice Bellard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "tcc.h"
22 #ifdef CONFIG_TCC_ASM
24 ST_FUNC int asm_get_local_label_name(TCCState *s1, unsigned int n)
26 char buf[64];
27 TokenSym *ts;
29 snprintf(buf, sizeof(buf), "L..%u", n);
30 ts = tok_alloc(buf, strlen(buf));
31 return ts->tok;
34 ST_FUNC void asm_expr(TCCState *s1, ExprValue *pe);
35 static int tcc_assemble_internal(TCCState *s1, int do_preprocess, int global);
36 static Sym sym_dot;
38 /* Return a symbol we can use inside the assembler, having name NAME.
39 The assembler symbol table is different from the C symbol table
40 (and the Sym members are used differently). But we must be able
41 to look up file-global C symbols from inside the assembler, e.g.
42 for global asm blocks to be able to refer to defined C symbols.
44 This routine gives back either an existing asm-internal
45 symbol, or a new one. In the latter case the new asm-internal
46 symbol is initialized with info from the C symbol table.
48 If CSYM is non-null we take symbol info from it, otherwise
49 we look up NAME in the C symbol table and use that. */
50 ST_FUNC Sym* get_asm_sym(int name, Sym *csym)
52 Sym *sym = label_find(name);
53 if (!sym) {
54 sym = label_push(&tcc_state->asm_labels, name, 0);
55 sym->type.t = VT_VOID | VT_EXTERN;
56 if (!csym) {
57 csym = sym_find(name);
58 /* We might be called for an asm block from inside a C routine
59 and so might have local decls on the identifier stack. Search
60 for the first global one. */
61 while (csym && csym->scope)
62 csym = csym->prev_tok;
64 /* Now, if we have a defined global symbol copy over
65 section and offset. */
66 if (csym &&
67 ((csym->r & (VT_SYM|VT_CONST)) == (VT_SYM|VT_CONST)) &&
68 csym->c) {
69 ElfW(Sym) *esym;
70 esym = &((ElfW(Sym) *)symtab_section->data)[csym->c];
71 sym->c = csym->c;
72 sym->r = esym->st_shndx;
73 sym->jnext = esym->st_value;
74 /* XXX can't yet store st_size anywhere. */
75 sym->type.t &= ~VT_EXTERN;
76 /* Mark that this asm symbol doesn't need to be fed back. */
77 sym->type.t |= VT_IMPORT;
80 return sym;
83 /* We do not use the C expression parser to handle symbols. Maybe the
84 C expression parser could be tweaked to do so. */
86 static void asm_expr_unary(TCCState *s1, ExprValue *pe)
88 Sym *sym;
89 int op, label;
90 uint64_t n;
91 const char *p;
93 switch(tok) {
94 case TOK_PPNUM:
95 p = tokc.str.data;
96 n = strtoull(p, (char **)&p, 0);
97 if (*p == 'b' || *p == 'f') {
98 /* backward or forward label */
99 label = asm_get_local_label_name(s1, n);
100 sym = label_find(label);
101 if (*p == 'b') {
102 /* backward : find the last corresponding defined label */
103 if (sym && sym->r == 0)
104 sym = sym->prev_tok;
105 if (!sym)
106 tcc_error("local label '%d' not found backward", n);
107 } else {
108 /* forward */
109 if (!sym || sym->r) {
110 /* if the last label is defined, then define a new one */
111 sym = label_push(&s1->asm_labels, label, 0);
112 sym->type.t = VT_STATIC | VT_VOID | VT_EXTERN;
115 pe->v = 0;
116 pe->sym = sym;
117 pe->pcrel = 0;
118 } else if (*p == '\0') {
119 pe->v = n;
120 pe->sym = NULL;
121 pe->pcrel = 0;
122 } else {
123 tcc_error("invalid number syntax");
125 next();
126 break;
127 case '+':
128 next();
129 asm_expr_unary(s1, pe);
130 break;
131 case '-':
132 case '~':
133 op = tok;
134 next();
135 asm_expr_unary(s1, pe);
136 if (pe->sym)
137 tcc_error("invalid operation with label");
138 if (op == '-')
139 pe->v = -pe->v;
140 else
141 pe->v = ~pe->v;
142 break;
143 case TOK_CCHAR:
144 case TOK_LCHAR:
145 pe->v = tokc.i;
146 pe->sym = NULL;
147 pe->pcrel = 0;
148 next();
149 break;
150 case '(':
151 next();
152 asm_expr(s1, pe);
153 skip(')');
154 break;
155 case '.':
156 pe->v = 0;
157 pe->sym = &sym_dot;
158 pe->pcrel = 0;
159 sym_dot.type.t = VT_VOID | VT_STATIC;
160 sym_dot.r = cur_text_section->sh_num;
161 sym_dot.jnext = ind;
162 next();
163 break;
164 default:
165 if (tok >= TOK_IDENT) {
166 /* label case : if the label was not found, add one */
167 sym = get_asm_sym(tok, NULL);
168 if (sym->r == SHN_ABS) {
169 /* if absolute symbol, no need to put a symbol value */
170 pe->v = sym->jnext;
171 pe->sym = NULL;
172 pe->pcrel = 0;
173 } else {
174 pe->v = 0;
175 pe->sym = sym;
176 pe->pcrel = 0;
178 next();
179 } else {
180 tcc_error("bad expression syntax [%s]", get_tok_str(tok, &tokc));
182 break;
186 static void asm_expr_prod(TCCState *s1, ExprValue *pe)
188 int op;
189 ExprValue e2;
191 asm_expr_unary(s1, pe);
192 for(;;) {
193 op = tok;
194 if (op != '*' && op != '/' && op != '%' &&
195 op != TOK_SHL && op != TOK_SAR)
196 break;
197 next();
198 asm_expr_unary(s1, &e2);
199 if (pe->sym || e2.sym)
200 tcc_error("invalid operation with label");
201 switch(op) {
202 case '*':
203 pe->v *= e2.v;
204 break;
205 case '/':
206 if (e2.v == 0) {
207 div_error:
208 tcc_error("division by zero");
210 pe->v /= e2.v;
211 break;
212 case '%':
213 if (e2.v == 0)
214 goto div_error;
215 pe->v %= e2.v;
216 break;
217 case TOK_SHL:
218 pe->v <<= e2.v;
219 break;
220 default:
221 case TOK_SAR:
222 pe->v >>= e2.v;
223 break;
228 static void asm_expr_logic(TCCState *s1, ExprValue *pe)
230 int op;
231 ExprValue e2;
233 asm_expr_prod(s1, pe);
234 for(;;) {
235 op = tok;
236 if (op != '&' && op != '|' && op != '^')
237 break;
238 next();
239 asm_expr_prod(s1, &e2);
240 if (pe->sym || e2.sym)
241 tcc_error("invalid operation with label");
242 switch(op) {
243 case '&':
244 pe->v &= e2.v;
245 break;
246 case '|':
247 pe->v |= e2.v;
248 break;
249 default:
250 case '^':
251 pe->v ^= e2.v;
252 break;
257 static inline void asm_expr_sum(TCCState *s1, ExprValue *pe)
259 int op;
260 ExprValue e2;
262 asm_expr_logic(s1, pe);
263 for(;;) {
264 op = tok;
265 if (op != '+' && op != '-')
266 break;
267 next();
268 asm_expr_logic(s1, &e2);
269 if (op == '+') {
270 if (pe->sym != NULL && e2.sym != NULL)
271 goto cannot_relocate;
272 pe->v += e2.v;
273 if (pe->sym == NULL && e2.sym != NULL)
274 pe->sym = e2.sym;
275 } else {
276 pe->v -= e2.v;
277 /* NOTE: we are less powerful than gas in that case
278 because we store only one symbol in the expression */
279 if (!e2.sym) {
280 /* OK */
281 } else if (pe->sym == e2.sym) {
282 /* OK */
283 pe->sym = NULL; /* same symbols can be subtracted to NULL */
284 } else if (pe->sym && pe->sym->r == e2.sym->r && pe->sym->r != 0) {
285 /* we also accept defined symbols in the same section */
286 pe->v += pe->sym->jnext - e2.sym->jnext;
287 pe->sym = NULL;
288 } else if (e2.sym->r == cur_text_section->sh_num) {
289 /* When subtracting a defined symbol in current section
290 this actually makes the value PC-relative. */
291 pe->v -= e2.sym->jnext - ind - 4;
292 pe->pcrel = 1;
293 e2.sym = NULL;
294 } else {
295 cannot_relocate:
296 tcc_error("invalid operation with label");
302 static inline void asm_expr_cmp(TCCState *s1, ExprValue *pe)
304 int op;
305 ExprValue e2;
307 asm_expr_sum(s1, pe);
308 for(;;) {
309 op = tok;
310 if (op != TOK_EQ && op != TOK_NE
311 && (op > TOK_GT || op < TOK_ULE))
312 break;
313 next();
314 asm_expr_sum(s1, &e2);
315 if (pe->sym || e2.sym)
316 tcc_error("invalid operation with label");
317 switch(op) {
318 case TOK_EQ:
319 pe->v = pe->v == e2.v;
320 break;
321 case TOK_NE:
322 pe->v = pe->v != e2.v;
323 break;
324 case TOK_LT:
325 pe->v = (int64_t)pe->v < (int64_t)e2.v;
326 break;
327 case TOK_GE:
328 pe->v = (int64_t)pe->v >= (int64_t)e2.v;
329 break;
330 case TOK_LE:
331 pe->v = (int64_t)pe->v <= (int64_t)e2.v;
332 break;
333 case TOK_GT:
334 pe->v = (int64_t)pe->v > (int64_t)e2.v;
335 break;
336 default:
337 break;
339 /* GAS compare results are -1/0 not 1/0. */
340 pe->v = -(int64_t)pe->v;
344 ST_FUNC void asm_expr(TCCState *s1, ExprValue *pe)
346 asm_expr_cmp(s1, pe);
349 ST_FUNC int asm_int_expr(TCCState *s1)
351 ExprValue e;
352 asm_expr(s1, &e);
353 if (e.sym)
354 expect("constant");
355 return e.v;
358 /* NOTE: the same name space as C labels is used to avoid using too
359 much memory when storing labels in TokenStrings */
360 static Sym* asm_new_label1(TCCState *s1, int label, int is_local,
361 int sh_num, int value)
363 Sym *sym;
365 sym = label_find(label);
366 if (sym) {
367 /* A VT_EXTERN symbol, even if it has a section is considered
368 overridable. This is how we "define" .set targets. Real
369 definitions won't have VT_EXTERN set. */
370 if (sym->r && !(sym->type.t & VT_EXTERN)) {
371 /* the label is already defined */
372 if (!is_local) {
373 tcc_error("assembler label '%s' already defined",
374 get_tok_str(label, NULL));
375 } else {
376 /* redefinition of local labels is possible */
377 goto new_label;
380 } else {
381 new_label:
382 sym = label_push(&s1->asm_labels, label, 0);
383 /* If we need a symbol to hold a value, mark it as
384 tentative only (for .set). If this is for a real label
385 we'll remove VT_EXTERN. */
386 sym->type.t = VT_STATIC | VT_VOID | VT_EXTERN;
388 sym->r = sh_num;
389 sym->jnext = value;
390 return sym;
393 static Sym* asm_new_label(TCCState *s1, int label, int is_local)
395 return asm_new_label1(s1, label, is_local, cur_text_section->sh_num, ind);
398 /* Set the value of LABEL to that of some expression (possibly
399 involving other symbols). LABEL can be overwritten later still. */
400 static Sym* set_symbol(TCCState *s1, int label)
402 long n;
403 ExprValue e;
404 next();
405 asm_expr(s1, &e);
406 n = e.v;
407 if (e.sym)
408 n += e.sym->jnext;
409 return asm_new_label1(s1, label, 0, e.sym ? e.sym->r : SHN_ABS, n);
412 static void asm_free_labels(TCCState *st)
414 Sym *s, *s1;
415 Section *sec;
417 for(s = st->asm_labels; s != NULL; s = s1) {
418 s1 = s->prev;
419 /* define symbol value in object file */
420 s->type.t &= ~VT_EXTERN;
421 if (s->r && !(s->type.t & VT_IMPORT)) {
422 if (s->r == SHN_ABS)
423 sec = SECTION_ABS;
424 else
425 sec = st->sections[s->r];
426 put_extern_sym2(s, sec, s->jnext, 0, 0);
428 /* remove label */
429 table_ident[s->v - TOK_IDENT]->sym_label = NULL;
430 sym_free(s);
432 st->asm_labels = NULL;
435 static void use_section1(TCCState *s1, Section *sec)
437 cur_text_section->data_offset = ind;
438 cur_text_section = sec;
439 ind = cur_text_section->data_offset;
442 static void use_section(TCCState *s1, const char *name)
444 Section *sec;
445 sec = find_section(s1, name);
446 use_section1(s1, sec);
449 static void push_section(TCCState *s1, const char *name)
451 Section *sec = find_section(s1, name);
452 sec->prev = cur_text_section;
453 use_section1(s1, sec);
456 static void pop_section(TCCState *s1)
458 Section *prev = cur_text_section->prev;
459 if (!prev)
460 tcc_error(".popsection without .pushsection");
461 cur_text_section->prev = NULL;
462 use_section1(s1, prev);
465 static void asm_parse_directive(TCCState *s1, int global)
467 int n, offset, v, size, tok1;
468 Section *sec;
469 uint8_t *ptr;
471 /* assembler directive */
472 sec = cur_text_section;
473 switch(tok) {
474 case TOK_ASMDIR_align:
475 case TOK_ASMDIR_balign:
476 case TOK_ASMDIR_p2align:
477 case TOK_ASMDIR_skip:
478 case TOK_ASMDIR_space:
479 tok1 = tok;
480 next();
481 n = asm_int_expr(s1);
482 if (tok1 == TOK_ASMDIR_p2align)
484 if (n < 0 || n > 30)
485 tcc_error("invalid p2align, must be between 0 and 30");
486 n = 1 << n;
487 tok1 = TOK_ASMDIR_align;
489 if (tok1 == TOK_ASMDIR_align || tok1 == TOK_ASMDIR_balign) {
490 if (n < 0 || (n & (n-1)) != 0)
491 tcc_error("alignment must be a positive power of two");
492 offset = (ind + n - 1) & -n;
493 size = offset - ind;
494 /* the section must have a compatible alignment */
495 if (sec->sh_addralign < n)
496 sec->sh_addralign = n;
497 } else {
498 if (n < 0)
499 n = 0;
500 size = n;
502 v = 0;
503 if (tok == ',') {
504 next();
505 v = asm_int_expr(s1);
507 zero_pad:
508 if (sec->sh_type != SHT_NOBITS) {
509 sec->data_offset = ind;
510 ptr = section_ptr_add(sec, size);
511 memset(ptr, v, size);
513 ind += size;
514 break;
515 case TOK_ASMDIR_quad:
516 #ifdef TCC_TARGET_X86_64
517 size = 8;
518 goto asm_data;
519 #else
520 next();
521 for(;;) {
522 uint64_t vl;
523 const char *p;
525 p = tokc.str.data;
526 if (tok != TOK_PPNUM) {
527 error_constant:
528 tcc_error("64 bit constant");
530 vl = strtoll(p, (char **)&p, 0);
531 if (*p != '\0')
532 goto error_constant;
533 next();
534 if (sec->sh_type != SHT_NOBITS) {
535 /* XXX: endianness */
536 gen_le32(vl);
537 gen_le32(vl >> 32);
538 } else {
539 ind += 8;
541 if (tok != ',')
542 break;
543 next();
545 break;
546 #endif
547 case TOK_ASMDIR_byte:
548 size = 1;
549 goto asm_data;
550 case TOK_ASMDIR_word:
551 case TOK_ASMDIR_short:
552 size = 2;
553 goto asm_data;
554 case TOK_ASMDIR_long:
555 case TOK_ASMDIR_int:
556 size = 4;
557 asm_data:
558 next();
559 for(;;) {
560 ExprValue e;
561 asm_expr(s1, &e);
562 if (sec->sh_type != SHT_NOBITS) {
563 if (size == 4) {
564 gen_expr32(&e);
565 #ifdef TCC_TARGET_X86_64
566 } else if (size == 8) {
567 gen_expr64(&e);
568 #endif
569 } else {
570 if (e.sym)
571 expect("constant");
572 if (size == 1)
573 g(e.v);
574 else
575 gen_le16(e.v);
577 } else {
578 ind += size;
580 if (tok != ',')
581 break;
582 next();
584 break;
585 case TOK_ASMDIR_fill:
587 int repeat, size, val, i, j;
588 uint8_t repeat_buf[8];
589 next();
590 repeat = asm_int_expr(s1);
591 if (repeat < 0) {
592 tcc_error("repeat < 0; .fill ignored");
593 break;
595 size = 1;
596 val = 0;
597 if (tok == ',') {
598 next();
599 size = asm_int_expr(s1);
600 if (size < 0) {
601 tcc_error("size < 0; .fill ignored");
602 break;
604 if (size > 8)
605 size = 8;
606 if (tok == ',') {
607 next();
608 val = asm_int_expr(s1);
611 /* XXX: endianness */
612 repeat_buf[0] = val;
613 repeat_buf[1] = val >> 8;
614 repeat_buf[2] = val >> 16;
615 repeat_buf[3] = val >> 24;
616 repeat_buf[4] = 0;
617 repeat_buf[5] = 0;
618 repeat_buf[6] = 0;
619 repeat_buf[7] = 0;
620 for(i = 0; i < repeat; i++) {
621 for(j = 0; j < size; j++) {
622 g(repeat_buf[j]);
626 break;
627 case TOK_ASMDIR_rept:
629 int repeat;
630 TokenString *init_str;
631 ParseState saved_parse_state = {0};
632 next();
633 repeat = asm_int_expr(s1);
634 init_str = tok_str_alloc();
635 next();
636 while ((tok != TOK_ASMDIR_endr) && (tok != CH_EOF)) {
637 tok_str_add_tok(init_str);
638 next();
640 if (tok == CH_EOF) tcc_error("we at end of file, .endr not found");
641 next();
642 tok_str_add(init_str, -1);
643 tok_str_add(init_str, 0);
644 save_parse_state(&saved_parse_state);
645 begin_macro(init_str, 1);
646 while (repeat-- > 0) {
647 tcc_assemble_internal(s1, (parse_flags & PARSE_FLAG_PREPROCESS),
648 global);
649 macro_ptr = init_str->str;
651 end_macro();
652 restore_parse_state(&saved_parse_state);
653 break;
655 case TOK_ASMDIR_org:
657 unsigned long n;
658 ExprValue e;
659 next();
660 asm_expr(s1, &e);
661 n = e.v;
662 if (e.sym) {
663 if (e.sym->r != cur_text_section->sh_num)
664 expect("constant or same-section symbol");
665 n += e.sym->jnext;
667 if (n < ind)
668 tcc_error("attempt to .org backwards");
669 v = 0;
670 size = n - ind;
671 goto zero_pad;
673 break;
674 case TOK_ASMDIR_set:
675 next();
676 tok1 = tok;
677 next();
678 /* Also accept '.set stuff', but don't do anything with this.
679 It's used in GAS to set various features like '.set mips16'. */
680 if (tok == ',')
681 set_symbol(s1, tok1);
682 break;
683 case TOK_ASMDIR_globl:
684 case TOK_ASMDIR_global:
685 case TOK_ASMDIR_weak:
686 case TOK_ASMDIR_hidden:
687 tok1 = tok;
688 do {
689 Sym *sym;
691 next();
692 sym = get_asm_sym(tok, NULL);
693 if (tok1 != TOK_ASMDIR_hidden)
694 sym->type.t &= ~VT_STATIC;
695 if (tok1 == TOK_ASMDIR_weak)
696 sym->type.t |= VT_WEAK;
697 else if (tok1 == TOK_ASMDIR_hidden)
698 sym->type.t |= STV_HIDDEN << VT_VIS_SHIFT;
699 next();
700 } while (tok == ',');
701 break;
702 case TOK_ASMDIR_string:
703 case TOK_ASMDIR_ascii:
704 case TOK_ASMDIR_asciz:
706 const uint8_t *p;
707 int i, size, t;
709 t = tok;
710 next();
711 for(;;) {
712 if (tok != TOK_STR)
713 expect("string constant");
714 p = tokc.str.data;
715 size = tokc.str.size;
716 if (t == TOK_ASMDIR_ascii && size > 0)
717 size--;
718 for(i = 0; i < size; i++)
719 g(p[i]);
720 next();
721 if (tok == ',') {
722 next();
723 } else if (tok != TOK_STR) {
724 break;
728 break;
729 case TOK_ASMDIR_text:
730 case TOK_ASMDIR_data:
731 case TOK_ASMDIR_bss:
733 char sname[64];
734 tok1 = tok;
735 n = 0;
736 next();
737 if (tok != ';' && tok != TOK_LINEFEED) {
738 n = asm_int_expr(s1);
739 next();
741 if (n)
742 sprintf(sname, "%s%d", get_tok_str(tok1, NULL), n);
743 else
744 sprintf(sname, "%s", get_tok_str(tok1, NULL));
745 use_section(s1, sname);
747 break;
748 case TOK_ASMDIR_file:
750 char filename[512];
752 filename[0] = '\0';
753 next();
755 if (tok == TOK_STR)
756 pstrcat(filename, sizeof(filename), tokc.str.data);
757 else
758 pstrcat(filename, sizeof(filename), get_tok_str(tok, NULL));
760 if (s1->warn_unsupported)
761 tcc_warning("ignoring .file %s", filename);
763 next();
765 break;
766 case TOK_ASMDIR_ident:
768 char ident[256];
770 ident[0] = '\0';
771 next();
773 if (tok == TOK_STR)
774 pstrcat(ident, sizeof(ident), tokc.str.data);
775 else
776 pstrcat(ident, sizeof(ident), get_tok_str(tok, NULL));
778 if (s1->warn_unsupported)
779 tcc_warning("ignoring .ident %s", ident);
781 next();
783 break;
784 case TOK_ASMDIR_size:
786 Sym *sym;
788 next();
789 sym = label_find(tok);
790 if (!sym) {
791 tcc_error("label not found: %s", get_tok_str(tok, NULL));
794 /* XXX .size name,label2-label1 */
795 if (s1->warn_unsupported)
796 tcc_warning("ignoring .size %s,*", get_tok_str(tok, NULL));
798 next();
799 skip(',');
800 while (tok != TOK_LINEFEED && tok != ';' && tok != CH_EOF) {
801 next();
804 break;
805 case TOK_ASMDIR_type:
807 Sym *sym;
808 const char *newtype;
810 next();
811 sym = get_asm_sym(tok, NULL);
812 next();
813 skip(',');
814 if (tok == TOK_STR) {
815 newtype = tokc.str.data;
816 } else {
817 if (tok == '@' || tok == '%')
818 next();
819 newtype = get_tok_str(tok, NULL);
822 if (!strcmp(newtype, "function") || !strcmp(newtype, "STT_FUNC")) {
823 sym->type.t = (sym->type.t & ~VT_BTYPE) | VT_FUNC;
825 else if (s1->warn_unsupported)
826 tcc_warning("change type of '%s' from 0x%x to '%s' ignored",
827 get_tok_str(sym->v, NULL), sym->type.t, newtype);
829 next();
831 break;
832 case TOK_ASMDIR_pushsection:
833 case TOK_ASMDIR_section:
835 char sname[256];
836 int old_nb_section = s1->nb_sections;
838 tok1 = tok;
839 /* XXX: support more options */
840 next();
841 sname[0] = '\0';
842 while (tok != ';' && tok != TOK_LINEFEED && tok != ',') {
843 if (tok == TOK_STR)
844 pstrcat(sname, sizeof(sname), tokc.str.data);
845 else
846 pstrcat(sname, sizeof(sname), get_tok_str(tok, NULL));
847 next();
849 if (tok == ',') {
850 /* skip section options */
851 next();
852 if (tok != TOK_STR)
853 expect("string constant");
854 next();
855 if (tok == ',') {
856 next();
857 if (tok == '@' || tok == '%')
858 next();
859 next();
862 last_text_section = cur_text_section;
863 if (tok1 == TOK_ASMDIR_section)
864 use_section(s1, sname);
865 else
866 push_section(s1, sname);
867 /* If we just allocated a new section reset its alignment to
868 1. new_section normally acts for GCC compatibility and
869 sets alignment to PTR_SIZE. The assembler behaves different. */
870 if (old_nb_section != s1->nb_sections)
871 cur_text_section->sh_addralign = 1;
873 break;
874 case TOK_ASMDIR_previous:
876 Section *sec;
877 next();
878 if (!last_text_section)
879 tcc_error("no previous section referenced");
880 sec = cur_text_section;
881 use_section1(s1, last_text_section);
882 last_text_section = sec;
884 break;
885 case TOK_ASMDIR_popsection:
886 next();
887 pop_section(s1);
888 break;
889 #ifdef TCC_TARGET_I386
890 case TOK_ASMDIR_code16:
892 next();
893 s1->seg_size = 16;
895 break;
896 case TOK_ASMDIR_code32:
898 next();
899 s1->seg_size = 32;
901 break;
902 #endif
903 #ifdef TCC_TARGET_X86_64
904 /* added for compatibility with GAS */
905 case TOK_ASMDIR_code64:
906 next();
907 break;
908 #endif
909 default:
910 tcc_error("unknown assembler directive '.%s'", get_tok_str(tok, NULL));
911 break;
916 /* assemble a file */
917 static int tcc_assemble_internal(TCCState *s1, int do_preprocess, int global)
919 int opcode;
921 /* XXX: undefine C labels */
923 ch = file->buf_ptr[0];
924 tok_flags = TOK_FLAG_BOL | TOK_FLAG_BOF;
925 parse_flags = PARSE_FLAG_ASM_FILE | PARSE_FLAG_TOK_STR;
926 set_idnum('.', IS_ID);
927 if (do_preprocess)
928 parse_flags |= PARSE_FLAG_PREPROCESS;
929 for(;;) {
930 next();
931 if (tok == TOK_EOF)
932 break;
933 /* generate line number info */
934 if (global && s1->do_debug)
935 tcc_debug_line(s1);
936 parse_flags |= PARSE_FLAG_LINEFEED; /* XXX: suppress that hack */
937 redo:
938 if (tok == '#') {
939 /* horrible gas comment */
940 while (tok != TOK_LINEFEED)
941 next();
942 } else if (tok >= TOK_ASMDIR_FIRST && tok <= TOK_ASMDIR_LAST) {
943 asm_parse_directive(s1, global);
944 } else if (tok == TOK_PPNUM) {
945 Sym *sym;
946 const char *p;
947 int n;
948 p = tokc.str.data;
949 n = strtoul(p, (char **)&p, 10);
950 if (*p != '\0')
951 expect("':'");
952 /* new local label */
953 sym = asm_new_label(s1, asm_get_local_label_name(s1, n), 1);
954 /* Remove the marker for tentative definitions. */
955 sym->type.t &= ~VT_EXTERN;
956 next();
957 skip(':');
958 goto redo;
959 } else if (tok >= TOK_IDENT) {
960 /* instruction or label */
961 opcode = tok;
962 next();
963 if (tok == ':') {
964 /* handle "extern void vide(void); __asm__("vide: ret");" as
965 "__asm__("globl vide\nvide: ret");" */
966 Sym *sym = sym_find(opcode);
967 if (sym && (sym->type.t & VT_EXTERN) && global) {
968 sym = label_find(opcode);
969 if (!sym) {
970 sym = label_push(&s1->asm_labels, opcode, 0);
971 sym->type.t = VT_VOID | VT_EXTERN;
974 /* new label */
975 sym = asm_new_label(s1, opcode, 0);
976 sym->type.t &= ~VT_EXTERN;
977 next();
978 goto redo;
979 } else if (tok == '=') {
980 set_symbol(s1, opcode);
981 goto redo;
982 } else {
983 asm_opcode(s1, opcode);
986 /* end of line */
987 if (tok != ';' && tok != TOK_LINEFEED)
988 expect("end of line");
989 parse_flags &= ~PARSE_FLAG_LINEFEED; /* XXX: suppress that hack */
992 asm_free_labels(s1);
993 return 0;
996 /* Assemble the current file */
997 ST_FUNC int tcc_assemble(TCCState *s1, int do_preprocess)
999 Sym *define_start;
1000 int ret;
1002 define_start = define_stack;
1003 preprocess_start(s1);
1004 tcc_debug_start(s1);
1006 /* default section is text */
1007 cur_text_section = text_section;
1008 ind = cur_text_section->data_offset;
1009 nocode_wanted = 0;
1011 ret = tcc_assemble_internal(s1, do_preprocess, 1);
1013 cur_text_section->data_offset = ind;
1015 tcc_debug_end(s1);
1016 free_defines(define_start);
1017 return ret;
1020 /********************************************************************/
1021 /* GCC inline asm support */
1023 /* assemble the string 'str' in the current C compilation unit without
1024 C preprocessing. NOTE: str is modified by modifying the '\0' at the
1025 end */
1026 static void tcc_assemble_inline(TCCState *s1, char *str, int len, int global)
1028 int saved_parse_flags;
1029 const int *saved_macro_ptr;
1031 saved_parse_flags = parse_flags;
1032 saved_macro_ptr = macro_ptr;
1034 tcc_open_bf(s1, ":asm:", len);
1035 memcpy(file->buffer, str, len);
1037 macro_ptr = NULL;
1038 tcc_assemble_internal(s1, 0, global);
1039 tcc_close();
1041 parse_flags = saved_parse_flags;
1042 set_idnum('.', (parse_flags & PARSE_FLAG_ASM_FILE) ? IS_ID : 0);
1043 macro_ptr = saved_macro_ptr;
1046 /* find a constraint by its number or id (gcc 3 extended
1047 syntax). return -1 if not found. Return in *pp in char after the
1048 constraint */
1049 ST_FUNC int find_constraint(ASMOperand *operands, int nb_operands,
1050 const char *name, const char **pp)
1052 int index;
1053 TokenSym *ts;
1054 const char *p;
1056 if (isnum(*name)) {
1057 index = 0;
1058 while (isnum(*name)) {
1059 index = (index * 10) + (*name) - '0';
1060 name++;
1062 if ((unsigned)index >= nb_operands)
1063 index = -1;
1064 } else if (*name == '[') {
1065 name++;
1066 p = strchr(name, ']');
1067 if (p) {
1068 ts = tok_alloc(name, p - name);
1069 for(index = 0; index < nb_operands; index++) {
1070 if (operands[index].id == ts->tok)
1071 goto found;
1073 index = -1;
1074 found:
1075 name = p + 1;
1076 } else {
1077 index = -1;
1079 } else {
1080 index = -1;
1082 if (pp)
1083 *pp = name;
1084 return index;
1087 static void subst_asm_operands(ASMOperand *operands, int nb_operands,
1088 CString *out_str, CString *in_str)
1090 int c, index, modifier;
1091 const char *str;
1092 ASMOperand *op;
1093 SValue sv;
1095 cstr_new(out_str);
1096 str = in_str->data;
1097 for(;;) {
1098 c = *str++;
1099 if (c == '%') {
1100 if (*str == '%') {
1101 str++;
1102 goto add_char;
1104 modifier = 0;
1105 if (*str == 'c' || *str == 'n' ||
1106 *str == 'b' || *str == 'w' || *str == 'h' || *str == 'k' ||
1107 *str == 'q' ||
1108 /* P in GCC would add "@PLT" to symbol refs in PIC mode,
1109 and make literal operands not be decorated with '$'. */
1110 *str == 'P')
1111 modifier = *str++;
1112 index = find_constraint(operands, nb_operands, str, &str);
1113 if (index < 0)
1114 tcc_error("invalid operand reference after %%");
1115 op = &operands[index];
1116 sv = *op->vt;
1117 if (op->reg >= 0) {
1118 sv.r = op->reg;
1119 if ((op->vt->r & VT_VALMASK) == VT_LLOCAL && op->is_memory)
1120 sv.r |= VT_LVAL;
1122 subst_asm_operand(out_str, &sv, modifier);
1123 } else {
1124 add_char:
1125 cstr_ccat(out_str, c);
1126 if (c == '\0')
1127 break;
1133 static void parse_asm_operands(ASMOperand *operands, int *nb_operands_ptr,
1134 int is_output)
1136 ASMOperand *op;
1137 int nb_operands;
1139 if (tok != ':') {
1140 nb_operands = *nb_operands_ptr;
1141 for(;;) {
1142 CString astr;
1143 if (nb_operands >= MAX_ASM_OPERANDS)
1144 tcc_error("too many asm operands");
1145 op = &operands[nb_operands++];
1146 op->id = 0;
1147 if (tok == '[') {
1148 next();
1149 if (tok < TOK_IDENT)
1150 expect("identifier");
1151 op->id = tok;
1152 next();
1153 skip(']');
1155 parse_mult_str(&astr, "string constant");
1156 op->constraint = tcc_malloc(astr.size);
1157 strcpy(op->constraint, astr.data);
1158 cstr_free(&astr);
1159 skip('(');
1160 gexpr();
1161 if (is_output) {
1162 if (!(vtop->type.t & VT_ARRAY))
1163 test_lvalue();
1164 } else {
1165 /* we want to avoid LLOCAL case, except when the 'm'
1166 constraint is used. Note that it may come from
1167 register storage, so we need to convert (reg)
1168 case */
1169 if ((vtop->r & VT_LVAL) &&
1170 ((vtop->r & VT_VALMASK) == VT_LLOCAL ||
1171 (vtop->r & VT_VALMASK) < VT_CONST) &&
1172 !strchr(op->constraint, 'm')) {
1173 gv(RC_INT);
1176 op->vt = vtop;
1177 skip(')');
1178 if (tok == ',') {
1179 next();
1180 } else {
1181 break;
1184 *nb_operands_ptr = nb_operands;
1188 /* parse the GCC asm() instruction */
1189 ST_FUNC void asm_instr(void)
1191 CString astr, astr1;
1192 ASMOperand operands[MAX_ASM_OPERANDS];
1193 int nb_outputs, nb_operands, i, must_subst, out_reg;
1194 uint8_t clobber_regs[NB_ASM_REGS];
1196 next();
1197 /* since we always generate the asm() instruction, we can ignore
1198 volatile */
1199 if (tok == TOK_VOLATILE1 || tok == TOK_VOLATILE2 || tok == TOK_VOLATILE3) {
1200 next();
1202 parse_asm_str(&astr);
1203 nb_operands = 0;
1204 nb_outputs = 0;
1205 must_subst = 0;
1206 memset(clobber_regs, 0, sizeof(clobber_regs));
1207 if (tok == ':') {
1208 next();
1209 must_subst = 1;
1210 /* output args */
1211 parse_asm_operands(operands, &nb_operands, 1);
1212 nb_outputs = nb_operands;
1213 if (tok == ':') {
1214 next();
1215 if (tok != ')') {
1216 /* input args */
1217 parse_asm_operands(operands, &nb_operands, 0);
1218 if (tok == ':') {
1219 /* clobber list */
1220 /* XXX: handle registers */
1221 next();
1222 for(;;) {
1223 if (tok != TOK_STR)
1224 expect("string constant");
1225 asm_clobber(clobber_regs, tokc.str.data);
1226 next();
1227 if (tok == ',') {
1228 next();
1229 } else {
1230 break;
1237 skip(')');
1238 /* NOTE: we do not eat the ';' so that we can restore the current
1239 token after the assembler parsing */
1240 if (tok != ';')
1241 expect("';'");
1243 /* save all values in the memory */
1244 save_regs(0);
1246 /* compute constraints */
1247 asm_compute_constraints(operands, nb_operands, nb_outputs,
1248 clobber_regs, &out_reg);
1250 /* substitute the operands in the asm string. No substitution is
1251 done if no operands (GCC behaviour) */
1252 #ifdef ASM_DEBUG
1253 printf("asm: \"%s\"\n", (char *)astr.data);
1254 #endif
1255 if (must_subst) {
1256 subst_asm_operands(operands, nb_operands, &astr1, &astr);
1257 cstr_free(&astr);
1258 } else {
1259 astr1 = astr;
1261 #ifdef ASM_DEBUG
1262 printf("subst_asm: \"%s\"\n", (char *)astr1.data);
1263 #endif
1265 /* generate loads */
1266 asm_gen_code(operands, nb_operands, nb_outputs, 0,
1267 clobber_regs, out_reg);
1269 /* assemble the string with tcc internal assembler */
1270 tcc_assemble_inline(tcc_state, astr1.data, astr1.size - 1, 0);
1272 /* restore the current C token */
1273 next();
1275 /* store the output values if needed */
1276 asm_gen_code(operands, nb_operands, nb_outputs, 1,
1277 clobber_regs, out_reg);
1279 /* free everything */
1280 for(i=0;i<nb_operands;i++) {
1281 ASMOperand *op;
1282 op = &operands[i];
1283 tcc_free(op->constraint);
1284 vpop();
1286 cstr_free(&astr1);
1289 ST_FUNC void asm_global_instr(void)
1291 CString astr;
1292 int saved_nocode_wanted = nocode_wanted;
1294 /* Global asm blocks are always emitted. */
1295 nocode_wanted = 0;
1296 next();
1297 parse_asm_str(&astr);
1298 skip(')');
1299 /* NOTE: we do not eat the ';' so that we can restore the current
1300 token after the assembler parsing */
1301 if (tok != ';')
1302 expect("';'");
1304 #ifdef ASM_DEBUG
1305 printf("asm_global: \"%s\"\n", (char *)astr.data);
1306 #endif
1307 cur_text_section = text_section;
1308 ind = cur_text_section->data_offset;
1310 /* assemble the string with tcc internal assembler */
1311 tcc_assemble_inline(tcc_state, astr.data, astr.size - 1, 1);
1313 cur_text_section->data_offset = ind;
1315 /* restore the current C token */
1316 next();
1318 cstr_free(&astr);
1319 nocode_wanted = saved_nocode_wanted;
1321 #endif /* CONFIG_TCC_ASM */